babylon.no-module.max.js 5.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989
  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. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  450. var preparedSourceCode = this._processPrecision(sourceCode);
  451. if (this._engine.webGLVersion == 1) {
  452. callback(preparedSourceCode);
  453. return;
  454. }
  455. // Already converted
  456. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  457. callback(preparedSourceCode.replace("#version 300 es", ""));
  458. return;
  459. }
  460. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  461. // Remove extensions
  462. // #extension GL_OES_standard_derivatives : enable
  463. // #extension GL_EXT_shader_texture_lod : enable
  464. // #extension GL_EXT_frag_depth : enable
  465. // #extension GL_EXT_draw_buffers : require
  466. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  467. var result = preparedSourceCode.replace(regex, "");
  468. // Migrate to GLSL v300
  469. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  470. result = result.replace(/attribute[ \t]/g, "in ");
  471. result = result.replace(/[ \t]attribute/g, " in");
  472. if (isFragment) {
  473. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  474. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  475. result = result.replace(/texture2D\s*\(/g, "texture(");
  476. result = result.replace(/textureCube\s*\(/g, "texture(");
  477. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  478. result = result.replace(/gl_FragColor/g, "glFragColor");
  479. result = result.replace(/gl_FragData/g, "glFragData");
  480. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  481. }
  482. callback(result);
  483. };
  484. Effect.prototype._processIncludes = function (sourceCode, callback) {
  485. var _this = this;
  486. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  487. var match = regex.exec(sourceCode);
  488. var returnValue = new String(sourceCode);
  489. while (match != null) {
  490. var includeFile = match[1];
  491. // Uniform declaration
  492. if (includeFile.indexOf("__decl__") !== -1) {
  493. includeFile = includeFile.replace(/__decl__/, "");
  494. if (this._engine.supportsUniformBuffers) {
  495. includeFile = includeFile.replace(/Vertex/, "Ubo");
  496. includeFile = includeFile.replace(/Fragment/, "Ubo");
  497. }
  498. includeFile = includeFile + "Declaration";
  499. }
  500. if (Effect.IncludesShadersStore[includeFile]) {
  501. // Substitution
  502. var includeContent = Effect.IncludesShadersStore[includeFile];
  503. if (match[2]) {
  504. var splits = match[3].split(",");
  505. for (var index = 0; index < splits.length; index += 2) {
  506. var source = new RegExp(splits[index], "g");
  507. var dest = splits[index + 1];
  508. includeContent = includeContent.replace(source, dest);
  509. }
  510. }
  511. if (match[4]) {
  512. var indexString = match[5];
  513. if (indexString.indexOf("..") !== -1) {
  514. var indexSplits = indexString.split("..");
  515. var minIndex = parseInt(indexSplits[0]);
  516. var maxIndex = parseInt(indexSplits[1]);
  517. var sourceIncludeContent = includeContent.slice(0);
  518. includeContent = "";
  519. if (isNaN(maxIndex)) {
  520. maxIndex = this._indexParameters[indexSplits[1]];
  521. }
  522. for (var i = minIndex; i < maxIndex; i++) {
  523. if (!this._engine.supportsUniformBuffers) {
  524. // Ubo replacement
  525. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  526. return p1 + "{X}";
  527. });
  528. }
  529. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  530. }
  531. }
  532. else {
  533. if (!this._engine.supportsUniformBuffers) {
  534. // Ubo replacement
  535. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  536. return p1 + "{X}";
  537. });
  538. }
  539. includeContent = includeContent.replace(/\{X\}/g, indexString);
  540. }
  541. }
  542. // Replace
  543. returnValue = returnValue.replace(match[0], includeContent);
  544. }
  545. else {
  546. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  547. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  548. Effect.IncludesShadersStore[includeFile] = fileContent;
  549. _this._processIncludes(returnValue, callback);
  550. });
  551. return;
  552. }
  553. match = regex.exec(sourceCode);
  554. }
  555. callback(returnValue);
  556. };
  557. Effect.prototype._processPrecision = function (source) {
  558. if (source.indexOf("precision highp float") === -1) {
  559. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  560. source = "precision mediump float;\n" + source;
  561. }
  562. else {
  563. source = "precision highp float;\n" + source;
  564. }
  565. }
  566. else {
  567. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  568. source = source.replace("precision highp float", "precision mediump float");
  569. }
  570. }
  571. return source;
  572. };
  573. /**
  574. * Recompiles the webGL program
  575. * @param vertexSourceCode The source code for the vertex shader.
  576. * @param fragmentSourceCode The source code for the fragment shader.
  577. * @param onCompiled Callback called when completed.
  578. * @param onError Callback called on error.
  579. * @hidden
  580. */
  581. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  582. var _this = this;
  583. this._isReady = false;
  584. this._vertexSourceCodeOverride = vertexSourceCode;
  585. this._fragmentSourceCodeOverride = fragmentSourceCode;
  586. this.onError = function (effect, error) {
  587. if (onError) {
  588. onError(error);
  589. }
  590. };
  591. this.onCompiled = function () {
  592. var scenes = _this.getEngine().scenes;
  593. for (var i = 0; i < scenes.length; i++) {
  594. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  595. }
  596. if (onCompiled) {
  597. onCompiled(_this._program);
  598. }
  599. };
  600. this._fallbacks = null;
  601. this._prepareEffect();
  602. };
  603. /**
  604. * Gets the uniform locations of the the specified variable names
  605. * @param names THe names of the variables to lookup.
  606. * @returns Array of locations in the same order as variable names.
  607. */
  608. Effect.prototype.getSpecificUniformLocations = function (names) {
  609. var engine = this._engine;
  610. return engine.getUniforms(this._program, names);
  611. };
  612. /**
  613. * Prepares the effect
  614. * @hidden
  615. */
  616. Effect.prototype._prepareEffect = function () {
  617. var attributesNames = this._attributesNames;
  618. var defines = this.defines;
  619. var fallbacks = this._fallbacks;
  620. this._valueCache = {};
  621. var previousProgram = this._program;
  622. try {
  623. var engine = this._engine;
  624. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  625. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  626. }
  627. else {
  628. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  629. }
  630. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  631. if (engine.supportsUniformBuffers) {
  632. for (var name in this._uniformBuffersNames) {
  633. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  634. }
  635. }
  636. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  637. this._attributes = engine.getAttributes(this._program, attributesNames);
  638. var index;
  639. for (index = 0; index < this._samplers.length; index++) {
  640. var sampler = this.getUniform(this._samplers[index]);
  641. if (sampler == null) {
  642. this._samplers.splice(index, 1);
  643. index--;
  644. }
  645. }
  646. engine.bindSamplers(this);
  647. this._compilationError = "";
  648. this._isReady = true;
  649. if (this.onCompiled) {
  650. this.onCompiled(this);
  651. }
  652. this.onCompileObservable.notifyObservers(this);
  653. this.onCompileObservable.clear();
  654. // Unbind mesh reference in fallbacks
  655. if (this._fallbacks) {
  656. this._fallbacks.unBindMesh();
  657. }
  658. if (previousProgram) {
  659. this.getEngine()._deleteProgram(previousProgram);
  660. }
  661. }
  662. catch (e) {
  663. this._compilationError = e.message;
  664. // Let's go through fallbacks then
  665. BABYLON.Tools.Error("Unable to compile effect:");
  666. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  667. return " " + uniform;
  668. }));
  669. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  670. return " " + attribute;
  671. }));
  672. BABYLON.Tools.Error("Error: " + this._compilationError);
  673. if (previousProgram) {
  674. this._program = previousProgram;
  675. this._isReady = true;
  676. if (this.onError) {
  677. this.onError(this, this._compilationError);
  678. }
  679. this.onErrorObservable.notifyObservers(this);
  680. }
  681. if (fallbacks && fallbacks.isMoreFallbacks) {
  682. BABYLON.Tools.Error("Trying next fallback.");
  683. this.defines = fallbacks.reduce(this.defines, this);
  684. this._prepareEffect();
  685. }
  686. else { // Sorry we did everything we can
  687. if (this.onError) {
  688. this.onError(this, this._compilationError);
  689. }
  690. this.onErrorObservable.notifyObservers(this);
  691. this.onErrorObservable.clear();
  692. // Unbind mesh reference in fallbacks
  693. if (this._fallbacks) {
  694. this._fallbacks.unBindMesh();
  695. }
  696. }
  697. }
  698. };
  699. Object.defineProperty(Effect.prototype, "isSupported", {
  700. /**
  701. * Checks if the effect is supported. (Must be called after compilation)
  702. */
  703. get: function () {
  704. return this._compilationError === "";
  705. },
  706. enumerable: true,
  707. configurable: true
  708. });
  709. /**
  710. * Binds a texture to the engine to be used as output of the shader.
  711. * @param channel Name of the output variable.
  712. * @param texture Texture to bind.
  713. * @hidden
  714. */
  715. Effect.prototype._bindTexture = function (channel, texture) {
  716. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  717. };
  718. /**
  719. * Sets a texture on the engine to be used in the shader.
  720. * @param channel Name of the sampler variable.
  721. * @param texture Texture to set.
  722. */
  723. Effect.prototype.setTexture = function (channel, texture) {
  724. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  725. };
  726. /**
  727. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  728. * @param channel Name of the sampler variable.
  729. * @param texture Texture to set.
  730. */
  731. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  732. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  733. };
  734. /**
  735. * Sets an array of textures on the engine to be used in the shader.
  736. * @param channel Name of the variable.
  737. * @param textures Textures to set.
  738. */
  739. Effect.prototype.setTextureArray = function (channel, textures) {
  740. if (this._samplers.indexOf(channel + "Ex") === -1) {
  741. var initialPos = this._samplers.indexOf(channel);
  742. for (var index = 1; index < textures.length; index++) {
  743. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  744. }
  745. }
  746. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  747. };
  748. /**
  749. * 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)
  750. * @param channel Name of the sampler variable.
  751. * @param postProcess Post process to get the input texture from.
  752. */
  753. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  754. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  755. };
  756. /**
  757. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  758. * 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)
  759. * @param channel Name of the sampler variable.
  760. * @param postProcess Post process to get the output texture from.
  761. */
  762. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  763. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  764. };
  765. /** @hidden */
  766. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  767. var cache = this._valueCache[uniformName];
  768. var flag = matrix.updateFlag;
  769. if (cache !== undefined && cache === flag) {
  770. return false;
  771. }
  772. this._valueCache[uniformName] = flag;
  773. return true;
  774. };
  775. /** @hidden */
  776. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  777. var cache = this._valueCache[uniformName];
  778. if (!cache) {
  779. cache = [x, y];
  780. this._valueCache[uniformName] = cache;
  781. return true;
  782. }
  783. var changed = false;
  784. if (cache[0] !== x) {
  785. cache[0] = x;
  786. changed = true;
  787. }
  788. if (cache[1] !== y) {
  789. cache[1] = y;
  790. changed = true;
  791. }
  792. return changed;
  793. };
  794. /** @hidden */
  795. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  796. var cache = this._valueCache[uniformName];
  797. if (!cache) {
  798. cache = [x, y, z];
  799. this._valueCache[uniformName] = cache;
  800. return true;
  801. }
  802. var changed = false;
  803. if (cache[0] !== x) {
  804. cache[0] = x;
  805. changed = true;
  806. }
  807. if (cache[1] !== y) {
  808. cache[1] = y;
  809. changed = true;
  810. }
  811. if (cache[2] !== z) {
  812. cache[2] = z;
  813. changed = true;
  814. }
  815. return changed;
  816. };
  817. /** @hidden */
  818. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  819. var cache = this._valueCache[uniformName];
  820. if (!cache) {
  821. cache = [x, y, z, w];
  822. this._valueCache[uniformName] = cache;
  823. return true;
  824. }
  825. var changed = false;
  826. if (cache[0] !== x) {
  827. cache[0] = x;
  828. changed = true;
  829. }
  830. if (cache[1] !== y) {
  831. cache[1] = y;
  832. changed = true;
  833. }
  834. if (cache[2] !== z) {
  835. cache[2] = z;
  836. changed = true;
  837. }
  838. if (cache[3] !== w) {
  839. cache[3] = w;
  840. changed = true;
  841. }
  842. return changed;
  843. };
  844. /**
  845. * Binds a buffer to a uniform.
  846. * @param buffer Buffer to bind.
  847. * @param name Name of the uniform variable to bind to.
  848. */
  849. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  850. var bufferName = this._uniformBuffersNames[name];
  851. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  852. return;
  853. }
  854. Effect._baseCache[bufferName] = buffer;
  855. this._engine.bindUniformBufferBase(buffer, bufferName);
  856. };
  857. /**
  858. * Binds block to a uniform.
  859. * @param blockName Name of the block to bind.
  860. * @param index Index to bind.
  861. */
  862. Effect.prototype.bindUniformBlock = function (blockName, index) {
  863. this._engine.bindUniformBlock(this._program, blockName, index);
  864. };
  865. /**
  866. * Sets an interger value on a uniform variable.
  867. * @param uniformName Name of the variable.
  868. * @param value Value to be set.
  869. * @returns this effect.
  870. */
  871. Effect.prototype.setInt = function (uniformName, value) {
  872. var cache = this._valueCache[uniformName];
  873. if (cache !== undefined && cache === value) {
  874. return this;
  875. }
  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. }
  1071. this._valueCache[uniformName] = value;
  1072. this._engine.setFloat(this.getUniform(uniformName), value);
  1073. return this;
  1074. };
  1075. /**
  1076. * Sets a boolean on a uniform variable.
  1077. * @param uniformName Name of the variable.
  1078. * @param bool value to be set.
  1079. * @returns this effect.
  1080. */
  1081. Effect.prototype.setBool = function (uniformName, bool) {
  1082. var cache = this._valueCache[uniformName];
  1083. if (cache !== undefined && cache === bool) {
  1084. return this;
  1085. }
  1086. this._valueCache[uniformName] = bool;
  1087. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1088. return this;
  1089. };
  1090. /**
  1091. * Sets a Vector2 on a uniform variable.
  1092. * @param uniformName Name of the variable.
  1093. * @param vector2 vector2 to be set.
  1094. * @returns this effect.
  1095. */
  1096. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1097. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1098. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1099. }
  1100. return this;
  1101. };
  1102. /**
  1103. * Sets a float2 on a uniform variable.
  1104. * @param uniformName Name of the variable.
  1105. * @param x First float in float2.
  1106. * @param y Second float in float2.
  1107. * @returns this effect.
  1108. */
  1109. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1110. if (this._cacheFloat2(uniformName, x, y)) {
  1111. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1112. }
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a Vector3 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param vector3 Value to be set.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1122. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1123. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a float3 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param x First float in float3.
  1131. * @param y Second float in float3.
  1132. * @param z Third float in float3.
  1133. * @returns this effect.
  1134. */
  1135. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1136. if (this._cacheFloat3(uniformName, x, y, z)) {
  1137. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1138. }
  1139. return this;
  1140. };
  1141. /**
  1142. * Sets a Vector4 on a uniform variable.
  1143. * @param uniformName Name of the variable.
  1144. * @param vector4 Value to be set.
  1145. * @returns this effect.
  1146. */
  1147. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1148. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1149. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1150. }
  1151. return this;
  1152. };
  1153. /**
  1154. * Sets a float4 on a uniform variable.
  1155. * @param uniformName Name of the variable.
  1156. * @param x First float in float4.
  1157. * @param y Second float in float4.
  1158. * @param z Third float in float4.
  1159. * @param w Fourth float in float4.
  1160. * @returns this effect.
  1161. */
  1162. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1163. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1164. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1165. }
  1166. return this;
  1167. };
  1168. /**
  1169. * Sets a Color3 on a uniform variable.
  1170. * @param uniformName Name of the variable.
  1171. * @param color3 Value to be set.
  1172. * @returns this effect.
  1173. */
  1174. Effect.prototype.setColor3 = function (uniformName, color3) {
  1175. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1176. this._engine.setColor3(this.getUniform(uniformName), color3);
  1177. }
  1178. return this;
  1179. };
  1180. /**
  1181. * Sets a Color4 on a uniform variable.
  1182. * @param uniformName Name of the variable.
  1183. * @param color3 Value to be set.
  1184. * @param alpha Alpha value to be set.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1188. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1189. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color4 on a uniform variable
  1195. * @param uniformName defines the name of the variable
  1196. * @param color4 defines the value to be set
  1197. * @returns this effect.
  1198. */
  1199. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1200. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1201. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1202. }
  1203. return this;
  1204. };
  1205. /**
  1206. * This function will add a new shader to the shader store
  1207. * @param name the name of the shader
  1208. * @param pixelShader optional pixel shader content
  1209. * @param vertexShader optional vertex shader content
  1210. */
  1211. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1212. if (pixelShader) {
  1213. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1214. }
  1215. if (vertexShader) {
  1216. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1217. }
  1218. };
  1219. /**
  1220. * Resets the cache of effects.
  1221. */
  1222. Effect.ResetCache = function () {
  1223. Effect._baseCache = {};
  1224. };
  1225. Effect._uniqueIdSeed = 0;
  1226. Effect._baseCache = {};
  1227. /**
  1228. * Store of each shader (The can be looked up using effect.key)
  1229. */
  1230. Effect.ShadersStore = {};
  1231. /**
  1232. * Store of each included file for a shader (The can be looked up using effect.key)
  1233. */
  1234. Effect.IncludesShadersStore = {};
  1235. return Effect;
  1236. }());
  1237. BABYLON.Effect = Effect;
  1238. })(BABYLON || (BABYLON = {}));
  1239. //# sourceMappingURL=babylon.effect.js.map
  1240. //# sourceMappingURL=babylon.types.js.map
  1241. var BABYLON;
  1242. (function (BABYLON) {
  1243. /**
  1244. * Gather the list of keyboard event types as constants.
  1245. */
  1246. var KeyboardEventTypes = /** @class */ (function () {
  1247. function KeyboardEventTypes() {
  1248. }
  1249. /**
  1250. * The keydown event is fired when a key becomes active (pressed).
  1251. */
  1252. KeyboardEventTypes.KEYDOWN = 0x01;
  1253. /**
  1254. * The keyup event is fired when a key has been released.
  1255. */
  1256. KeyboardEventTypes.KEYUP = 0x02;
  1257. return KeyboardEventTypes;
  1258. }());
  1259. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1260. /**
  1261. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1262. */
  1263. var KeyboardInfo = /** @class */ (function () {
  1264. /**
  1265. * Instantiates a new keyboard info.
  1266. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1267. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1268. * @param event Defines the related dom event
  1269. */
  1270. function KeyboardInfo(
  1271. /**
  1272. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1273. */
  1274. type,
  1275. /**
  1276. * Defines the related dom event
  1277. */
  1278. event) {
  1279. this.type = type;
  1280. this.event = event;
  1281. }
  1282. return KeyboardInfo;
  1283. }());
  1284. BABYLON.KeyboardInfo = KeyboardInfo;
  1285. /**
  1286. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1287. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1288. */
  1289. var KeyboardInfoPre = /** @class */ (function (_super) {
  1290. __extends(KeyboardInfoPre, _super);
  1291. /**
  1292. * Instantiates a new keyboard pre info.
  1293. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1294. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1295. * @param event Defines the related dom event
  1296. */
  1297. function KeyboardInfoPre(
  1298. /**
  1299. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1300. */
  1301. type,
  1302. /**
  1303. * Defines the related dom event
  1304. */
  1305. event) {
  1306. var _this = _super.call(this, type, event) || this;
  1307. _this.type = type;
  1308. _this.event = event;
  1309. _this.skipOnPointerObservable = false;
  1310. return _this;
  1311. }
  1312. return KeyboardInfoPre;
  1313. }(KeyboardInfo));
  1314. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1315. })(BABYLON || (BABYLON = {}));
  1316. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1317. var BABYLON;
  1318. (function (BABYLON) {
  1319. /**
  1320. * Gather the list of pointer event types as constants.
  1321. */
  1322. var PointerEventTypes = /** @class */ (function () {
  1323. function PointerEventTypes() {
  1324. }
  1325. /**
  1326. * The pointerdown event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer.
  1327. */
  1328. PointerEventTypes.POINTERDOWN = 0x01;
  1329. /**
  1330. * The pointerup event is fired when a pointer is no longer active.
  1331. */
  1332. PointerEventTypes.POINTERUP = 0x02;
  1333. /**
  1334. * The pointermove event is fired when a pointer changes coordinates.
  1335. */
  1336. PointerEventTypes.POINTERMOVE = 0x04;
  1337. /**
  1338. * The pointerwheel event is fired when a mouse wheel has been rotated.
  1339. */
  1340. PointerEventTypes.POINTERWHEEL = 0x08;
  1341. /**
  1342. * The pointerpick event is fired when a mesh or sprite has been picked by the pointer.
  1343. */
  1344. PointerEventTypes.POINTERPICK = 0x10;
  1345. /**
  1346. * The pointertap event is fired when a the object has been touched and released without drag.
  1347. */
  1348. PointerEventTypes.POINTERTAP = 0x20;
  1349. /**
  1350. * The pointerdoubletap event is fired when a the object has been touched and released twice without drag.
  1351. */
  1352. PointerEventTypes.POINTERDOUBLETAP = 0x40;
  1353. return PointerEventTypes;
  1354. }());
  1355. BABYLON.PointerEventTypes = PointerEventTypes;
  1356. /**
  1357. * Base class of pointer info types.
  1358. */
  1359. var PointerInfoBase = /** @class */ (function () {
  1360. /**
  1361. * Instantiates the base class of pointers info.
  1362. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1363. * @param event Defines the related dom event
  1364. */
  1365. function PointerInfoBase(
  1366. /**
  1367. * Defines the type of event (BABYLON.PointerEventTypes)
  1368. */
  1369. type,
  1370. /**
  1371. * Defines the related dom event
  1372. */
  1373. event) {
  1374. this.type = type;
  1375. this.event = event;
  1376. }
  1377. return PointerInfoBase;
  1378. }());
  1379. BABYLON.PointerInfoBase = PointerInfoBase;
  1380. /**
  1381. * This class is used to store pointer related info for the onPrePointerObservable event.
  1382. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1383. */
  1384. var PointerInfoPre = /** @class */ (function (_super) {
  1385. __extends(PointerInfoPre, _super);
  1386. /**
  1387. * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.
  1388. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1389. * @param event Defines the related dom event
  1390. * @param localX Defines the local x coordinates of the pointer when the event occured
  1391. * @param localY Defines the local y coordinates of the pointer when the event occured
  1392. */
  1393. function PointerInfoPre(type, event, localX, localY) {
  1394. var _this = _super.call(this, type, event) || this;
  1395. /**
  1396. * Ray from a pointer if availible (eg. 6dof controller)
  1397. */
  1398. _this.ray = null;
  1399. _this.skipOnPointerObservable = false;
  1400. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1401. return _this;
  1402. }
  1403. return PointerInfoPre;
  1404. }(PointerInfoBase));
  1405. BABYLON.PointerInfoPre = PointerInfoPre;
  1406. /**
  1407. * This type contains all the data related to a pointer event in Babylon.js.
  1408. * 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.
  1409. */
  1410. var PointerInfo = /** @class */ (function (_super) {
  1411. __extends(PointerInfo, _super);
  1412. /**
  1413. * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.
  1414. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1415. * @param event Defines the related dom event
  1416. * @param pickInfo Defines the picking info associated to the info (if any)\
  1417. */
  1418. function PointerInfo(type, event,
  1419. /**
  1420. * Defines the picking info associated to the info (if any)\
  1421. */
  1422. pickInfo) {
  1423. var _this = _super.call(this, type, event) || this;
  1424. _this.pickInfo = pickInfo;
  1425. return _this;
  1426. }
  1427. return PointerInfo;
  1428. }(PointerInfoBase));
  1429. BABYLON.PointerInfo = PointerInfo;
  1430. })(BABYLON || (BABYLON = {}));
  1431. //# sourceMappingURL=babylon.pointerEvents.js.map
  1432. var BABYLON;
  1433. (function (BABYLON) {
  1434. /**
  1435. * Constant used to convert a value to gamma space
  1436. * @ignorenaming
  1437. */
  1438. BABYLON.ToGammaSpace = 1 / 2.2;
  1439. /**
  1440. * Constant used to convert a value to linear space
  1441. * @ignorenaming
  1442. */
  1443. BABYLON.ToLinearSpace = 2.2;
  1444. /**
  1445. * Constant used to define the minimal number value in Babylon.js
  1446. * @ignorenaming
  1447. */
  1448. BABYLON.Epsilon = 0.001;
  1449. /**
  1450. * Class used to hold a RBG color
  1451. */
  1452. var Color3 = /** @class */ (function () {
  1453. /**
  1454. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1455. * @param r defines the red component (between 0 and 1, default is 0)
  1456. * @param g defines the green component (between 0 and 1, default is 0)
  1457. * @param b defines the blue component (between 0 and 1, default is 0)
  1458. */
  1459. function Color3(
  1460. /**
  1461. * Defines the red component (between 0 and 1, default is 0)
  1462. */
  1463. r,
  1464. /**
  1465. * Defines the green component (between 0 and 1, default is 0)
  1466. */
  1467. g,
  1468. /**
  1469. * Defines the blue component (between 0 and 1, default is 0)
  1470. */
  1471. b) {
  1472. if (r === void 0) { r = 0; }
  1473. if (g === void 0) { g = 0; }
  1474. if (b === void 0) { b = 0; }
  1475. this.r = r;
  1476. this.g = g;
  1477. this.b = b;
  1478. }
  1479. /**
  1480. * Creates a string with the Color3 current values
  1481. * @returns the string representation of the Color3 object
  1482. */
  1483. Color3.prototype.toString = function () {
  1484. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1485. };
  1486. /**
  1487. * Returns the string "Color3"
  1488. * @returns "Color3"
  1489. */
  1490. Color3.prototype.getClassName = function () {
  1491. return "Color3";
  1492. };
  1493. /**
  1494. * Compute the Color3 hash code
  1495. * @returns an unique number that can be used to hash Color3 objects
  1496. */
  1497. Color3.prototype.getHashCode = function () {
  1498. var hash = this.r || 0;
  1499. hash = (hash * 397) ^ (this.g || 0);
  1500. hash = (hash * 397) ^ (this.b || 0);
  1501. return hash;
  1502. };
  1503. // Operators
  1504. /**
  1505. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1506. * @param array defines the array where to store the r,g,b components
  1507. * @param index defines an optional index in the target array to define where to start storing values
  1508. * @returns the current Color3 object
  1509. */
  1510. Color3.prototype.toArray = function (array, index) {
  1511. if (index === undefined) {
  1512. index = 0;
  1513. }
  1514. array[index] = this.r;
  1515. array[index + 1] = this.g;
  1516. array[index + 2] = this.b;
  1517. return this;
  1518. };
  1519. /**
  1520. * Returns a new Color4 object from the current Color3 and the given alpha
  1521. * @param alpha defines the alpha component on the new Color4 object (default is 1)
  1522. * @returns a new Color4 object
  1523. */
  1524. Color3.prototype.toColor4 = function (alpha) {
  1525. if (alpha === void 0) { alpha = 1; }
  1526. return new Color4(this.r, this.g, this.b, alpha);
  1527. };
  1528. /**
  1529. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1530. * @returns the new array
  1531. */
  1532. Color3.prototype.asArray = function () {
  1533. var result = new Array();
  1534. this.toArray(result, 0);
  1535. return result;
  1536. };
  1537. /**
  1538. * Returns the luminance value
  1539. * @returns a float value
  1540. */
  1541. Color3.prototype.toLuminance = function () {
  1542. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1543. };
  1544. /**
  1545. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1546. * @param otherColor defines the second operand
  1547. * @returns the new Color3 object
  1548. */
  1549. Color3.prototype.multiply = function (otherColor) {
  1550. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1551. };
  1552. /**
  1553. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1554. * @param otherColor defines the second operand
  1555. * @param result defines the Color3 object where to store the result
  1556. * @returns the current Color3
  1557. */
  1558. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1559. result.r = this.r * otherColor.r;
  1560. result.g = this.g * otherColor.g;
  1561. result.b = this.b * otherColor.b;
  1562. return this;
  1563. };
  1564. /**
  1565. * Determines equality between Color3 objects
  1566. * @param otherColor defines the second operand
  1567. * @returns true if the rgb values are equal to the given ones
  1568. */
  1569. Color3.prototype.equals = function (otherColor) {
  1570. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1571. };
  1572. /**
  1573. * Determines equality between the current Color3 object and a set of r,b,g values
  1574. * @param r defines the red component to check
  1575. * @param g defines the green component to check
  1576. * @param b defines the blue component to check
  1577. * @returns true if the rgb values are equal to the given ones
  1578. */
  1579. Color3.prototype.equalsFloats = function (r, g, b) {
  1580. return this.r === r && this.g === g && this.b === b;
  1581. };
  1582. /**
  1583. * Multiplies in place each rgb value by scale
  1584. * @param scale defines the scaling factor
  1585. * @returns the updated Color3
  1586. */
  1587. Color3.prototype.scale = function (scale) {
  1588. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1589. };
  1590. /**
  1591. * Multiplies the rgb values by scale and stores the result into "result"
  1592. * @param scale defines the scaling factor
  1593. * @param result defines the Color3 object where to store the result
  1594. * @returns the unmodified current Color3
  1595. */
  1596. Color3.prototype.scaleToRef = function (scale, result) {
  1597. result.r = this.r * scale;
  1598. result.g = this.g * scale;
  1599. result.b = this.b * scale;
  1600. return this;
  1601. };
  1602. /**
  1603. * Scale the current Color3 values by a factor and add the result to a given Color3
  1604. * @param scale defines the scale factor
  1605. * @param result defines color to store the result into
  1606. * @returns the unmodified current Color3
  1607. */
  1608. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1609. result.r += this.r * scale;
  1610. result.g += this.g * scale;
  1611. result.b += this.b * scale;
  1612. return this;
  1613. };
  1614. /**
  1615. * Clamps the rgb values by the min and max values and stores the result into "result"
  1616. * @param min defines minimum clamping value (default is 0)
  1617. * @param max defines maximum clamping value (default is 1)
  1618. * @param result defines color to store the result into
  1619. * @returns the original Color3
  1620. */
  1621. Color3.prototype.clampToRef = function (min, max, result) {
  1622. if (min === void 0) { min = 0; }
  1623. if (max === void 0) { max = 1; }
  1624. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1625. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1626. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1627. return this;
  1628. };
  1629. /**
  1630. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1631. * @param otherColor defines the second operand
  1632. * @returns the new Color3
  1633. */
  1634. Color3.prototype.add = function (otherColor) {
  1635. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1636. };
  1637. /**
  1638. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1639. * @param otherColor defines the second operand
  1640. * @param result defines Color3 object to store the result into
  1641. * @returns the unmodified current Color3
  1642. */
  1643. Color3.prototype.addToRef = function (otherColor, result) {
  1644. result.r = this.r + otherColor.r;
  1645. result.g = this.g + otherColor.g;
  1646. result.b = this.b + otherColor.b;
  1647. return this;
  1648. };
  1649. /**
  1650. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1651. * @param otherColor defines the second operand
  1652. * @returns the new Color3
  1653. */
  1654. Color3.prototype.subtract = function (otherColor) {
  1655. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1656. };
  1657. /**
  1658. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1659. * @param otherColor defines the second operand
  1660. * @param result defines Color3 object to store the result into
  1661. * @returns the unmodified current Color3
  1662. */
  1663. Color3.prototype.subtractToRef = function (otherColor, result) {
  1664. result.r = this.r - otherColor.r;
  1665. result.g = this.g - otherColor.g;
  1666. result.b = this.b - otherColor.b;
  1667. return this;
  1668. };
  1669. /**
  1670. * Copy the current object
  1671. * @returns a new Color3 copied the current one
  1672. */
  1673. Color3.prototype.clone = function () {
  1674. return new Color3(this.r, this.g, this.b);
  1675. };
  1676. /**
  1677. * Copies the rgb values from the source in the current Color3
  1678. * @param source defines the source Color3 object
  1679. * @returns the updated Color3 object
  1680. */
  1681. Color3.prototype.copyFrom = function (source) {
  1682. this.r = source.r;
  1683. this.g = source.g;
  1684. this.b = source.b;
  1685. return this;
  1686. };
  1687. /**
  1688. * Updates the Color3 rgb values from the given floats
  1689. * @param r defines the red component to read from
  1690. * @param g defines the green component to read from
  1691. * @param b defines the blue component to read from
  1692. * @returns the current Color3 object
  1693. */
  1694. Color3.prototype.copyFromFloats = function (r, g, b) {
  1695. this.r = r;
  1696. this.g = g;
  1697. this.b = b;
  1698. return this;
  1699. };
  1700. /**
  1701. * Updates the Color3 rgb values from the given floats
  1702. * @param r defines the red component to read from
  1703. * @param g defines the green component to read from
  1704. * @param b defines the blue component to read from
  1705. * @returns the current Color3 object
  1706. */
  1707. Color3.prototype.set = function (r, g, b) {
  1708. return this.copyFromFloats(r, g, b);
  1709. };
  1710. /**
  1711. * Compute the Color3 hexadecimal code as a string
  1712. * @returns a string containing the hexadecimal representation of the Color3 object
  1713. */
  1714. Color3.prototype.toHexString = function () {
  1715. var intR = (this.r * 255) | 0;
  1716. var intG = (this.g * 255) | 0;
  1717. var intB = (this.b * 255) | 0;
  1718. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1719. };
  1720. /**
  1721. * Computes a new Color3 converted from the current one to linear space
  1722. * @returns a new Color3 object
  1723. */
  1724. Color3.prototype.toLinearSpace = function () {
  1725. var convertedColor = new Color3();
  1726. this.toLinearSpaceToRef(convertedColor);
  1727. return convertedColor;
  1728. };
  1729. /**
  1730. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1731. * @param convertedColor defines the Color3 object where to store the linear space version
  1732. * @returns the unmodified Color3
  1733. */
  1734. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1735. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1736. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1737. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1738. return this;
  1739. };
  1740. /**
  1741. * Computes a new Color3 converted from the current one to gamma space
  1742. * @returns a new Color3 object
  1743. */
  1744. Color3.prototype.toGammaSpace = function () {
  1745. var convertedColor = new Color3();
  1746. this.toGammaSpaceToRef(convertedColor);
  1747. return convertedColor;
  1748. };
  1749. /**
  1750. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1751. * @param convertedColor defines the Color3 object where to store the gamma space version
  1752. * @returns the unmodified Color3
  1753. */
  1754. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1755. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1756. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1757. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1758. return this;
  1759. };
  1760. // Statics
  1761. /**
  1762. * Creates a new Color3 from the string containing valid hexadecimal values
  1763. * @param hex defines a string containing valid hexadecimal values
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.FromHexString = function (hex) {
  1767. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1768. return new Color3(0, 0, 0);
  1769. }
  1770. var r = parseInt(hex.substring(1, 3), 16);
  1771. var g = parseInt(hex.substring(3, 5), 16);
  1772. var b = parseInt(hex.substring(5, 7), 16);
  1773. return Color3.FromInts(r, g, b);
  1774. };
  1775. /**
  1776. * Creates a new Vector3 from the starting index of the given array
  1777. * @param array defines the source array
  1778. * @param offset defines an offset in the source array
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.FromArray = function (array, offset) {
  1782. if (offset === void 0) { offset = 0; }
  1783. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1784. };
  1785. /**
  1786. * Creates a new Color3 from integer values (< 256)
  1787. * @param r defines the red component to read from (value between 0 and 255)
  1788. * @param g defines the green component to read from (value between 0 and 255)
  1789. * @param b defines the blue component to read from (value between 0 and 255)
  1790. * @returns a new Color3 object
  1791. */
  1792. Color3.FromInts = function (r, g, b) {
  1793. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1794. };
  1795. /**
  1796. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1797. * @param start defines the start Color3 value
  1798. * @param end defines the end Color3 value
  1799. * @param amount defines the gradient value between start and end
  1800. * @returns a new Color3 object
  1801. */
  1802. Color3.Lerp = function (start, end, amount) {
  1803. var result = new Color3(0.0, 0.0, 0.0);
  1804. Color3.LerpToRef(start, end, amount, result);
  1805. return result;
  1806. };
  1807. /**
  1808. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1809. * @param left defines the start value
  1810. * @param right defines the end value
  1811. * @param amount defines the gradient factor
  1812. * @param result defines the Color3 object where to store the result
  1813. */
  1814. Color3.LerpToRef = function (left, right, amount, result) {
  1815. result.r = left.r + ((right.r - left.r) * amount);
  1816. result.g = left.g + ((right.g - left.g) * amount);
  1817. result.b = left.b + ((right.b - left.b) * amount);
  1818. };
  1819. /**
  1820. * Returns a Color3 value containing a red color
  1821. * @returns a new Color3 object
  1822. */
  1823. Color3.Red = function () { return new Color3(1, 0, 0); };
  1824. /**
  1825. * Returns a Color3 value containing a green color
  1826. * @returns a new Color3 object
  1827. */
  1828. Color3.Green = function () { return new Color3(0, 1, 0); };
  1829. /**
  1830. * Returns a Color3 value containing a blue color
  1831. * @returns a new Color3 object
  1832. */
  1833. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1834. /**
  1835. * Returns a Color3 value containing a black color
  1836. * @returns a new Color3 object
  1837. */
  1838. Color3.Black = function () { return new Color3(0, 0, 0); };
  1839. /**
  1840. * Returns a Color3 value containing a white color
  1841. * @returns a new Color3 object
  1842. */
  1843. Color3.White = function () { return new Color3(1, 1, 1); };
  1844. /**
  1845. * Returns a Color3 value containing a purple color
  1846. * @returns a new Color3 object
  1847. */
  1848. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1849. /**
  1850. * Returns a Color3 value containing a magenta color
  1851. * @returns a new Color3 object
  1852. */
  1853. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1854. /**
  1855. * Returns a Color3 value containing a yellow color
  1856. * @returns a new Color3 object
  1857. */
  1858. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1859. /**
  1860. * Returns a Color3 value containing a gray color
  1861. * @returns a new Color3 object
  1862. */
  1863. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1864. /**
  1865. * Returns a Color3 value containing a teal color
  1866. * @returns a new Color3 object
  1867. */
  1868. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1869. /**
  1870. * Returns a Color3 value containing a random color
  1871. * @returns a new Color3 object
  1872. */
  1873. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1874. return Color3;
  1875. }());
  1876. BABYLON.Color3 = Color3;
  1877. /**
  1878. * Class used to hold a RBGA color
  1879. */
  1880. var Color4 = /** @class */ (function () {
  1881. /**
  1882. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1883. * @param r defines the red component (between 0 and 1, default is 0)
  1884. * @param g defines the green component (between 0 and 1, default is 0)
  1885. * @param b defines the blue component (between 0 and 1, default is 0)
  1886. * @param a defines the alpha component (between 0 and 1, default is 1)
  1887. */
  1888. function Color4(
  1889. /**
  1890. * Defines the red component (between 0 and 1, default is 0)
  1891. */
  1892. r,
  1893. /**
  1894. * Defines the green component (between 0 and 1, default is 0)
  1895. */
  1896. g,
  1897. /**
  1898. * Defines the blue component (between 0 and 1, default is 0)
  1899. */
  1900. b,
  1901. /**
  1902. * Defines the alpha component (between 0 and 1, default is 1)
  1903. */
  1904. a) {
  1905. if (r === void 0) { r = 0; }
  1906. if (g === void 0) { g = 0; }
  1907. if (b === void 0) { b = 0; }
  1908. if (a === void 0) { a = 1; }
  1909. this.r = r;
  1910. this.g = g;
  1911. this.b = b;
  1912. this.a = a;
  1913. }
  1914. // Operators
  1915. /**
  1916. * Adds in place the given Color4 values to the current Color4 object
  1917. * @param right defines the second operand
  1918. * @returns the current updated Color4 object
  1919. */
  1920. Color4.prototype.addInPlace = function (right) {
  1921. this.r += right.r;
  1922. this.g += right.g;
  1923. this.b += right.b;
  1924. this.a += right.a;
  1925. return this;
  1926. };
  1927. /**
  1928. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1929. * @returns the new array
  1930. */
  1931. Color4.prototype.asArray = function () {
  1932. var result = new Array();
  1933. this.toArray(result, 0);
  1934. return result;
  1935. };
  1936. /**
  1937. * Stores from the starting index in the given array the Color4 successive values
  1938. * @param array defines the array where to store the r,g,b components
  1939. * @param index defines an optional index in the target array to define where to start storing values
  1940. * @returns the current Color4 object
  1941. */
  1942. Color4.prototype.toArray = function (array, index) {
  1943. if (index === undefined) {
  1944. index = 0;
  1945. }
  1946. array[index] = this.r;
  1947. array[index + 1] = this.g;
  1948. array[index + 2] = this.b;
  1949. array[index + 3] = this.a;
  1950. return this;
  1951. };
  1952. /**
  1953. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1954. * @param right defines the second operand
  1955. * @returns a new Color4 object
  1956. */
  1957. Color4.prototype.add = function (right) {
  1958. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1959. };
  1960. /**
  1961. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1962. * @param right defines the second operand
  1963. * @returns a new Color4 object
  1964. */
  1965. Color4.prototype.subtract = function (right) {
  1966. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1967. };
  1968. /**
  1969. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1970. * @param right defines the second operand
  1971. * @param result defines the Color4 object where to store the result
  1972. * @returns the current Color4 object
  1973. */
  1974. Color4.prototype.subtractToRef = function (right, result) {
  1975. result.r = this.r - right.r;
  1976. result.g = this.g - right.g;
  1977. result.b = this.b - right.b;
  1978. result.a = this.a - right.a;
  1979. return this;
  1980. };
  1981. /**
  1982. * Creates a new Color4 with the current Color4 values multiplied by scale
  1983. * @param scale defines the scaling factor to apply
  1984. * @returns a new Color4 object
  1985. */
  1986. Color4.prototype.scale = function (scale) {
  1987. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1988. };
  1989. /**
  1990. * Multiplies the current Color4 values by scale and stores the result in "result"
  1991. * @param scale defines the scaling factor to apply
  1992. * @param result defines the Color4 object where to store the result
  1993. * @returns the current unmodified Color4
  1994. */
  1995. Color4.prototype.scaleToRef = function (scale, result) {
  1996. result.r = this.r * scale;
  1997. result.g = this.g * scale;
  1998. result.b = this.b * scale;
  1999. result.a = this.a * scale;
  2000. return this;
  2001. };
  2002. /**
  2003. * Scale the current Color4 values by a factor and add the result to a given Color4
  2004. * @param scale defines the scale factor
  2005. * @param result defines the Color4 object where to store the result
  2006. * @returns the unmodified current Color4
  2007. */
  2008. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2009. result.r += this.r * scale;
  2010. result.g += this.g * scale;
  2011. result.b += this.b * scale;
  2012. result.a += this.a * scale;
  2013. return this;
  2014. };
  2015. /**
  2016. * Clamps the rgb values by the min and max values and stores the result into "result"
  2017. * @param min defines minimum clamping value (default is 0)
  2018. * @param max defines maximum clamping value (default is 1)
  2019. * @param result defines color to store the result into.
  2020. * @returns the cuurent Color4
  2021. */
  2022. Color4.prototype.clampToRef = function (min, max, result) {
  2023. if (min === void 0) { min = 0; }
  2024. if (max === void 0) { max = 1; }
  2025. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2026. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2027. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2028. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2029. return this;
  2030. };
  2031. /**
  2032. * Multipy an Color4 value by another and return a new Color4 object
  2033. * @param color defines the Color4 value to multiply by
  2034. * @returns a new Color4 object
  2035. */
  2036. Color4.prototype.multiply = function (color) {
  2037. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2038. };
  2039. /**
  2040. * Multipy a Color4 value by another and push the result in a reference value
  2041. * @param color defines the Color4 value to multiply by
  2042. * @param result defines the Color4 to fill the result in
  2043. * @returns the result Color4
  2044. */
  2045. Color4.prototype.multiplyToRef = function (color, result) {
  2046. result.r = this.r * color.r;
  2047. result.g = this.g * color.g;
  2048. result.b = this.b * color.b;
  2049. result.a = this.a * color.a;
  2050. return result;
  2051. };
  2052. /**
  2053. * Creates a string with the Color4 current values
  2054. * @returns the string representation of the Color4 object
  2055. */
  2056. Color4.prototype.toString = function () {
  2057. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2058. };
  2059. /**
  2060. * Returns the string "Color4"
  2061. * @returns "Color4"
  2062. */
  2063. Color4.prototype.getClassName = function () {
  2064. return "Color4";
  2065. };
  2066. /**
  2067. * Compute the Color4 hash code
  2068. * @returns an unique number that can be used to hash Color4 objects
  2069. */
  2070. Color4.prototype.getHashCode = function () {
  2071. var hash = this.r || 0;
  2072. hash = (hash * 397) ^ (this.g || 0);
  2073. hash = (hash * 397) ^ (this.b || 0);
  2074. hash = (hash * 397) ^ (this.a || 0);
  2075. return hash;
  2076. };
  2077. /**
  2078. * Creates a new Color4 copied from the current one
  2079. * @returns a new Color4 object
  2080. */
  2081. Color4.prototype.clone = function () {
  2082. return new Color4(this.r, this.g, this.b, this.a);
  2083. };
  2084. /**
  2085. * Copies the given Color4 values into the current one
  2086. * @param source defines the source Color4 object
  2087. * @returns the current updated Color4 object
  2088. */
  2089. Color4.prototype.copyFrom = function (source) {
  2090. this.r = source.r;
  2091. this.g = source.g;
  2092. this.b = source.b;
  2093. this.a = source.a;
  2094. return this;
  2095. };
  2096. /**
  2097. * Copies the given float values into the current one
  2098. * @param r defines the red component to read from
  2099. * @param g defines the green component to read from
  2100. * @param b defines the blue component to read from
  2101. * @param a defines the alpha component to read from
  2102. * @returns the current updated Color4 object
  2103. */
  2104. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2105. this.r = r;
  2106. this.g = g;
  2107. this.b = b;
  2108. this.a = a;
  2109. return this;
  2110. };
  2111. /**
  2112. * Copies the given float values into the current one
  2113. * @param r defines the red component to read from
  2114. * @param g defines the green component to read from
  2115. * @param b defines the blue component to read from
  2116. * @param a defines the alpha component to read from
  2117. * @returns the current updated Color4 object
  2118. */
  2119. Color4.prototype.set = function (r, g, b, a) {
  2120. return this.copyFromFloats(r, g, b, a);
  2121. };
  2122. /**
  2123. * Compute the Color4 hexadecimal code as a string
  2124. * @returns a string containing the hexadecimal representation of the Color4 object
  2125. */
  2126. Color4.prototype.toHexString = function () {
  2127. var intR = (this.r * 255) | 0;
  2128. var intG = (this.g * 255) | 0;
  2129. var intB = (this.b * 255) | 0;
  2130. var intA = (this.a * 255) | 0;
  2131. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2132. };
  2133. /**
  2134. * Computes a new Color4 converted from the current one to linear space
  2135. * @returns a new Color4 object
  2136. */
  2137. Color4.prototype.toLinearSpace = function () {
  2138. var convertedColor = new Color4();
  2139. this.toLinearSpaceToRef(convertedColor);
  2140. return convertedColor;
  2141. };
  2142. /**
  2143. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2144. * @param convertedColor defines the Color4 object where to store the linear space version
  2145. * @returns the unmodified Color4
  2146. */
  2147. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2148. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2149. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2150. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2151. convertedColor.a = this.a;
  2152. return this;
  2153. };
  2154. /**
  2155. * Computes a new Color4 converted from the current one to gamma space
  2156. * @returns a new Color4 object
  2157. */
  2158. Color4.prototype.toGammaSpace = function () {
  2159. var convertedColor = new Color4();
  2160. this.toGammaSpaceToRef(convertedColor);
  2161. return convertedColor;
  2162. };
  2163. /**
  2164. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2165. * @param convertedColor defines the Color4 object where to store the gamma space version
  2166. * @returns the unmodified Color4
  2167. */
  2168. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2169. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2170. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2171. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2172. convertedColor.a = this.a;
  2173. return this;
  2174. };
  2175. // Statics
  2176. /**
  2177. * Creates a new Color4 from the string containing valid hexadecimal values
  2178. * @param hex defines a string containing valid hexadecimal values
  2179. * @returns a new Color4 object
  2180. */
  2181. Color4.FromHexString = function (hex) {
  2182. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2183. return new Color4(0.0, 0.0, 0.0, 0.0);
  2184. }
  2185. var r = parseInt(hex.substring(1, 3), 16);
  2186. var g = parseInt(hex.substring(3, 5), 16);
  2187. var b = parseInt(hex.substring(5, 7), 16);
  2188. var a = parseInt(hex.substring(7, 9), 16);
  2189. return Color4.FromInts(r, g, b, a);
  2190. };
  2191. /**
  2192. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2193. * @param left defines the start value
  2194. * @param right defines the end value
  2195. * @param amount defines the gradient factor
  2196. * @returns a new Color4 object
  2197. */
  2198. Color4.Lerp = function (left, right, amount) {
  2199. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2200. Color4.LerpToRef(left, right, amount, result);
  2201. return result;
  2202. };
  2203. /**
  2204. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2205. * @param left defines the start value
  2206. * @param right defines the end value
  2207. * @param amount defines the gradient factor
  2208. * @param result defines the Color4 object where to store data
  2209. */
  2210. Color4.LerpToRef = function (left, right, amount, result) {
  2211. result.r = left.r + (right.r - left.r) * amount;
  2212. result.g = left.g + (right.g - left.g) * amount;
  2213. result.b = left.b + (right.b - left.b) * amount;
  2214. result.a = left.a + (right.a - left.a) * amount;
  2215. };
  2216. /**
  2217. * Creates a new Color4 from a Color3 and an alpha value
  2218. * @param color3 defines the source Color3 to read from
  2219. * @param alpha defines the alpha component (1.0 by default)
  2220. * @returns a new Color4 object
  2221. */
  2222. Color4.FromColor3 = function (color3, alpha) {
  2223. if (alpha === void 0) { alpha = 1.0; }
  2224. return new Color4(color3.r, color3.g, color3.b, alpha);
  2225. };
  2226. /**
  2227. * Creates a new Color4 from the starting index element of the given array
  2228. * @param array defines the source array to read from
  2229. * @param offset defines the offset in the source array
  2230. * @returns a new Color4 object
  2231. */
  2232. Color4.FromArray = function (array, offset) {
  2233. if (offset === void 0) { offset = 0; }
  2234. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2235. };
  2236. /**
  2237. * Creates a new Color3 from integer values (< 256)
  2238. * @param r defines the red component to read from (value between 0 and 255)
  2239. * @param g defines the green component to read from (value between 0 and 255)
  2240. * @param b defines the blue component to read from (value between 0 and 255)
  2241. * @param a defines the alpha component to read from (value between 0 and 255)
  2242. * @returns a new Color3 object
  2243. */
  2244. Color4.FromInts = function (r, g, b, a) {
  2245. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2246. };
  2247. /**
  2248. * Check the content of a given array and convert it to an array containing RGBA data
  2249. * If the original array was already containing count * 4 values then it is returned directly
  2250. * @param colors defines the array to check
  2251. * @param count defines the number of RGBA data to expect
  2252. * @returns an array containing count * 4 values (RGBA)
  2253. */
  2254. Color4.CheckColors4 = function (colors, count) {
  2255. // Check if color3 was used
  2256. if (colors.length === count * 3) {
  2257. var colors4 = [];
  2258. for (var index = 0; index < colors.length; index += 3) {
  2259. var newIndex = (index / 3) * 4;
  2260. colors4[newIndex] = colors[index];
  2261. colors4[newIndex + 1] = colors[index + 1];
  2262. colors4[newIndex + 2] = colors[index + 2];
  2263. colors4[newIndex + 3] = 1.0;
  2264. }
  2265. return colors4;
  2266. }
  2267. return colors;
  2268. };
  2269. return Color4;
  2270. }());
  2271. BABYLON.Color4 = Color4;
  2272. /**
  2273. * Class representing a vector containing 2 coordinates
  2274. */
  2275. var Vector2 = /** @class */ (function () {
  2276. /**
  2277. * Creates a new Vector2 from the given x and y coordinates
  2278. * @param x defines the first coordinate
  2279. * @param y defines the second coordinate
  2280. */
  2281. function Vector2(
  2282. /** defines the first coordinate */
  2283. x,
  2284. /** defines the second coordinate */
  2285. y) {
  2286. if (x === void 0) { x = 0; }
  2287. if (y === void 0) { y = 0; }
  2288. this.x = x;
  2289. this.y = y;
  2290. }
  2291. /**
  2292. * Gets a string with the Vector2 coordinates
  2293. * @returns a string with the Vector2 coordinates
  2294. */
  2295. Vector2.prototype.toString = function () {
  2296. return "{X: " + this.x + " Y:" + this.y + "}";
  2297. };
  2298. /**
  2299. * Gets class name
  2300. * @returns the string "Vector2"
  2301. */
  2302. Vector2.prototype.getClassName = function () {
  2303. return "Vector2";
  2304. };
  2305. /**
  2306. * Gets current vector hash code
  2307. * @returns the Vector2 hash code as a number
  2308. */
  2309. Vector2.prototype.getHashCode = function () {
  2310. var hash = this.x || 0;
  2311. hash = (hash * 397) ^ (this.y || 0);
  2312. return hash;
  2313. };
  2314. // Operators
  2315. /**
  2316. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2317. * @param array defines the source array
  2318. * @param index defines the offset in source array
  2319. * @returns the current Vector2
  2320. */
  2321. Vector2.prototype.toArray = function (array, index) {
  2322. if (index === void 0) { index = 0; }
  2323. array[index] = this.x;
  2324. array[index + 1] = this.y;
  2325. return this;
  2326. };
  2327. /**
  2328. * Copy the current vector to an array
  2329. * @returns a new array with 2 elements: the Vector2 coordinates.
  2330. */
  2331. Vector2.prototype.asArray = function () {
  2332. var result = new Array();
  2333. this.toArray(result, 0);
  2334. return result;
  2335. };
  2336. /**
  2337. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2338. * @param source defines the source Vector2
  2339. * @returns the current updated Vector2
  2340. */
  2341. Vector2.prototype.copyFrom = function (source) {
  2342. this.x = source.x;
  2343. this.y = source.y;
  2344. return this;
  2345. };
  2346. /**
  2347. * Sets the Vector2 coordinates with the given floats
  2348. * @param x defines the first coordinate
  2349. * @param y defines the second coordinate
  2350. * @returns the current updated Vector2
  2351. */
  2352. Vector2.prototype.copyFromFloats = function (x, y) {
  2353. this.x = x;
  2354. this.y = y;
  2355. return this;
  2356. };
  2357. /**
  2358. * Sets the Vector2 coordinates with the given floats
  2359. * @param x defines the first coordinate
  2360. * @param y defines the second coordinate
  2361. * @returns the current updated Vector2
  2362. */
  2363. Vector2.prototype.set = function (x, y) {
  2364. return this.copyFromFloats(x, y);
  2365. };
  2366. /**
  2367. * Add another vector with the current one
  2368. * @param otherVector defines the other vector
  2369. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2370. */
  2371. Vector2.prototype.add = function (otherVector) {
  2372. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2373. };
  2374. /**
  2375. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2376. * @param otherVector defines the other vector
  2377. * @param result defines the target vector
  2378. * @returns the unmodified current Vector2
  2379. */
  2380. Vector2.prototype.addToRef = function (otherVector, result) {
  2381. result.x = this.x + otherVector.x;
  2382. result.y = this.y + otherVector.y;
  2383. return this;
  2384. };
  2385. /**
  2386. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2387. * @param otherVector defines the other vector
  2388. * @returns the current updated Vector2
  2389. */
  2390. Vector2.prototype.addInPlace = function (otherVector) {
  2391. this.x += otherVector.x;
  2392. this.y += otherVector.y;
  2393. return this;
  2394. };
  2395. /**
  2396. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2397. * @param otherVector defines the other vector
  2398. * @returns a new Vector2
  2399. */
  2400. Vector2.prototype.addVector3 = function (otherVector) {
  2401. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2402. };
  2403. /**
  2404. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2405. * @param otherVector defines the other vector
  2406. * @returns a new Vector2
  2407. */
  2408. Vector2.prototype.subtract = function (otherVector) {
  2409. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2410. };
  2411. /**
  2412. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2413. * @param otherVector defines the other vector
  2414. * @param result defines the target vector
  2415. * @returns the unmodified current Vector2
  2416. */
  2417. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2418. result.x = this.x - otherVector.x;
  2419. result.y = this.y - otherVector.y;
  2420. return this;
  2421. };
  2422. /**
  2423. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2424. * @param otherVector defines the other vector
  2425. * @returns the current updated Vector2
  2426. */
  2427. Vector2.prototype.subtractInPlace = function (otherVector) {
  2428. this.x -= otherVector.x;
  2429. this.y -= otherVector.y;
  2430. return this;
  2431. };
  2432. /**
  2433. * Multiplies in place the current Vector2 coordinates by the given ones
  2434. * @param otherVector defines the other vector
  2435. * @returns the current updated Vector2
  2436. */
  2437. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2438. this.x *= otherVector.x;
  2439. this.y *= otherVector.y;
  2440. return this;
  2441. };
  2442. /**
  2443. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2444. * @param otherVector defines the other vector
  2445. * @returns a new Vector2
  2446. */
  2447. Vector2.prototype.multiply = function (otherVector) {
  2448. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2449. };
  2450. /**
  2451. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2452. * @param otherVector defines the other vector
  2453. * @param result defines the target vector
  2454. * @returns the unmodified current Vector2
  2455. */
  2456. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2457. result.x = this.x * otherVector.x;
  2458. result.y = this.y * otherVector.y;
  2459. return this;
  2460. };
  2461. /**
  2462. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2463. * @param x defines the first coordinate
  2464. * @param y defines the second coordinate
  2465. * @returns a new Vector2
  2466. */
  2467. Vector2.prototype.multiplyByFloats = function (x, y) {
  2468. return new Vector2(this.x * x, this.y * y);
  2469. };
  2470. /**
  2471. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2472. * @param otherVector defines the other vector
  2473. * @returns a new Vector2
  2474. */
  2475. Vector2.prototype.divide = function (otherVector) {
  2476. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2477. };
  2478. /**
  2479. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2480. * @param otherVector defines the other vector
  2481. * @param result defines the target vector
  2482. * @returns the unmodified current Vector2
  2483. */
  2484. Vector2.prototype.divideToRef = function (otherVector, result) {
  2485. result.x = this.x / otherVector.x;
  2486. result.y = this.y / otherVector.y;
  2487. return this;
  2488. };
  2489. /**
  2490. * Divides the current Vector2 coordinates by the given ones
  2491. * @param otherVector defines the other vector
  2492. * @returns the current updated Vector2
  2493. */
  2494. Vector2.prototype.divideInPlace = function (otherVector) {
  2495. return this.divideToRef(otherVector, this);
  2496. };
  2497. /**
  2498. * Gets a new Vector2 with current Vector2 negated coordinates
  2499. * @returns a new Vector2
  2500. */
  2501. Vector2.prototype.negate = function () {
  2502. return new Vector2(-this.x, -this.y);
  2503. };
  2504. /**
  2505. * Multiply the Vector2 coordinates by scale
  2506. * @param scale defines the scaling factor
  2507. * @returns the current updated Vector2
  2508. */
  2509. Vector2.prototype.scaleInPlace = function (scale) {
  2510. this.x *= scale;
  2511. this.y *= scale;
  2512. return this;
  2513. };
  2514. /**
  2515. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2516. * @param scale defines the scaling factor
  2517. * @returns a new Vector2
  2518. */
  2519. Vector2.prototype.scale = function (scale) {
  2520. var result = new Vector2(0, 0);
  2521. this.scaleToRef(scale, result);
  2522. return result;
  2523. };
  2524. /**
  2525. * Scale the current Vector2 values by a factor to a given Vector2
  2526. * @param scale defines the scale factor
  2527. * @param result defines the Vector2 object where to store the result
  2528. * @returns the unmodified current Vector2
  2529. */
  2530. Vector2.prototype.scaleToRef = function (scale, result) {
  2531. result.x = this.x * scale;
  2532. result.y = this.y * scale;
  2533. return this;
  2534. };
  2535. /**
  2536. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2537. * @param scale defines the scale factor
  2538. * @param result defines the Vector2 object where to store the result
  2539. * @returns the unmodified current Vector2
  2540. */
  2541. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2542. result.x += this.x * scale;
  2543. result.y += this.y * scale;
  2544. return this;
  2545. };
  2546. /**
  2547. * Gets a boolean if two vectors are equals
  2548. * @param otherVector defines the other vector
  2549. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2550. */
  2551. Vector2.prototype.equals = function (otherVector) {
  2552. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2553. };
  2554. /**
  2555. * Gets a boolean if two vectors are equals (using an epsilon value)
  2556. * @param otherVector defines the other vector
  2557. * @param epsilon defines the minimal distance to consider equality
  2558. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2559. */
  2560. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2561. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2562. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2563. };
  2564. /**
  2565. * Gets a new Vector2 from current Vector2 floored values
  2566. * @returns a new Vector2
  2567. */
  2568. Vector2.prototype.floor = function () {
  2569. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2570. };
  2571. /**
  2572. * Gets a new Vector2 from current Vector2 floored values
  2573. * @returns a new Vector2
  2574. */
  2575. Vector2.prototype.fract = function () {
  2576. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2577. };
  2578. // Properties
  2579. /**
  2580. * Gets the length of the vector
  2581. * @returns the vector length (float)
  2582. */
  2583. Vector2.prototype.length = function () {
  2584. return Math.sqrt(this.x * this.x + this.y * this.y);
  2585. };
  2586. /**
  2587. * Gets the vector squared length
  2588. * @returns the vector squared length (float)
  2589. */
  2590. Vector2.prototype.lengthSquared = function () {
  2591. return (this.x * this.x + this.y * this.y);
  2592. };
  2593. // Methods
  2594. /**
  2595. * Normalize the vector
  2596. * @returns the current updated Vector2
  2597. */
  2598. Vector2.prototype.normalize = function () {
  2599. var len = this.length();
  2600. if (len === 0) {
  2601. return this;
  2602. }
  2603. var num = 1.0 / len;
  2604. this.x *= num;
  2605. this.y *= num;
  2606. return this;
  2607. };
  2608. /**
  2609. * Gets a new Vector2 copied from the Vector2
  2610. * @returns a new Vector2
  2611. */
  2612. Vector2.prototype.clone = function () {
  2613. return new Vector2(this.x, this.y);
  2614. };
  2615. // Statics
  2616. /**
  2617. * Gets a new Vector2(0, 0)
  2618. * @returns a new Vector2
  2619. */
  2620. Vector2.Zero = function () {
  2621. return new Vector2(0, 0);
  2622. };
  2623. /**
  2624. * Gets a new Vector2(1, 1)
  2625. * @returns a new Vector2
  2626. */
  2627. Vector2.One = function () {
  2628. return new Vector2(1, 1);
  2629. };
  2630. /**
  2631. * Gets a new Vector2 set from the given index element of the given array
  2632. * @param array defines the data source
  2633. * @param offset defines the offset in the data source
  2634. * @returns a new Vector2
  2635. */
  2636. Vector2.FromArray = function (array, offset) {
  2637. if (offset === void 0) { offset = 0; }
  2638. return new Vector2(array[offset], array[offset + 1]);
  2639. };
  2640. /**
  2641. * Sets "result" from the given index element of the given array
  2642. * @param array defines the data source
  2643. * @param offset defines the offset in the data source
  2644. * @param result defines the target vector
  2645. */
  2646. Vector2.FromArrayToRef = function (array, offset, result) {
  2647. result.x = array[offset];
  2648. result.y = array[offset + 1];
  2649. };
  2650. /**
  2651. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2652. * @param value1 defines 1st point of control
  2653. * @param value2 defines 2nd point of control
  2654. * @param value3 defines 3rd point of control
  2655. * @param value4 defines 4th point of control
  2656. * @param amount defines the interpolation factor
  2657. * @returns a new Vector2
  2658. */
  2659. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2660. var squared = amount * amount;
  2661. var cubed = amount * squared;
  2662. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2663. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2664. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2665. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2666. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2667. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2668. return new Vector2(x, y);
  2669. };
  2670. /**
  2671. * 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".
  2672. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2673. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2674. * @param value defines the value to clamp
  2675. * @param min defines the lower limit
  2676. * @param max defines the upper limit
  2677. * @returns a new Vector2
  2678. */
  2679. Vector2.Clamp = function (value, min, max) {
  2680. var x = value.x;
  2681. x = (x > max.x) ? max.x : x;
  2682. x = (x < min.x) ? min.x : x;
  2683. var y = value.y;
  2684. y = (y > max.y) ? max.y : y;
  2685. y = (y < min.y) ? min.y : y;
  2686. return new Vector2(x, y);
  2687. };
  2688. /**
  2689. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2690. * @param value1 defines the 1st control point
  2691. * @param tangent1 defines the outgoing tangent
  2692. * @param value2 defines the 2nd control point
  2693. * @param tangent2 defines the incoming tangent
  2694. * @param amount defines the interpolation factor
  2695. * @returns a new Vector2
  2696. */
  2697. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2698. var squared = amount * amount;
  2699. var cubed = amount * squared;
  2700. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2701. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2702. var part3 = (cubed - (2.0 * squared)) + amount;
  2703. var part4 = cubed - squared;
  2704. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2705. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2706. return new Vector2(x, y);
  2707. };
  2708. /**
  2709. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2710. * @param start defines the start vector
  2711. * @param end defines the end vector
  2712. * @param amount defines the interpolation factor
  2713. * @returns a new Vector2
  2714. */
  2715. Vector2.Lerp = function (start, end, amount) {
  2716. var x = start.x + ((end.x - start.x) * amount);
  2717. var y = start.y + ((end.y - start.y) * amount);
  2718. return new Vector2(x, y);
  2719. };
  2720. /**
  2721. * Gets the dot product of the vector "left" and the vector "right"
  2722. * @param left defines first vector
  2723. * @param right defines second vector
  2724. * @returns the dot product (float)
  2725. */
  2726. Vector2.Dot = function (left, right) {
  2727. return left.x * right.x + left.y * right.y;
  2728. };
  2729. /**
  2730. * Returns a new Vector2 equal to the normalized given vector
  2731. * @param vector defines the vector to normalize
  2732. * @returns a new Vector2
  2733. */
  2734. Vector2.Normalize = function (vector) {
  2735. var newVector = vector.clone();
  2736. newVector.normalize();
  2737. return newVector;
  2738. };
  2739. /**
  2740. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2741. * @param left defines 1st vector
  2742. * @param right defines 2nd vector
  2743. * @returns a new Vector2
  2744. */
  2745. Vector2.Minimize = function (left, right) {
  2746. var x = (left.x < right.x) ? left.x : right.x;
  2747. var y = (left.y < right.y) ? left.y : right.y;
  2748. return new Vector2(x, y);
  2749. };
  2750. /**
  2751. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2752. * @param left defines 1st vector
  2753. * @param right defines 2nd vector
  2754. * @returns a new Vector2
  2755. */
  2756. Vector2.Maximize = function (left, right) {
  2757. var x = (left.x > right.x) ? left.x : right.x;
  2758. var y = (left.y > right.y) ? left.y : right.y;
  2759. return new Vector2(x, y);
  2760. };
  2761. /**
  2762. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2763. * @param vector defines the vector to transform
  2764. * @param transformation defines the matrix to apply
  2765. * @returns a new Vector2
  2766. */
  2767. Vector2.Transform = function (vector, transformation) {
  2768. var r = Vector2.Zero();
  2769. Vector2.TransformToRef(vector, transformation, r);
  2770. return r;
  2771. };
  2772. /**
  2773. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2774. * @param vector defines the vector to transform
  2775. * @param transformation defines the matrix to apply
  2776. * @param result defines the target vector
  2777. */
  2778. Vector2.TransformToRef = function (vector, transformation, result) {
  2779. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2780. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2781. result.x = x;
  2782. result.y = y;
  2783. };
  2784. /**
  2785. * Determines if a given vector is included in a triangle
  2786. * @param p defines the vector to test
  2787. * @param p0 defines 1st triangle point
  2788. * @param p1 defines 2nd triangle point
  2789. * @param p2 defines 3rd triangle point
  2790. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2791. */
  2792. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2793. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2794. var sign = a < 0 ? -1 : 1;
  2795. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2796. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2797. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2798. };
  2799. /**
  2800. * Gets the distance between the vectors "value1" and "value2"
  2801. * @param value1 defines first vector
  2802. * @param value2 defines second vector
  2803. * @returns the distance between vectors
  2804. */
  2805. Vector2.Distance = function (value1, value2) {
  2806. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2807. };
  2808. /**
  2809. * Returns the squared distance between the vectors "value1" and "value2"
  2810. * @param value1 defines first vector
  2811. * @param value2 defines second vector
  2812. * @returns the squared distance between vectors
  2813. */
  2814. Vector2.DistanceSquared = function (value1, value2) {
  2815. var x = value1.x - value2.x;
  2816. var y = value1.y - value2.y;
  2817. return (x * x) + (y * y);
  2818. };
  2819. /**
  2820. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2821. * @param value1 defines first vector
  2822. * @param value2 defines second vector
  2823. * @returns a new Vector2
  2824. */
  2825. Vector2.Center = function (value1, value2) {
  2826. var center = value1.add(value2);
  2827. center.scaleInPlace(0.5);
  2828. return center;
  2829. };
  2830. /**
  2831. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2832. * @param p defines the middle point
  2833. * @param segA defines one point of the segment
  2834. * @param segB defines the other point of the segment
  2835. * @returns the shortest distance
  2836. */
  2837. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2838. var l2 = Vector2.DistanceSquared(segA, segB);
  2839. if (l2 === 0.0) {
  2840. return Vector2.Distance(p, segA);
  2841. }
  2842. var v = segB.subtract(segA);
  2843. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2844. var proj = segA.add(v.multiplyByFloats(t, t));
  2845. return Vector2.Distance(p, proj);
  2846. };
  2847. return Vector2;
  2848. }());
  2849. BABYLON.Vector2 = Vector2;
  2850. /**
  2851. * Classed used to store (x,y,z) vector representation
  2852. * A Vector3 is the main object used in 3D geometry
  2853. * It can represent etiher the coordinates of a point the space, either a direction
  2854. * Reminder: Babylon.js uses a left handed forward facing system
  2855. */
  2856. var Vector3 = /** @class */ (function () {
  2857. /**
  2858. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2859. * @param x defines the first coordinates (on X axis)
  2860. * @param y defines the second coordinates (on Y axis)
  2861. * @param z defines the third coordinates (on Z axis)
  2862. */
  2863. function Vector3(
  2864. /**
  2865. * Defines the first coordinates (on X axis)
  2866. */
  2867. x,
  2868. /**
  2869. * Defines the second coordinates (on Y axis)
  2870. */
  2871. y,
  2872. /**
  2873. * Defines the third coordinates (on Z axis)
  2874. */
  2875. z) {
  2876. if (x === void 0) { x = 0; }
  2877. if (y === void 0) { y = 0; }
  2878. if (z === void 0) { z = 0; }
  2879. this.x = x;
  2880. this.y = y;
  2881. this.z = z;
  2882. }
  2883. /**
  2884. * Creates a string representation of the Vector3
  2885. * @returns a string with the Vector3 coordinates.
  2886. */
  2887. Vector3.prototype.toString = function () {
  2888. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2889. };
  2890. /**
  2891. * Gets the class name
  2892. * @returns the string "Vector3"
  2893. */
  2894. Vector3.prototype.getClassName = function () {
  2895. return "Vector3";
  2896. };
  2897. /**
  2898. * Creates the Vector3 hash code
  2899. * @returns a number which tends to be unique between Vector3 instances
  2900. */
  2901. Vector3.prototype.getHashCode = function () {
  2902. var hash = this.x || 0;
  2903. hash = (hash * 397) ^ (this.y || 0);
  2904. hash = (hash * 397) ^ (this.z || 0);
  2905. return hash;
  2906. };
  2907. // Operators
  2908. /**
  2909. * Creates an array containing three elements : the coordinates of the Vector3
  2910. * @returns a new array of numbers
  2911. */
  2912. Vector3.prototype.asArray = function () {
  2913. var result = [];
  2914. this.toArray(result, 0);
  2915. return result;
  2916. };
  2917. /**
  2918. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2919. * @param array defines the destination array
  2920. * @param index defines the offset in the destination array
  2921. * @returns the current Vector3
  2922. */
  2923. Vector3.prototype.toArray = function (array, index) {
  2924. if (index === void 0) { index = 0; }
  2925. array[index] = this.x;
  2926. array[index + 1] = this.y;
  2927. array[index + 2] = this.z;
  2928. return this;
  2929. };
  2930. /**
  2931. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2932. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2933. */
  2934. Vector3.prototype.toQuaternion = function () {
  2935. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2936. };
  2937. /**
  2938. * Adds the given vector to the current Vector3
  2939. * @param otherVector defines the second operand
  2940. * @returns the current updated Vector3
  2941. */
  2942. Vector3.prototype.addInPlace = function (otherVector) {
  2943. this.x += otherVector.x;
  2944. this.y += otherVector.y;
  2945. this.z += otherVector.z;
  2946. return this;
  2947. };
  2948. /**
  2949. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2950. * @param otherVector defines the second operand
  2951. * @returns the resulting Vector3
  2952. */
  2953. Vector3.prototype.add = function (otherVector) {
  2954. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2955. };
  2956. /**
  2957. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2958. * @param otherVector defines the second operand
  2959. * @param result defines the Vector3 object where to store the result
  2960. * @returns the current Vector3
  2961. */
  2962. Vector3.prototype.addToRef = function (otherVector, result) {
  2963. result.x = this.x + otherVector.x;
  2964. result.y = this.y + otherVector.y;
  2965. result.z = this.z + otherVector.z;
  2966. return this;
  2967. };
  2968. /**
  2969. * Subtract the given vector from the current Vector3
  2970. * @param otherVector defines the second operand
  2971. * @returns the current updated Vector3
  2972. */
  2973. Vector3.prototype.subtractInPlace = function (otherVector) {
  2974. this.x -= otherVector.x;
  2975. this.y -= otherVector.y;
  2976. this.z -= otherVector.z;
  2977. return this;
  2978. };
  2979. /**
  2980. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2981. * @param otherVector defines the second operand
  2982. * @returns the resulting Vector3
  2983. */
  2984. Vector3.prototype.subtract = function (otherVector) {
  2985. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2986. };
  2987. /**
  2988. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2989. * @param otherVector defines the second operand
  2990. * @param result defines the Vector3 object where to store the result
  2991. * @returns the current Vector3
  2992. */
  2993. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2994. result.x = this.x - otherVector.x;
  2995. result.y = this.y - otherVector.y;
  2996. result.z = this.z - otherVector.z;
  2997. return this;
  2998. };
  2999. /**
  3000. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  3001. * @param x defines the x coordinate of the operand
  3002. * @param y defines the y coordinate of the operand
  3003. * @param z defines the z coordinate of the operand
  3004. * @returns the resulting Vector3
  3005. */
  3006. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  3007. return new Vector3(this.x - x, this.y - y, this.z - z);
  3008. };
  3009. /**
  3010. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  3011. * @param x defines the x coordinate of the operand
  3012. * @param y defines the y coordinate of the operand
  3013. * @param z defines the z coordinate of the operand
  3014. * @param result defines the Vector3 object where to store the result
  3015. * @returns the current Vector3
  3016. */
  3017. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3018. result.x = this.x - x;
  3019. result.y = this.y - y;
  3020. result.z = this.z - z;
  3021. return this;
  3022. };
  3023. /**
  3024. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3025. * @returns a new Vector3
  3026. */
  3027. Vector3.prototype.negate = function () {
  3028. return new Vector3(-this.x, -this.y, -this.z);
  3029. };
  3030. /**
  3031. * Multiplies the Vector3 coordinates by the float "scale"
  3032. * @param scale defines the multiplier factor
  3033. * @returns the current updated Vector3
  3034. */
  3035. Vector3.prototype.scaleInPlace = function (scale) {
  3036. this.x *= scale;
  3037. this.y *= scale;
  3038. this.z *= scale;
  3039. return this;
  3040. };
  3041. /**
  3042. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3043. * @param scale defines the multiplier factor
  3044. * @returns a new Vector3
  3045. */
  3046. Vector3.prototype.scale = function (scale) {
  3047. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3048. };
  3049. /**
  3050. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3051. * @param scale defines the multiplier factor
  3052. * @param result defines the Vector3 object where to store the result
  3053. * @returns the current Vector3
  3054. */
  3055. Vector3.prototype.scaleToRef = function (scale, result) {
  3056. result.x = this.x * scale;
  3057. result.y = this.y * scale;
  3058. result.z = this.z * scale;
  3059. return this;
  3060. };
  3061. /**
  3062. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3063. * @param scale defines the scale factor
  3064. * @param result defines the Vector3 object where to store the result
  3065. * @returns the unmodified current Vector3
  3066. */
  3067. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3068. result.x += this.x * scale;
  3069. result.y += this.y * scale;
  3070. result.z += this.z * scale;
  3071. return this;
  3072. };
  3073. /**
  3074. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3075. * @param otherVector defines the second operand
  3076. * @returns true if both vectors are equals
  3077. */
  3078. Vector3.prototype.equals = function (otherVector) {
  3079. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3080. };
  3081. /**
  3082. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3083. * @param otherVector defines the second operand
  3084. * @param epsilon defines the minimal distance to define values as equals
  3085. * @returns true if both vectors are distant less than epsilon
  3086. */
  3087. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3088. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3089. 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);
  3090. };
  3091. /**
  3092. * Returns true if the current Vector3 coordinates equals the given floats
  3093. * @param x defines the x coordinate of the operand
  3094. * @param y defines the y coordinate of the operand
  3095. * @param z defines the z coordinate of the operand
  3096. * @returns true if both vectors are equals
  3097. */
  3098. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3099. return this.x === x && this.y === y && this.z === z;
  3100. };
  3101. /**
  3102. * Multiplies the current Vector3 coordinates by the given ones
  3103. * @param otherVector defines the second operand
  3104. * @returns the current updated Vector3
  3105. */
  3106. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3107. this.x *= otherVector.x;
  3108. this.y *= otherVector.y;
  3109. this.z *= otherVector.z;
  3110. return this;
  3111. };
  3112. /**
  3113. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3114. * @param otherVector defines the second operand
  3115. * @returns the new Vector3
  3116. */
  3117. Vector3.prototype.multiply = function (otherVector) {
  3118. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3119. };
  3120. /**
  3121. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3122. * @param otherVector defines the second operand
  3123. * @param result defines the Vector3 object where to store the result
  3124. * @returns the current Vector3
  3125. */
  3126. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3127. result.x = this.x * otherVector.x;
  3128. result.y = this.y * otherVector.y;
  3129. result.z = this.z * otherVector.z;
  3130. return this;
  3131. };
  3132. /**
  3133. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3134. * @param x defines the x coordinate of the operand
  3135. * @param y defines the y coordinate of the operand
  3136. * @param z defines the z coordinate of the operand
  3137. * @returns the new Vector3
  3138. */
  3139. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3140. return new Vector3(this.x * x, this.y * y, this.z * z);
  3141. };
  3142. /**
  3143. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3144. * @param otherVector defines the second operand
  3145. * @returns the new Vector3
  3146. */
  3147. Vector3.prototype.divide = function (otherVector) {
  3148. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3149. };
  3150. /**
  3151. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3152. * @param otherVector defines the second operand
  3153. * @param result defines the Vector3 object where to store the result
  3154. * @returns the current Vector3
  3155. */
  3156. Vector3.prototype.divideToRef = function (otherVector, result) {
  3157. result.x = this.x / otherVector.x;
  3158. result.y = this.y / otherVector.y;
  3159. result.z = this.z / otherVector.z;
  3160. return this;
  3161. };
  3162. /**
  3163. * Divides the current Vector3 coordinates by the given ones.
  3164. * @param otherVector defines the second operand
  3165. * @returns the current updated Vector3
  3166. */
  3167. Vector3.prototype.divideInPlace = function (otherVector) {
  3168. return this.divideToRef(otherVector, this);
  3169. };
  3170. /**
  3171. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3172. * @param other defines the second operand
  3173. * @returns the current updated Vector3
  3174. */
  3175. Vector3.prototype.minimizeInPlace = function (other) {
  3176. return this.minimizeInPlaceFromFloats(other.x, other.y, other.z);
  3177. };
  3178. /**
  3179. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3180. * @param other defines the second operand
  3181. * @returns the current updated Vector3
  3182. */
  3183. Vector3.prototype.maximizeInPlace = function (other) {
  3184. return this.maximizeInPlaceFromFloats(other.x, other.y, other.z);
  3185. };
  3186. /**
  3187. * Updates the current Vector3 with the minimal coordinate values between its and the given coordinates
  3188. * @param x defines the x coordinate of the operand
  3189. * @param y defines the y coordinate of the operand
  3190. * @param z defines the z coordinate of the operand
  3191. * @returns the current updated Vector3
  3192. */
  3193. Vector3.prototype.minimizeInPlaceFromFloats = function (x, y, z) {
  3194. if (x < this.x) {
  3195. this.x = x;
  3196. }
  3197. if (y < this.y) {
  3198. this.y = y;
  3199. }
  3200. if (z < this.z) {
  3201. this.z = z;
  3202. }
  3203. return this;
  3204. };
  3205. /**
  3206. * Updates the current Vector3 with the maximal coordinate values between its and the given coordinates.
  3207. * @param x defines the x coordinate of the operand
  3208. * @param y defines the y coordinate of the operand
  3209. * @param z defines the z coordinate of the operand
  3210. * @returns the current updated Vector3
  3211. */
  3212. Vector3.prototype.maximizeInPlaceFromFloats = function (x, y, z) {
  3213. if (x > this.x) {
  3214. this.x = x;
  3215. }
  3216. if (y > this.y) {
  3217. this.y = y;
  3218. }
  3219. if (z > this.z) {
  3220. this.z = z;
  3221. }
  3222. return this;
  3223. };
  3224. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3225. /**
  3226. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3227. */
  3228. get: function () {
  3229. var absX = Math.abs(this.x);
  3230. var absY = Math.abs(this.y);
  3231. if (absX !== absY) {
  3232. return true;
  3233. }
  3234. var absZ = Math.abs(this.z);
  3235. if (absX !== absZ) {
  3236. return true;
  3237. }
  3238. if (absY !== absZ) {
  3239. return true;
  3240. }
  3241. return false;
  3242. },
  3243. enumerable: true,
  3244. configurable: true
  3245. });
  3246. /**
  3247. * Gets a new Vector3 from current Vector3 floored values
  3248. * @returns a new Vector3
  3249. */
  3250. Vector3.prototype.floor = function () {
  3251. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3252. };
  3253. /**
  3254. * Gets a new Vector3 from current Vector3 floored values
  3255. * @returns a new Vector3
  3256. */
  3257. Vector3.prototype.fract = function () {
  3258. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3259. };
  3260. // Properties
  3261. /**
  3262. * Gets the length of the Vector3
  3263. * @returns the length of the Vecto3
  3264. */
  3265. Vector3.prototype.length = function () {
  3266. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3267. };
  3268. /**
  3269. * Gets the squared length of the Vector3
  3270. * @returns squared length of the Vector3
  3271. */
  3272. Vector3.prototype.lengthSquared = function () {
  3273. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3274. };
  3275. /**
  3276. * Normalize the current Vector3.
  3277. * Please note that this is an in place operation.
  3278. * @returns the current updated Vector3
  3279. */
  3280. Vector3.prototype.normalize = function () {
  3281. var len = this.length();
  3282. if (len === 0 || len === 1.0) {
  3283. return this;
  3284. }
  3285. var num = 1.0 / len;
  3286. this.x *= num;
  3287. this.y *= num;
  3288. this.z *= num;
  3289. return this;
  3290. };
  3291. /**
  3292. * Normalize the current Vector3 to a new vector
  3293. * @returns the new Vector3
  3294. */
  3295. Vector3.prototype.normalizeToNew = function () {
  3296. var normalized = new Vector3(0, 0, 0);
  3297. this.normalizeToRef(normalized);
  3298. return normalized;
  3299. };
  3300. /**
  3301. * Normalize the current Vector3 to the reference
  3302. * @param reference define the Vector3 to update
  3303. * @returns the updated Vector3
  3304. */
  3305. Vector3.prototype.normalizeToRef = function (reference) {
  3306. var len = this.length();
  3307. if (len === 0 || len === 1.0) {
  3308. reference.set(this.x, this.y, this.z);
  3309. return reference;
  3310. }
  3311. var scale = 1.0 / len;
  3312. this.scaleToRef(scale, reference);
  3313. return reference;
  3314. };
  3315. /**
  3316. * Creates a new Vector3 copied from the current Vector3
  3317. * @returns the new Vector3
  3318. */
  3319. Vector3.prototype.clone = function () {
  3320. return new Vector3(this.x, this.y, this.z);
  3321. };
  3322. /**
  3323. * Copies the given vector coordinates to the current Vector3 ones
  3324. * @param source defines the source Vector3
  3325. * @returns the current updated Vector3
  3326. */
  3327. Vector3.prototype.copyFrom = function (source) {
  3328. this.x = source.x;
  3329. this.y = source.y;
  3330. this.z = source.z;
  3331. return this;
  3332. };
  3333. /**
  3334. * Copies the given floats to the current Vector3 coordinates
  3335. * @param x defines the x coordinate of the operand
  3336. * @param y defines the y coordinate of the operand
  3337. * @param z defines the z coordinate of the operand
  3338. * @returns the current updated Vector3
  3339. */
  3340. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3341. this.x = x;
  3342. this.y = y;
  3343. this.z = z;
  3344. return this;
  3345. };
  3346. /**
  3347. * Copies the given floats to the current Vector3 coordinates
  3348. * @param x defines the x coordinate of the operand
  3349. * @param y defines the y coordinate of the operand
  3350. * @param z defines the z coordinate of the operand
  3351. * @returns the current updated Vector3
  3352. */
  3353. Vector3.prototype.set = function (x, y, z) {
  3354. return this.copyFromFloats(x, y, z);
  3355. };
  3356. // Statics
  3357. /**
  3358. * Get the clip factor between two vectors
  3359. * @param vector0 defines the first operand
  3360. * @param vector1 defines the second operand
  3361. * @param axis defines the axis to use
  3362. * @param size defines the size along the axis
  3363. * @returns the clip factor
  3364. */
  3365. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3366. var d0 = Vector3.Dot(vector0, axis) - size;
  3367. var d1 = Vector3.Dot(vector1, axis) - size;
  3368. var s = d0 / (d0 - d1);
  3369. return s;
  3370. };
  3371. /**
  3372. * Get angle between two vectors
  3373. * @param vector0 angle between vector0 and vector1
  3374. * @param vector1 angle between vector0 and vector1
  3375. * @param normal direction of the normal
  3376. * @return the angle between vector0 and vector1
  3377. */
  3378. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3379. var v0 = MathTmp.Vector3[1].copyFrom(vector0).normalize();
  3380. var v1 = MathTmp.Vector3[2].copyFrom(vector1).normalize();
  3381. var dot = Vector3.Dot(v0, v1);
  3382. var n = MathTmp.Vector3[3];
  3383. Vector3.CrossToRef(v0, v1, n);
  3384. if (Vector3.Dot(n, normal) > 0) {
  3385. return Math.acos(dot);
  3386. }
  3387. return -Math.acos(dot);
  3388. };
  3389. /**
  3390. * Returns a new Vector3 set from the index "offset" of the given array
  3391. * @param array defines the source array
  3392. * @param offset defines the offset in the source array
  3393. * @returns the new Vector3
  3394. */
  3395. Vector3.FromArray = function (array, offset) {
  3396. if (!offset) {
  3397. offset = 0;
  3398. }
  3399. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3400. };
  3401. /**
  3402. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3403. * This function is deprecated. Use FromArray instead
  3404. * @param array defines the source array
  3405. * @param offset defines the offset in the source array
  3406. * @returns the new Vector3
  3407. */
  3408. Vector3.FromFloatArray = function (array, offset) {
  3409. return Vector3.FromArray(array, offset);
  3410. };
  3411. /**
  3412. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3413. * @param array defines the source array
  3414. * @param offset defines the offset in the source array
  3415. * @param result defines the Vector3 where to store the result
  3416. */
  3417. Vector3.FromArrayToRef = function (array, offset, result) {
  3418. result.x = array[offset];
  3419. result.y = array[offset + 1];
  3420. result.z = array[offset + 2];
  3421. };
  3422. /**
  3423. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3424. * This function is deprecated. Use FromArrayToRef instead.
  3425. * @param array defines the source array
  3426. * @param offset defines the offset in the source array
  3427. * @param result defines the Vector3 where to store the result
  3428. */
  3429. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3430. return Vector3.FromArrayToRef(array, offset, result);
  3431. };
  3432. /**
  3433. * Sets the given vector "result" with the given floats.
  3434. * @param x defines the x coordinate of the source
  3435. * @param y defines the y coordinate of the source
  3436. * @param z defines the z coordinate of the source
  3437. * @param result defines the Vector3 where to store the result
  3438. */
  3439. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3440. result.x = x;
  3441. result.y = y;
  3442. result.z = z;
  3443. };
  3444. /**
  3445. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3446. * @returns a new empty Vector3
  3447. */
  3448. Vector3.Zero = function () {
  3449. return new Vector3(0.0, 0.0, 0.0);
  3450. };
  3451. /**
  3452. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3453. * @returns a new unit Vector3
  3454. */
  3455. Vector3.One = function () {
  3456. return new Vector3(1.0, 1.0, 1.0);
  3457. };
  3458. /**
  3459. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3460. * @returns a new up Vector3
  3461. */
  3462. Vector3.Up = function () {
  3463. return new Vector3(0.0, 1.0, 0.0);
  3464. };
  3465. /**
  3466. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3467. * @returns a new down Vector3
  3468. */
  3469. Vector3.Down = function () {
  3470. return new Vector3(0.0, -1.0, 0.0);
  3471. };
  3472. /**
  3473. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3474. * @returns a new forward Vector3
  3475. */
  3476. Vector3.Forward = function () {
  3477. return new Vector3(0.0, 0.0, 1.0);
  3478. };
  3479. /**
  3480. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  3481. * @returns a new forward Vector3
  3482. */
  3483. Vector3.Backward = function () {
  3484. return new Vector3(0.0, 0.0, -1.0);
  3485. };
  3486. /**
  3487. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3488. * @returns a new right Vector3
  3489. */
  3490. Vector3.Right = function () {
  3491. return new Vector3(1.0, 0.0, 0.0);
  3492. };
  3493. /**
  3494. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3495. * @returns a new left Vector3
  3496. */
  3497. Vector3.Left = function () {
  3498. return new Vector3(-1.0, 0.0, 0.0);
  3499. };
  3500. /**
  3501. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3502. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3503. * @param vector defines the Vector3 to transform
  3504. * @param transformation defines the transformation matrix
  3505. * @returns the transformed Vector3
  3506. */
  3507. Vector3.TransformCoordinates = function (vector, transformation) {
  3508. var result = Vector3.Zero();
  3509. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3510. return result;
  3511. };
  3512. /**
  3513. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3514. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3515. * @param vector defines the Vector3 to transform
  3516. * @param transformation defines the transformation matrix
  3517. * @param result defines the Vector3 where to store the result
  3518. */
  3519. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3520. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3521. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3522. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3523. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3524. result.x = x / w;
  3525. result.y = y / w;
  3526. result.z = z / w;
  3527. };
  3528. /**
  3529. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3530. * This method computes tranformed coordinates only, not transformed direction vectors
  3531. * @param x define the x coordinate of the source vector
  3532. * @param y define the y coordinate of the source vector
  3533. * @param z define the z coordinate of the source vector
  3534. * @param transformation defines the transformation matrix
  3535. * @param result defines the Vector3 where to store the result
  3536. */
  3537. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3538. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3539. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3540. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3541. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3542. result.x = rx / rw;
  3543. result.y = ry / rw;
  3544. result.z = rz / rw;
  3545. };
  3546. /**
  3547. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3548. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3549. * @param vector defines the Vector3 to transform
  3550. * @param transformation defines the transformation matrix
  3551. * @returns the new Vector3
  3552. */
  3553. Vector3.TransformNormal = function (vector, transformation) {
  3554. var result = Vector3.Zero();
  3555. Vector3.TransformNormalToRef(vector, transformation, result);
  3556. return result;
  3557. };
  3558. /**
  3559. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3560. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3561. * @param vector defines the Vector3 to transform
  3562. * @param transformation defines the transformation matrix
  3563. * @param result defines the Vector3 where to store the result
  3564. */
  3565. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3566. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3567. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3568. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3569. result.x = x;
  3570. result.y = y;
  3571. result.z = z;
  3572. };
  3573. /**
  3574. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3575. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3576. * @param x define the x coordinate of the source vector
  3577. * @param y define the y coordinate of the source vector
  3578. * @param z define the z coordinate of the source vector
  3579. * @param transformation defines the transformation matrix
  3580. * @param result defines the Vector3 where to store the result
  3581. */
  3582. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3583. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3584. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3585. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3586. };
  3587. /**
  3588. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3589. * @param value1 defines the first control point
  3590. * @param value2 defines the second control point
  3591. * @param value3 defines the third control point
  3592. * @param value4 defines the fourth control point
  3593. * @param amount defines the amount on the spline to use
  3594. * @returns the new Vector3
  3595. */
  3596. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3597. var squared = amount * amount;
  3598. var cubed = amount * squared;
  3599. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3600. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3601. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3602. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3603. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3604. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3605. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3606. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3607. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3608. return new Vector3(x, y, z);
  3609. };
  3610. /**
  3611. * 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"
  3612. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3613. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3614. * @param value defines the current value
  3615. * @param min defines the lower range value
  3616. * @param max defines the upper range value
  3617. * @returns the new Vector3
  3618. */
  3619. Vector3.Clamp = function (value, min, max) {
  3620. var x = value.x;
  3621. x = (x > max.x) ? max.x : x;
  3622. x = (x < min.x) ? min.x : x;
  3623. var y = value.y;
  3624. y = (y > max.y) ? max.y : y;
  3625. y = (y < min.y) ? min.y : y;
  3626. var z = value.z;
  3627. z = (z > max.z) ? max.z : z;
  3628. z = (z < min.z) ? min.z : z;
  3629. return new Vector3(x, y, z);
  3630. };
  3631. /**
  3632. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3633. * @param value1 defines the first control point
  3634. * @param tangent1 defines the first tangent vector
  3635. * @param value2 defines the second control point
  3636. * @param tangent2 defines the second tangent vector
  3637. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3638. * @returns the new Vector3
  3639. */
  3640. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3641. var squared = amount * amount;
  3642. var cubed = amount * squared;
  3643. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3644. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3645. var part3 = (cubed - (2.0 * squared)) + amount;
  3646. var part4 = cubed - squared;
  3647. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3648. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3649. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3650. return new Vector3(x, y, z);
  3651. };
  3652. /**
  3653. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3654. * @param start defines the start value
  3655. * @param end defines the end value
  3656. * @param amount max defines amount between both (between 0 and 1)
  3657. * @returns the new Vector3
  3658. */
  3659. Vector3.Lerp = function (start, end, amount) {
  3660. var result = new Vector3(0, 0, 0);
  3661. Vector3.LerpToRef(start, end, amount, result);
  3662. return result;
  3663. };
  3664. /**
  3665. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3666. * @param start defines the start value
  3667. * @param end defines the end value
  3668. * @param amount max defines amount between both (between 0 and 1)
  3669. * @param result defines the Vector3 where to store the result
  3670. */
  3671. Vector3.LerpToRef = function (start, end, amount, result) {
  3672. result.x = start.x + ((end.x - start.x) * amount);
  3673. result.y = start.y + ((end.y - start.y) * amount);
  3674. result.z = start.z + ((end.z - start.z) * amount);
  3675. };
  3676. /**
  3677. * Returns the dot product (float) between the vectors "left" and "right"
  3678. * @param left defines the left operand
  3679. * @param right defines the right operand
  3680. * @returns the dot product
  3681. */
  3682. Vector3.Dot = function (left, right) {
  3683. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3684. };
  3685. /**
  3686. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3687. * The cross product is then orthogonal to both "left" and "right"
  3688. * @param left defines the left operand
  3689. * @param right defines the right operand
  3690. * @returns the cross product
  3691. */
  3692. Vector3.Cross = function (left, right) {
  3693. var result = Vector3.Zero();
  3694. Vector3.CrossToRef(left, right, result);
  3695. return result;
  3696. };
  3697. /**
  3698. * Sets the given vector "result" with the cross product of "left" and "right"
  3699. * The cross product is then orthogonal to both "left" and "right"
  3700. * @param left defines the left operand
  3701. * @param right defines the right operand
  3702. * @param result defines the Vector3 where to store the result
  3703. */
  3704. Vector3.CrossToRef = function (left, right, result) {
  3705. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3706. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3707. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3708. result.copyFrom(MathTmp.Vector3[0]);
  3709. };
  3710. /**
  3711. * Returns a new Vector3 as the normalization of the given vector
  3712. * @param vector defines the Vector3 to normalize
  3713. * @returns the new Vector3
  3714. */
  3715. Vector3.Normalize = function (vector) {
  3716. var result = Vector3.Zero();
  3717. Vector3.NormalizeToRef(vector, result);
  3718. return result;
  3719. };
  3720. /**
  3721. * Sets the given vector "result" with the normalization of the given first vector
  3722. * @param vector defines the Vector3 to normalize
  3723. * @param result defines the Vector3 where to store the result
  3724. */
  3725. Vector3.NormalizeToRef = function (vector, result) {
  3726. result.copyFrom(vector);
  3727. result.normalize();
  3728. };
  3729. /**
  3730. * Project a Vector3 onto screen space
  3731. * @param vector defines the Vector3 to project
  3732. * @param world defines the world matrix to use
  3733. * @param transform defines the transform (view x projection) matrix to use
  3734. * @param viewport defines the screen viewport to use
  3735. * @returns the new Vector3
  3736. */
  3737. Vector3.Project = function (vector, world, transform, viewport) {
  3738. var cw = viewport.width;
  3739. var ch = viewport.height;
  3740. var cx = viewport.x;
  3741. var cy = viewport.y;
  3742. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3743. 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);
  3744. var matrix = MathTmp.Matrix[0];
  3745. world.multiplyToRef(transform, matrix);
  3746. matrix.multiplyToRef(viewportMatrix, matrix);
  3747. return Vector3.TransformCoordinates(vector, matrix);
  3748. };
  3749. /**
  3750. * Unproject from screen space to object space
  3751. * @param source defines the screen space Vector3 to use
  3752. * @param viewportWidth defines the current width of the viewport
  3753. * @param viewportHeight defines the current height of the viewport
  3754. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3755. * @param transform defines the transform (view x projection) matrix to use
  3756. * @returns the new Vector3
  3757. */
  3758. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3759. var matrix = MathTmp.Matrix[0];
  3760. world.multiplyToRef(transform, matrix);
  3761. matrix.invert();
  3762. source.x = source.x / viewportWidth * 2 - 1;
  3763. source.y = -(source.y / viewportHeight * 2 - 1);
  3764. var vector = Vector3.TransformCoordinates(source, matrix);
  3765. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3766. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3767. vector = vector.scale(1.0 / num);
  3768. }
  3769. return vector;
  3770. };
  3771. /**
  3772. * Unproject from screen space to object space
  3773. * @param source defines the screen space Vector3 to use
  3774. * @param viewportWidth defines the current width of the viewport
  3775. * @param viewportHeight defines the current height of the viewport
  3776. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3777. * @param view defines the view matrix to use
  3778. * @param projection defines the projection matrix to use
  3779. * @returns the new Vector3
  3780. */
  3781. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3782. var result = Vector3.Zero();
  3783. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3784. return result;
  3785. };
  3786. /**
  3787. * Unproject from screen space to object space
  3788. * @param source defines the screen space Vector3 to use
  3789. * @param viewportWidth defines the current width of the viewport
  3790. * @param viewportHeight defines the current height of the viewport
  3791. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3792. * @param view defines the view matrix to use
  3793. * @param projection defines the projection matrix to use
  3794. * @param result defines the Vector3 where to store the result
  3795. */
  3796. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3797. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3798. };
  3799. /**
  3800. * Unproject from screen space to object space
  3801. * @param sourceX defines the screen space x coordinate to use
  3802. * @param sourceY defines the screen space y coordinate to use
  3803. * @param sourceZ defines the screen space z coordinate to use
  3804. * @param viewportWidth defines the current width of the viewport
  3805. * @param viewportHeight defines the current height of the viewport
  3806. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3807. * @param view defines the view matrix to use
  3808. * @param projection defines the projection matrix to use
  3809. * @param result defines the Vector3 where to store the result
  3810. */
  3811. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3812. var matrix = MathTmp.Matrix[0];
  3813. world.multiplyToRef(view, matrix);
  3814. matrix.multiplyToRef(projection, matrix);
  3815. matrix.invert();
  3816. var screenSource = MathTmp.Vector3[0];
  3817. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3818. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3819. screenSource.z = 2 * sourceZ - 1.0;
  3820. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3821. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3822. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3823. result.scaleInPlace(1.0 / num);
  3824. }
  3825. };
  3826. /**
  3827. * Gets the minimal coordinate values between two Vector3
  3828. * @param left defines the first operand
  3829. * @param right defines the second operand
  3830. * @returns the new Vector3
  3831. */
  3832. Vector3.Minimize = function (left, right) {
  3833. var min = left.clone();
  3834. min.minimizeInPlace(right);
  3835. return min;
  3836. };
  3837. /**
  3838. * Gets the maximal coordinate values between two Vector3
  3839. * @param left defines the first operand
  3840. * @param right defines the second operand
  3841. * @returns the new Vector3
  3842. */
  3843. Vector3.Maximize = function (left, right) {
  3844. var max = left.clone();
  3845. max.maximizeInPlace(right);
  3846. return max;
  3847. };
  3848. /**
  3849. * Returns the distance between the vectors "value1" and "value2"
  3850. * @param value1 defines the first operand
  3851. * @param value2 defines the second operand
  3852. * @returns the distance
  3853. */
  3854. Vector3.Distance = function (value1, value2) {
  3855. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3856. };
  3857. /**
  3858. * Returns the squared distance between the vectors "value1" and "value2"
  3859. * @param value1 defines the first operand
  3860. * @param value2 defines the second operand
  3861. * @returns the squared distance
  3862. */
  3863. Vector3.DistanceSquared = function (value1, value2) {
  3864. var x = value1.x - value2.x;
  3865. var y = value1.y - value2.y;
  3866. var z = value1.z - value2.z;
  3867. return (x * x) + (y * y) + (z * z);
  3868. };
  3869. /**
  3870. * Returns a new Vector3 located at the center between "value1" and "value2"
  3871. * @param value1 defines the first operand
  3872. * @param value2 defines the second operand
  3873. * @returns the new Vector3
  3874. */
  3875. Vector3.Center = function (value1, value2) {
  3876. var center = value1.add(value2);
  3877. center.scaleInPlace(0.5);
  3878. return center;
  3879. };
  3880. /**
  3881. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3882. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3883. * to something in order to rotate it from its local system to the given target system
  3884. * Note: axis1, axis2 and axis3 are normalized during this operation
  3885. * @param axis1 defines the first axis
  3886. * @param axis2 defines the second axis
  3887. * @param axis3 defines the third axis
  3888. * @returns a new Vector3
  3889. */
  3890. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3891. var rotation = Vector3.Zero();
  3892. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3893. return rotation;
  3894. };
  3895. /**
  3896. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3897. * @param axis1 defines the first axis
  3898. * @param axis2 defines the second axis
  3899. * @param axis3 defines the third axis
  3900. * @param ref defines the Vector3 where to store the result
  3901. */
  3902. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3903. var quat = MathTmp.Quaternion[0];
  3904. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3905. quat.toEulerAnglesToRef(ref);
  3906. };
  3907. return Vector3;
  3908. }());
  3909. BABYLON.Vector3 = Vector3;
  3910. /**
  3911. * Vector4 class created for EulerAngle class conversion to Quaternion
  3912. */
  3913. var Vector4 = /** @class */ (function () {
  3914. /**
  3915. * Creates a Vector4 object from the given floats.
  3916. * @param x x value of the vector
  3917. * @param y y value of the vector
  3918. * @param z z value of the vector
  3919. * @param w w value of the vector
  3920. */
  3921. function Vector4(
  3922. /** x value of the vector */
  3923. x,
  3924. /** y value of the vector */
  3925. y,
  3926. /** z value of the vector */
  3927. z,
  3928. /** w value of the vector */
  3929. w) {
  3930. this.x = x;
  3931. this.y = y;
  3932. this.z = z;
  3933. this.w = w;
  3934. }
  3935. /**
  3936. * Returns the string with the Vector4 coordinates.
  3937. * @returns a string containing all the vector values
  3938. */
  3939. Vector4.prototype.toString = function () {
  3940. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3941. };
  3942. /**
  3943. * Returns the string "Vector4".
  3944. * @returns "Vector4"
  3945. */
  3946. Vector4.prototype.getClassName = function () {
  3947. return "Vector4";
  3948. };
  3949. /**
  3950. * Returns the Vector4 hash code.
  3951. * @returns a unique hash code
  3952. */
  3953. Vector4.prototype.getHashCode = function () {
  3954. var hash = this.x || 0;
  3955. hash = (hash * 397) ^ (this.y || 0);
  3956. hash = (hash * 397) ^ (this.z || 0);
  3957. hash = (hash * 397) ^ (this.w || 0);
  3958. return hash;
  3959. };
  3960. // Operators
  3961. /**
  3962. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3963. * @returns the resulting array
  3964. */
  3965. Vector4.prototype.asArray = function () {
  3966. var result = new Array();
  3967. this.toArray(result, 0);
  3968. return result;
  3969. };
  3970. /**
  3971. * Populates the given array from the given index with the Vector4 coordinates.
  3972. * @param array array to populate
  3973. * @param index index of the array to start at (default: 0)
  3974. * @returns the Vector4.
  3975. */
  3976. Vector4.prototype.toArray = function (array, index) {
  3977. if (index === undefined) {
  3978. index = 0;
  3979. }
  3980. array[index] = this.x;
  3981. array[index + 1] = this.y;
  3982. array[index + 2] = this.z;
  3983. array[index + 3] = this.w;
  3984. return this;
  3985. };
  3986. /**
  3987. * Adds the given vector to the current Vector4.
  3988. * @param otherVector the vector to add
  3989. * @returns the updated Vector4.
  3990. */
  3991. Vector4.prototype.addInPlace = function (otherVector) {
  3992. this.x += otherVector.x;
  3993. this.y += otherVector.y;
  3994. this.z += otherVector.z;
  3995. this.w += otherVector.w;
  3996. return this;
  3997. };
  3998. /**
  3999. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  4000. * @param otherVector the vector to add
  4001. * @returns the resulting vector
  4002. */
  4003. Vector4.prototype.add = function (otherVector) {
  4004. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  4005. };
  4006. /**
  4007. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  4008. * @param otherVector the vector to add
  4009. * @param result the vector to store the result
  4010. * @returns the current Vector4.
  4011. */
  4012. Vector4.prototype.addToRef = function (otherVector, result) {
  4013. result.x = this.x + otherVector.x;
  4014. result.y = this.y + otherVector.y;
  4015. result.z = this.z + otherVector.z;
  4016. result.w = this.w + otherVector.w;
  4017. return this;
  4018. };
  4019. /**
  4020. * Subtract in place the given vector from the current Vector4.
  4021. * @param otherVector the vector to subtract
  4022. * @returns the updated Vector4.
  4023. */
  4024. Vector4.prototype.subtractInPlace = function (otherVector) {
  4025. this.x -= otherVector.x;
  4026. this.y -= otherVector.y;
  4027. this.z -= otherVector.z;
  4028. this.w -= otherVector.w;
  4029. return this;
  4030. };
  4031. /**
  4032. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  4033. * @param otherVector the vector to add
  4034. * @returns the new vector with the result
  4035. */
  4036. Vector4.prototype.subtract = function (otherVector) {
  4037. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  4038. };
  4039. /**
  4040. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  4041. * @param otherVector the vector to subtract
  4042. * @param result the vector to store the result
  4043. * @returns the current Vector4.
  4044. */
  4045. Vector4.prototype.subtractToRef = function (otherVector, result) {
  4046. result.x = this.x - otherVector.x;
  4047. result.y = this.y - otherVector.y;
  4048. result.z = this.z - otherVector.z;
  4049. result.w = this.w - otherVector.w;
  4050. return this;
  4051. };
  4052. /**
  4053. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4054. */
  4055. /**
  4056. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4057. * @param x value to subtract
  4058. * @param y value to subtract
  4059. * @param z value to subtract
  4060. * @param w value to subtract
  4061. * @returns new vector containing the result
  4062. */
  4063. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  4064. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  4065. };
  4066. /**
  4067. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4068. * @param x value to subtract
  4069. * @param y value to subtract
  4070. * @param z value to subtract
  4071. * @param w value to subtract
  4072. * @param result the vector to store the result in
  4073. * @returns the current Vector4.
  4074. */
  4075. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  4076. result.x = this.x - x;
  4077. result.y = this.y - y;
  4078. result.z = this.z - z;
  4079. result.w = this.w - w;
  4080. return this;
  4081. };
  4082. /**
  4083. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  4084. * @returns a new vector with the negated values
  4085. */
  4086. Vector4.prototype.negate = function () {
  4087. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  4088. };
  4089. /**
  4090. * Multiplies the current Vector4 coordinates by scale (float).
  4091. * @param scale the number to scale with
  4092. * @returns the updated Vector4.
  4093. */
  4094. Vector4.prototype.scaleInPlace = function (scale) {
  4095. this.x *= scale;
  4096. this.y *= scale;
  4097. this.z *= scale;
  4098. this.w *= scale;
  4099. return this;
  4100. };
  4101. /**
  4102. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  4103. * @param scale the number to scale with
  4104. * @returns a new vector with the result
  4105. */
  4106. Vector4.prototype.scale = function (scale) {
  4107. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4108. };
  4109. /**
  4110. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4111. * @param scale the number to scale with
  4112. * @param result a vector to store the result in
  4113. * @returns the current Vector4.
  4114. */
  4115. Vector4.prototype.scaleToRef = function (scale, result) {
  4116. result.x = this.x * scale;
  4117. result.y = this.y * scale;
  4118. result.z = this.z * scale;
  4119. result.w = this.w * scale;
  4120. return this;
  4121. };
  4122. /**
  4123. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4124. * @param scale defines the scale factor
  4125. * @param result defines the Vector4 object where to store the result
  4126. * @returns the unmodified current Vector4
  4127. */
  4128. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4129. result.x += this.x * scale;
  4130. result.y += this.y * scale;
  4131. result.z += this.z * scale;
  4132. result.w += this.w * scale;
  4133. return this;
  4134. };
  4135. /**
  4136. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4137. * @param otherVector the vector to compare against
  4138. * @returns true if they are equal
  4139. */
  4140. Vector4.prototype.equals = function (otherVector) {
  4141. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4142. };
  4143. /**
  4144. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4145. * @param otherVector vector to compare against
  4146. * @param epsilon (Default: very small number)
  4147. * @returns true if they are equal
  4148. */
  4149. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4150. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4151. return otherVector
  4152. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4153. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4154. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4155. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4156. };
  4157. /**
  4158. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4159. * @param x x value to compare against
  4160. * @param y y value to compare against
  4161. * @param z z value to compare against
  4162. * @param w w value to compare against
  4163. * @returns true if equal
  4164. */
  4165. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4166. return this.x === x && this.y === y && this.z === z && this.w === w;
  4167. };
  4168. /**
  4169. * Multiplies in place the current Vector4 by the given one.
  4170. * @param otherVector vector to multiple with
  4171. * @returns the updated Vector4.
  4172. */
  4173. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4174. this.x *= otherVector.x;
  4175. this.y *= otherVector.y;
  4176. this.z *= otherVector.z;
  4177. this.w *= otherVector.w;
  4178. return this;
  4179. };
  4180. /**
  4181. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4182. * @param otherVector vector to multiple with
  4183. * @returns resulting new vector
  4184. */
  4185. Vector4.prototype.multiply = function (otherVector) {
  4186. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4187. };
  4188. /**
  4189. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4190. * @param otherVector vector to multiple with
  4191. * @param result vector to store the result
  4192. * @returns the current Vector4.
  4193. */
  4194. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4195. result.x = this.x * otherVector.x;
  4196. result.y = this.y * otherVector.y;
  4197. result.z = this.z * otherVector.z;
  4198. result.w = this.w * otherVector.w;
  4199. return this;
  4200. };
  4201. /**
  4202. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4203. * @param x x value multiply with
  4204. * @param y y value multiply with
  4205. * @param z z value multiply with
  4206. * @param w w value multiply with
  4207. * @returns resulting new vector
  4208. */
  4209. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4210. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4211. };
  4212. /**
  4213. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4214. * @param otherVector vector to devide with
  4215. * @returns resulting new vector
  4216. */
  4217. Vector4.prototype.divide = function (otherVector) {
  4218. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4219. };
  4220. /**
  4221. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4222. * @param otherVector vector to devide with
  4223. * @param result vector to store the result
  4224. * @returns the current Vector4.
  4225. */
  4226. Vector4.prototype.divideToRef = function (otherVector, result) {
  4227. result.x = this.x / otherVector.x;
  4228. result.y = this.y / otherVector.y;
  4229. result.z = this.z / otherVector.z;
  4230. result.w = this.w / otherVector.w;
  4231. return this;
  4232. };
  4233. /**
  4234. * Divides the current Vector3 coordinates by the given ones.
  4235. * @param otherVector vector to devide with
  4236. * @returns the updated Vector3.
  4237. */
  4238. Vector4.prototype.divideInPlace = function (otherVector) {
  4239. return this.divideToRef(otherVector, this);
  4240. };
  4241. /**
  4242. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4243. * @param other defines the second operand
  4244. * @returns the current updated Vector4
  4245. */
  4246. Vector4.prototype.minimizeInPlace = function (other) {
  4247. if (other.x < this.x) {
  4248. this.x = other.x;
  4249. }
  4250. if (other.y < this.y) {
  4251. this.y = other.y;
  4252. }
  4253. if (other.z < this.z) {
  4254. this.z = other.z;
  4255. }
  4256. if (other.w < this.w) {
  4257. this.w = other.w;
  4258. }
  4259. return this;
  4260. };
  4261. /**
  4262. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4263. * @param other defines the second operand
  4264. * @returns the current updated Vector4
  4265. */
  4266. Vector4.prototype.maximizeInPlace = function (other) {
  4267. if (other.x > this.x) {
  4268. this.x = other.x;
  4269. }
  4270. if (other.y > this.y) {
  4271. this.y = other.y;
  4272. }
  4273. if (other.z > this.z) {
  4274. this.z = other.z;
  4275. }
  4276. if (other.w > this.w) {
  4277. this.w = other.w;
  4278. }
  4279. return this;
  4280. };
  4281. /**
  4282. * Gets a new Vector4 from current Vector4 floored values
  4283. * @returns a new Vector4
  4284. */
  4285. Vector4.prototype.floor = function () {
  4286. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4287. };
  4288. /**
  4289. * Gets a new Vector4 from current Vector3 floored values
  4290. * @returns a new Vector4
  4291. */
  4292. Vector4.prototype.fract = function () {
  4293. 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));
  4294. };
  4295. // Properties
  4296. /**
  4297. * Returns the Vector4 length (float).
  4298. * @returns the length
  4299. */
  4300. Vector4.prototype.length = function () {
  4301. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4302. };
  4303. /**
  4304. * Returns the Vector4 squared length (float).
  4305. * @returns the length squared
  4306. */
  4307. Vector4.prototype.lengthSquared = function () {
  4308. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4309. };
  4310. // Methods
  4311. /**
  4312. * Normalizes in place the Vector4.
  4313. * @returns the updated Vector4.
  4314. */
  4315. Vector4.prototype.normalize = function () {
  4316. var len = this.length();
  4317. if (len === 0) {
  4318. return this;
  4319. }
  4320. var num = 1.0 / len;
  4321. this.x *= num;
  4322. this.y *= num;
  4323. this.z *= num;
  4324. this.w *= num;
  4325. return this;
  4326. };
  4327. /**
  4328. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4329. * @returns this converted to a new vector3
  4330. */
  4331. Vector4.prototype.toVector3 = function () {
  4332. return new Vector3(this.x, this.y, this.z);
  4333. };
  4334. /**
  4335. * Returns a new Vector4 copied from the current one.
  4336. * @returns the new cloned vector
  4337. */
  4338. Vector4.prototype.clone = function () {
  4339. return new Vector4(this.x, this.y, this.z, this.w);
  4340. };
  4341. /**
  4342. * Updates the current Vector4 with the given one coordinates.
  4343. * @param source the source vector to copy from
  4344. * @returns the updated Vector4.
  4345. */
  4346. Vector4.prototype.copyFrom = function (source) {
  4347. this.x = source.x;
  4348. this.y = source.y;
  4349. this.z = source.z;
  4350. this.w = source.w;
  4351. return this;
  4352. };
  4353. /**
  4354. * Updates the current Vector4 coordinates with the given floats.
  4355. * @param x float to copy from
  4356. * @param y float to copy from
  4357. * @param z float to copy from
  4358. * @param w float to copy from
  4359. * @returns the updated Vector4.
  4360. */
  4361. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4362. this.x = x;
  4363. this.y = y;
  4364. this.z = z;
  4365. this.w = w;
  4366. return this;
  4367. };
  4368. /**
  4369. * Updates the current Vector4 coordinates with the given floats.
  4370. * @param x float to set from
  4371. * @param y float to set from
  4372. * @param z float to set from
  4373. * @param w float to set from
  4374. * @returns the updated Vector4.
  4375. */
  4376. Vector4.prototype.set = function (x, y, z, w) {
  4377. return this.copyFromFloats(x, y, z, w);
  4378. };
  4379. // Statics
  4380. /**
  4381. * Returns a new Vector4 set from the starting index of the given array.
  4382. * @param array the array to pull values from
  4383. * @param offset the offset into the array to start at
  4384. * @returns the new vector
  4385. */
  4386. Vector4.FromArray = function (array, offset) {
  4387. if (!offset) {
  4388. offset = 0;
  4389. }
  4390. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4391. };
  4392. /**
  4393. * Updates the given vector "result" from the starting index of the given array.
  4394. * @param array the array to pull values from
  4395. * @param offset the offset into the array to start at
  4396. * @param result the vector to store the result in
  4397. */
  4398. Vector4.FromArrayToRef = function (array, offset, result) {
  4399. result.x = array[offset];
  4400. result.y = array[offset + 1];
  4401. result.z = array[offset + 2];
  4402. result.w = array[offset + 3];
  4403. };
  4404. /**
  4405. * Updates the given vector "result" from the starting index of the given Float32Array.
  4406. * @param array the array to pull values from
  4407. * @param offset the offset into the array to start at
  4408. * @param result the vector to store the result in
  4409. */
  4410. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4411. Vector4.FromArrayToRef(array, offset, result);
  4412. };
  4413. /**
  4414. * Updates the given vector "result" coordinates from the given floats.
  4415. * @param x float to set from
  4416. * @param y float to set from
  4417. * @param z float to set from
  4418. * @param w float to set from
  4419. * @param result the vector to the floats in
  4420. */
  4421. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4422. result.x = x;
  4423. result.y = y;
  4424. result.z = z;
  4425. result.w = w;
  4426. };
  4427. /**
  4428. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4429. * @returns the new vector
  4430. */
  4431. Vector4.Zero = function () {
  4432. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4433. };
  4434. /**
  4435. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4436. * @returns the new vector
  4437. */
  4438. Vector4.One = function () {
  4439. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4440. };
  4441. /**
  4442. * Returns a new normalized Vector4 from the given one.
  4443. * @param vector the vector to normalize
  4444. * @returns the vector
  4445. */
  4446. Vector4.Normalize = function (vector) {
  4447. var result = Vector4.Zero();
  4448. Vector4.NormalizeToRef(vector, result);
  4449. return result;
  4450. };
  4451. /**
  4452. * Updates the given vector "result" from the normalization of the given one.
  4453. * @param vector the vector to normalize
  4454. * @param result the vector to store the result in
  4455. */
  4456. Vector4.NormalizeToRef = function (vector, result) {
  4457. result.copyFrom(vector);
  4458. result.normalize();
  4459. };
  4460. /**
  4461. * Returns a vector with the minimum values from the left and right vectors
  4462. * @param left left vector to minimize
  4463. * @param right right vector to minimize
  4464. * @returns a new vector with the minimum of the left and right vector values
  4465. */
  4466. Vector4.Minimize = function (left, right) {
  4467. var min = left.clone();
  4468. min.minimizeInPlace(right);
  4469. return min;
  4470. };
  4471. /**
  4472. * Returns a vector with the maximum values from the left and right vectors
  4473. * @param left left vector to maximize
  4474. * @param right right vector to maximize
  4475. * @returns a new vector with the maximum of the left and right vector values
  4476. */
  4477. Vector4.Maximize = function (left, right) {
  4478. var max = left.clone();
  4479. max.maximizeInPlace(right);
  4480. return max;
  4481. };
  4482. /**
  4483. * Returns the distance (float) between the vectors "value1" and "value2".
  4484. * @param value1 value to calulate the distance between
  4485. * @param value2 value to calulate the distance between
  4486. * @return the distance between the two vectors
  4487. */
  4488. Vector4.Distance = function (value1, value2) {
  4489. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4490. };
  4491. /**
  4492. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4493. * @param value1 value to calulate the distance between
  4494. * @param value2 value to calulate the distance between
  4495. * @return the distance between the two vectors squared
  4496. */
  4497. Vector4.DistanceSquared = function (value1, value2) {
  4498. var x = value1.x - value2.x;
  4499. var y = value1.y - value2.y;
  4500. var z = value1.z - value2.z;
  4501. var w = value1.w - value2.w;
  4502. return (x * x) + (y * y) + (z * z) + (w * w);
  4503. };
  4504. /**
  4505. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4506. * @param value1 value to calulate the center between
  4507. * @param value2 value to calulate the center between
  4508. * @return the center between the two vectors
  4509. */
  4510. Vector4.Center = function (value1, value2) {
  4511. var center = value1.add(value2);
  4512. center.scaleInPlace(0.5);
  4513. return center;
  4514. };
  4515. /**
  4516. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4517. * This methods computes transformed normalized direction vectors only.
  4518. * @param vector the vector to transform
  4519. * @param transformation the transformation matrix to apply
  4520. * @returns the new vector
  4521. */
  4522. Vector4.TransformNormal = function (vector, transformation) {
  4523. var result = Vector4.Zero();
  4524. Vector4.TransformNormalToRef(vector, transformation, result);
  4525. return result;
  4526. };
  4527. /**
  4528. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4529. * This methods computes transformed normalized direction vectors only.
  4530. * @param vector the vector to transform
  4531. * @param transformation the transformation matrix to apply
  4532. * @param result the vector to store the result in
  4533. */
  4534. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4535. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4536. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4537. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4538. result.x = x;
  4539. result.y = y;
  4540. result.z = z;
  4541. result.w = vector.w;
  4542. };
  4543. /**
  4544. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4545. * This methods computes transformed normalized direction vectors only.
  4546. * @param x value to transform
  4547. * @param y value to transform
  4548. * @param z value to transform
  4549. * @param w value to transform
  4550. * @param transformation the transformation matrix to apply
  4551. * @param result the vector to store the results in
  4552. */
  4553. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4554. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4555. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4556. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4557. result.w = w;
  4558. };
  4559. return Vector4;
  4560. }());
  4561. BABYLON.Vector4 = Vector4;
  4562. /**
  4563. * Size containing widht and height
  4564. */
  4565. var Size = /** @class */ (function () {
  4566. /**
  4567. * Creates a Size object from the given width and height (floats).
  4568. * @param width width of the new size
  4569. * @param height height of the new size
  4570. */
  4571. function Size(width, height) {
  4572. this.width = width;
  4573. this.height = height;
  4574. }
  4575. /**
  4576. * Returns a string with the Size width and height
  4577. * @returns a string with the Size width and height
  4578. */
  4579. Size.prototype.toString = function () {
  4580. return "{W: " + this.width + ", H: " + this.height + "}";
  4581. };
  4582. /**
  4583. * "Size"
  4584. * @returns the string "Size"
  4585. */
  4586. Size.prototype.getClassName = function () {
  4587. return "Size";
  4588. };
  4589. /**
  4590. * Returns the Size hash code.
  4591. * @returns a hash code for a unique width and height
  4592. */
  4593. Size.prototype.getHashCode = function () {
  4594. var hash = this.width || 0;
  4595. hash = (hash * 397) ^ (this.height || 0);
  4596. return hash;
  4597. };
  4598. /**
  4599. * Updates the current size from the given one.
  4600. * @param src the given size
  4601. */
  4602. Size.prototype.copyFrom = function (src) {
  4603. this.width = src.width;
  4604. this.height = src.height;
  4605. };
  4606. /**
  4607. * Updates in place the current Size from the given floats.
  4608. * @param width width of the new size
  4609. * @param height height of the new size
  4610. * @returns the updated Size.
  4611. */
  4612. Size.prototype.copyFromFloats = function (width, height) {
  4613. this.width = width;
  4614. this.height = height;
  4615. return this;
  4616. };
  4617. /**
  4618. * Updates in place the current Size from the given floats.
  4619. * @param width width to set
  4620. * @param height height to set
  4621. * @returns the updated Size.
  4622. */
  4623. Size.prototype.set = function (width, height) {
  4624. return this.copyFromFloats(width, height);
  4625. };
  4626. /**
  4627. * Multiplies the width and height by numbers
  4628. * @param w factor to multiple the width by
  4629. * @param h factor to multiple the height by
  4630. * @returns a new Size set with the multiplication result of the current Size and the given floats.
  4631. */
  4632. Size.prototype.multiplyByFloats = function (w, h) {
  4633. return new Size(this.width * w, this.height * h);
  4634. };
  4635. /**
  4636. * Clones the size
  4637. * @returns a new Size copied from the given one.
  4638. */
  4639. Size.prototype.clone = function () {
  4640. return new Size(this.width, this.height);
  4641. };
  4642. /**
  4643. * True if the current Size and the given one width and height are strictly equal.
  4644. * @param other the other size to compare against
  4645. * @returns True if the current Size and the given one width and height are strictly equal.
  4646. */
  4647. Size.prototype.equals = function (other) {
  4648. if (!other) {
  4649. return false;
  4650. }
  4651. return (this.width === other.width) && (this.height === other.height);
  4652. };
  4653. Object.defineProperty(Size.prototype, "surface", {
  4654. /**
  4655. * The surface of the Size : width * height (float).
  4656. */
  4657. get: function () {
  4658. return this.width * this.height;
  4659. },
  4660. enumerable: true,
  4661. configurable: true
  4662. });
  4663. /**
  4664. * Create a new size of zero
  4665. * @returns a new Size set to (0.0, 0.0)
  4666. */
  4667. Size.Zero = function () {
  4668. return new Size(0.0, 0.0);
  4669. };
  4670. /**
  4671. * Sums the width and height of two sizes
  4672. * @param otherSize size to add to this size
  4673. * @returns a new Size set as the addition result of the current Size and the given one.
  4674. */
  4675. Size.prototype.add = function (otherSize) {
  4676. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4677. return r;
  4678. };
  4679. /**
  4680. * Subtracts the width and height of two
  4681. * @param otherSize size to subtract to this size
  4682. * @returns a new Size set as the subtraction result of the given one from the current Size.
  4683. */
  4684. Size.prototype.subtract = function (otherSize) {
  4685. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4686. return r;
  4687. };
  4688. /**
  4689. * Creates a new Size set at the linear interpolation "amount" between "start" and "end"
  4690. * @param start starting size to lerp between
  4691. * @param end end size to lerp between
  4692. * @param amount amount to lerp between the start and end values
  4693. * @returns a new Size set at the linear interpolation "amount" between "start" and "end"
  4694. */
  4695. Size.Lerp = function (start, end, amount) {
  4696. var w = start.width + ((end.width - start.width) * amount);
  4697. var h = start.height + ((end.height - start.height) * amount);
  4698. return new Size(w, h);
  4699. };
  4700. return Size;
  4701. }());
  4702. BABYLON.Size = Size;
  4703. /**
  4704. * Class used to store quaternion data
  4705. * @see https://en.wikipedia.org/wiki/Quaternion
  4706. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4707. */
  4708. var Quaternion = /** @class */ (function () {
  4709. /**
  4710. * Creates a new Quaternion from the given floats
  4711. * @param x defines the first component (0 by default)
  4712. * @param y defines the second component (0 by default)
  4713. * @param z defines the third component (0 by default)
  4714. * @param w defines the fourth component (1.0 by default)
  4715. */
  4716. function Quaternion(
  4717. /** defines the first component (0 by default) */
  4718. x,
  4719. /** defines the second component (0 by default) */
  4720. y,
  4721. /** defines the third component (0 by default) */
  4722. z,
  4723. /** defines the fourth component (1.0 by default) */
  4724. w) {
  4725. if (x === void 0) { x = 0.0; }
  4726. if (y === void 0) { y = 0.0; }
  4727. if (z === void 0) { z = 0.0; }
  4728. if (w === void 0) { w = 1.0; }
  4729. this.x = x;
  4730. this.y = y;
  4731. this.z = z;
  4732. this.w = w;
  4733. }
  4734. /**
  4735. * Gets a string representation for the current quaternion
  4736. * @returns a string with the Quaternion coordinates
  4737. */
  4738. Quaternion.prototype.toString = function () {
  4739. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4740. };
  4741. /**
  4742. * Gets the class name of the quaternion
  4743. * @returns the string "Quaternion"
  4744. */
  4745. Quaternion.prototype.getClassName = function () {
  4746. return "Quaternion";
  4747. };
  4748. /**
  4749. * Gets a hash code for this quaternion
  4750. * @returns the quaternion hash code
  4751. */
  4752. Quaternion.prototype.getHashCode = function () {
  4753. var hash = this.x || 0;
  4754. hash = (hash * 397) ^ (this.y || 0);
  4755. hash = (hash * 397) ^ (this.z || 0);
  4756. hash = (hash * 397) ^ (this.w || 0);
  4757. return hash;
  4758. };
  4759. /**
  4760. * Copy the quaternion to an array
  4761. * @returns a new array populated with 4 elements from the quaternion coordinates
  4762. */
  4763. Quaternion.prototype.asArray = function () {
  4764. return [this.x, this.y, this.z, this.w];
  4765. };
  4766. /**
  4767. * Check if two quaternions are equals
  4768. * @param otherQuaternion defines the second operand
  4769. * @return true if the current quaternion and the given one coordinates are strictly equals
  4770. */
  4771. Quaternion.prototype.equals = function (otherQuaternion) {
  4772. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4773. };
  4774. /**
  4775. * Clone the current quaternion
  4776. * @returns a new quaternion copied from the current one
  4777. */
  4778. Quaternion.prototype.clone = function () {
  4779. return new Quaternion(this.x, this.y, this.z, this.w);
  4780. };
  4781. /**
  4782. * Copy a quaternion to the current one
  4783. * @param other defines the other quaternion
  4784. * @returns the updated current quaternion
  4785. */
  4786. Quaternion.prototype.copyFrom = function (other) {
  4787. this.x = other.x;
  4788. this.y = other.y;
  4789. this.z = other.z;
  4790. this.w = other.w;
  4791. return this;
  4792. };
  4793. /**
  4794. * Updates the current quaternion with the given float coordinates
  4795. * @param x defines the x coordinate
  4796. * @param y defines the y coordinate
  4797. * @param z defines the z coordinate
  4798. * @param w defines the w coordinate
  4799. * @returns the updated current quaternion
  4800. */
  4801. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4802. this.x = x;
  4803. this.y = y;
  4804. this.z = z;
  4805. this.w = w;
  4806. return this;
  4807. };
  4808. /**
  4809. * Updates the current quaternion from the given float coordinates
  4810. * @param x defines the x coordinate
  4811. * @param y defines the y coordinate
  4812. * @param z defines the z coordinate
  4813. * @param w defines the w coordinate
  4814. * @returns the updated current quaternion
  4815. */
  4816. Quaternion.prototype.set = function (x, y, z, w) {
  4817. return this.copyFromFloats(x, y, z, w);
  4818. };
  4819. /**
  4820. * Adds two quaternions
  4821. * @param other defines the second operand
  4822. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4823. */
  4824. Quaternion.prototype.add = function (other) {
  4825. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4826. };
  4827. /**
  4828. * Add a quaternion to the current one
  4829. * @param other defines the quaternion to add
  4830. * @returns the current quaternion
  4831. */
  4832. Quaternion.prototype.addInPlace = function (other) {
  4833. this.x += other.x;
  4834. this.y += other.y;
  4835. this.z += other.z;
  4836. this.w += other.w;
  4837. return this;
  4838. };
  4839. /**
  4840. * Subtract two quaternions
  4841. * @param other defines the second operand
  4842. * @returns a new quaternion as the subtraction result of the given one from the current one
  4843. */
  4844. Quaternion.prototype.subtract = function (other) {
  4845. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4846. };
  4847. /**
  4848. * Multiplies the current quaternion by a scale factor
  4849. * @param value defines the scale factor
  4850. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4851. */
  4852. Quaternion.prototype.scale = function (value) {
  4853. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4854. };
  4855. /**
  4856. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4857. * @param scale defines the scale factor
  4858. * @param result defines the Quaternion object where to store the result
  4859. * @returns the unmodified current quaternion
  4860. */
  4861. Quaternion.prototype.scaleToRef = function (scale, result) {
  4862. result.x = this.x * scale;
  4863. result.y = this.y * scale;
  4864. result.z = this.z * scale;
  4865. result.w = this.w * scale;
  4866. return this;
  4867. };
  4868. /**
  4869. * Multiplies in place the current quaternion by a scale factor
  4870. * @param value defines the scale factor
  4871. * @returns the current modified quaternion
  4872. */
  4873. Quaternion.prototype.scaleInPlace = function (value) {
  4874. this.x *= value;
  4875. this.y *= value;
  4876. this.z *= value;
  4877. this.w *= value;
  4878. return this;
  4879. };
  4880. /**
  4881. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4882. * @param scale defines the scale factor
  4883. * @param result defines the Quaternion object where to store the result
  4884. * @returns the unmodified current quaternion
  4885. */
  4886. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4887. result.x += this.x * scale;
  4888. result.y += this.y * scale;
  4889. result.z += this.z * scale;
  4890. result.w += this.w * scale;
  4891. return this;
  4892. };
  4893. /**
  4894. * Multiplies two quaternions
  4895. * @param q1 defines the second operand
  4896. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4897. */
  4898. Quaternion.prototype.multiply = function (q1) {
  4899. var result = new Quaternion(0, 0, 0, 1.0);
  4900. this.multiplyToRef(q1, result);
  4901. return result;
  4902. };
  4903. /**
  4904. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4905. * @param q1 defines the second operand
  4906. * @param result defines the target quaternion
  4907. * @returns the current quaternion
  4908. */
  4909. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4910. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4911. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4912. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4913. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4914. result.copyFromFloats(x, y, z, w);
  4915. return this;
  4916. };
  4917. /**
  4918. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4919. * @param q1 defines the second operand
  4920. * @returns the currentupdated quaternion
  4921. */
  4922. Quaternion.prototype.multiplyInPlace = function (q1) {
  4923. this.multiplyToRef(q1, this);
  4924. return this;
  4925. };
  4926. /**
  4927. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4928. * @param ref defines the target quaternion
  4929. * @returns the current quaternion
  4930. */
  4931. Quaternion.prototype.conjugateToRef = function (ref) {
  4932. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4933. return this;
  4934. };
  4935. /**
  4936. * Conjugates in place (1-q) the current quaternion
  4937. * @returns the current updated quaternion
  4938. */
  4939. Quaternion.prototype.conjugateInPlace = function () {
  4940. this.x *= -1;
  4941. this.y *= -1;
  4942. this.z *= -1;
  4943. return this;
  4944. };
  4945. /**
  4946. * Conjugates in place (1-q) the current quaternion
  4947. * @returns a new quaternion
  4948. */
  4949. Quaternion.prototype.conjugate = function () {
  4950. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4951. return result;
  4952. };
  4953. /**
  4954. * Gets length of current quaternion
  4955. * @returns the quaternion length (float)
  4956. */
  4957. Quaternion.prototype.length = function () {
  4958. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4959. };
  4960. /**
  4961. * Normalize in place the current quaternion
  4962. * @returns the current updated quaternion
  4963. */
  4964. Quaternion.prototype.normalize = function () {
  4965. var length = 1.0 / this.length();
  4966. this.x *= length;
  4967. this.y *= length;
  4968. this.z *= length;
  4969. this.w *= length;
  4970. return this;
  4971. };
  4972. /**
  4973. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4974. * @param order is a reserved parameter and is ignore for now
  4975. * @returns a new Vector3 containing the Euler angles
  4976. */
  4977. Quaternion.prototype.toEulerAngles = function (order) {
  4978. if (order === void 0) { order = "YZX"; }
  4979. var result = Vector3.Zero();
  4980. this.toEulerAnglesToRef(result, order);
  4981. return result;
  4982. };
  4983. /**
  4984. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4985. * @param result defines the vector which will be filled with the Euler angles
  4986. * @param order is a reserved parameter and is ignore for now
  4987. * @returns the current unchanged quaternion
  4988. */
  4989. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4990. if (order === void 0) { order = "YZX"; }
  4991. var qz = this.z;
  4992. var qx = this.x;
  4993. var qy = this.y;
  4994. var qw = this.w;
  4995. var sqw = qw * qw;
  4996. var sqz = qz * qz;
  4997. var sqx = qx * qx;
  4998. var sqy = qy * qy;
  4999. var zAxisY = qy * qz - qx * qw;
  5000. var limit = .4999999;
  5001. if (zAxisY < -limit) {
  5002. result.y = 2 * Math.atan2(qy, qw);
  5003. result.x = Math.PI / 2;
  5004. result.z = 0;
  5005. }
  5006. else if (zAxisY > limit) {
  5007. result.y = 2 * Math.atan2(qy, qw);
  5008. result.x = -Math.PI / 2;
  5009. result.z = 0;
  5010. }
  5011. else {
  5012. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  5013. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  5014. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  5015. }
  5016. return this;
  5017. };
  5018. /**
  5019. * Updates the given rotation matrix with the current quaternion values
  5020. * @param result defines the target matrix
  5021. * @returns the current unchanged quaternion
  5022. */
  5023. Quaternion.prototype.toRotationMatrix = function (result) {
  5024. var xx = this.x * this.x;
  5025. var yy = this.y * this.y;
  5026. var zz = this.z * this.z;
  5027. var xy = this.x * this.y;
  5028. var zw = this.z * this.w;
  5029. var zx = this.z * this.x;
  5030. var yw = this.y * this.w;
  5031. var yz = this.y * this.z;
  5032. var xw = this.x * this.w;
  5033. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5034. result.m[1] = 2.0 * (xy + zw);
  5035. result.m[2] = 2.0 * (zx - yw);
  5036. result.m[3] = 0;
  5037. result.m[4] = 2.0 * (xy - zw);
  5038. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5039. result.m[6] = 2.0 * (yz + xw);
  5040. result.m[7] = 0;
  5041. result.m[8] = 2.0 * (zx + yw);
  5042. result.m[9] = 2.0 * (yz - xw);
  5043. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5044. result.m[11] = 0;
  5045. result.m[12] = 0;
  5046. result.m[13] = 0;
  5047. result.m[14] = 0;
  5048. result.m[15] = 1.0;
  5049. result._markAsUpdated();
  5050. return this;
  5051. };
  5052. /**
  5053. * Updates the current quaternion from the given rotation matrix values
  5054. * @param matrix defines the source matrix
  5055. * @returns the current updated quaternion
  5056. */
  5057. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  5058. Quaternion.FromRotationMatrixToRef(matrix, this);
  5059. return this;
  5060. };
  5061. // Statics
  5062. /**
  5063. * Creates a new quaternion from a rotation matrix
  5064. * @param matrix defines the source matrix
  5065. * @returns a new quaternion created from the given rotation matrix values
  5066. */
  5067. Quaternion.FromRotationMatrix = function (matrix) {
  5068. var result = new Quaternion();
  5069. Quaternion.FromRotationMatrixToRef(matrix, result);
  5070. return result;
  5071. };
  5072. /**
  5073. * Updates the given quaternion with the given rotation matrix values
  5074. * @param matrix defines the source matrix
  5075. * @param result defines the target quaternion
  5076. */
  5077. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  5078. var data = matrix.m;
  5079. var m11 = data[0], m12 = data[4], m13 = data[8];
  5080. var m21 = data[1], m22 = data[5], m23 = data[9];
  5081. var m31 = data[2], m32 = data[6], m33 = data[10];
  5082. var trace = m11 + m22 + m33;
  5083. var s;
  5084. if (trace > 0) {
  5085. s = 0.5 / Math.sqrt(trace + 1.0);
  5086. result.w = 0.25 / s;
  5087. result.x = (m32 - m23) * s;
  5088. result.y = (m13 - m31) * s;
  5089. result.z = (m21 - m12) * s;
  5090. }
  5091. else if (m11 > m22 && m11 > m33) {
  5092. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  5093. result.w = (m32 - m23) / s;
  5094. result.x = 0.25 * s;
  5095. result.y = (m12 + m21) / s;
  5096. result.z = (m13 + m31) / s;
  5097. }
  5098. else if (m22 > m33) {
  5099. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  5100. result.w = (m13 - m31) / s;
  5101. result.x = (m12 + m21) / s;
  5102. result.y = 0.25 * s;
  5103. result.z = (m23 + m32) / s;
  5104. }
  5105. else {
  5106. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  5107. result.w = (m21 - m12) / s;
  5108. result.x = (m13 + m31) / s;
  5109. result.y = (m23 + m32) / s;
  5110. result.z = 0.25 * s;
  5111. }
  5112. };
  5113. /**
  5114. * Returns the dot product (float) between the quaternions "left" and "right"
  5115. * @param left defines the left operand
  5116. * @param right defines the right operand
  5117. * @returns the dot product
  5118. */
  5119. Quaternion.Dot = function (left, right) {
  5120. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  5121. };
  5122. /**
  5123. * Checks if the two quaternions are close to each other
  5124. * @param quat0 defines the first quaternion to check
  5125. * @param quat1 defines the second quaternion to check
  5126. * @returns true if the two quaternions are close to each other
  5127. */
  5128. Quaternion.AreClose = function (quat0, quat1) {
  5129. var dot = Quaternion.Dot(quat0, quat1);
  5130. return dot >= 0;
  5131. };
  5132. /**
  5133. * Creates an empty quaternion
  5134. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  5135. */
  5136. Quaternion.Zero = function () {
  5137. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  5138. };
  5139. /**
  5140. * Inverse a given quaternion
  5141. * @param q defines the source quaternion
  5142. * @returns a new quaternion as the inverted current quaternion
  5143. */
  5144. Quaternion.Inverse = function (q) {
  5145. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  5146. };
  5147. /**
  5148. * Creates an identity quaternion
  5149. * @returns the identity quaternion
  5150. */
  5151. Quaternion.Identity = function () {
  5152. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  5153. };
  5154. /**
  5155. * Gets a boolean indicating if the given quaternion is identity
  5156. * @param quaternion defines the quaternion to check
  5157. * @returns true if the quaternion is identity
  5158. */
  5159. Quaternion.IsIdentity = function (quaternion) {
  5160. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  5161. };
  5162. /**
  5163. * Creates a quaternion from a rotation around an axis
  5164. * @param axis defines the axis to use
  5165. * @param angle defines the angle to use
  5166. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  5167. */
  5168. Quaternion.RotationAxis = function (axis, angle) {
  5169. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  5170. };
  5171. /**
  5172. * Creates a rotation around an axis and stores it into the given quaternion
  5173. * @param axis defines the axis to use
  5174. * @param angle defines the angle to use
  5175. * @param result defines the target quaternion
  5176. * @returns the target quaternion
  5177. */
  5178. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  5179. var sin = Math.sin(angle / 2);
  5180. axis.normalize();
  5181. result.w = Math.cos(angle / 2);
  5182. result.x = axis.x * sin;
  5183. result.y = axis.y * sin;
  5184. result.z = axis.z * sin;
  5185. return result;
  5186. };
  5187. /**
  5188. * Creates a new quaternion from data stored into an array
  5189. * @param array defines the data source
  5190. * @param offset defines the offset in the source array where the data starts
  5191. * @returns a new quaternion
  5192. */
  5193. Quaternion.FromArray = function (array, offset) {
  5194. if (!offset) {
  5195. offset = 0;
  5196. }
  5197. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  5198. };
  5199. /**
  5200. * Creates a new quaternion from the given Euler float angles (y, x, z)
  5201. * @param yaw defines the rotation around Y axis
  5202. * @param pitch defines the rotation around X axis
  5203. * @param roll defines the rotation around Z axis
  5204. * @returns the new quaternion
  5205. */
  5206. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5207. var q = new Quaternion();
  5208. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  5209. return q;
  5210. };
  5211. /**
  5212. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  5213. * @param yaw defines the rotation around Y axis
  5214. * @param pitch defines the rotation around X axis
  5215. * @param roll defines the rotation around Z axis
  5216. * @param result defines the target quaternion
  5217. */
  5218. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5219. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  5220. var halfRoll = roll * 0.5;
  5221. var halfPitch = pitch * 0.5;
  5222. var halfYaw = yaw * 0.5;
  5223. var sinRoll = Math.sin(halfRoll);
  5224. var cosRoll = Math.cos(halfRoll);
  5225. var sinPitch = Math.sin(halfPitch);
  5226. var cosPitch = Math.cos(halfPitch);
  5227. var sinYaw = Math.sin(halfYaw);
  5228. var cosYaw = Math.cos(halfYaw);
  5229. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  5230. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  5231. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  5232. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  5233. };
  5234. /**
  5235. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  5236. * @param alpha defines the rotation around first axis
  5237. * @param beta defines the rotation around second axis
  5238. * @param gamma defines the rotation around third axis
  5239. * @returns the new quaternion
  5240. */
  5241. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  5242. var result = new Quaternion();
  5243. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  5244. return result;
  5245. };
  5246. /**
  5247. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5248. * @param alpha defines the rotation around first axis
  5249. * @param beta defines the rotation around second axis
  5250. * @param gamma defines the rotation around third axis
  5251. * @param result defines the target quaternion
  5252. */
  5253. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5254. // Produces a quaternion from Euler angles in the z-x-z orientation
  5255. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5256. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5257. var halfBeta = beta * 0.5;
  5258. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5259. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5260. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5261. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5262. };
  5263. /**
  5264. * 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)
  5265. * @param axis1 defines the first axis
  5266. * @param axis2 defines the second axis
  5267. * @param axis3 defines the third axis
  5268. * @returns the new quaternion
  5269. */
  5270. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5271. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5272. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5273. return quat;
  5274. };
  5275. /**
  5276. * 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
  5277. * @param axis1 defines the first axis
  5278. * @param axis2 defines the second axis
  5279. * @param axis3 defines the third axis
  5280. * @param ref defines the target quaternion
  5281. */
  5282. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5283. var rotMat = MathTmp.Matrix[0];
  5284. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5285. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5286. };
  5287. /**
  5288. * Interpolates between two quaternions
  5289. * @param left defines first quaternion
  5290. * @param right defines second quaternion
  5291. * @param amount defines the gradient to use
  5292. * @returns the new interpolated quaternion
  5293. */
  5294. Quaternion.Slerp = function (left, right, amount) {
  5295. var result = Quaternion.Identity();
  5296. Quaternion.SlerpToRef(left, right, amount, result);
  5297. return result;
  5298. };
  5299. /**
  5300. * Interpolates between two quaternions and stores it into a target quaternion
  5301. * @param left defines first quaternion
  5302. * @param right defines second quaternion
  5303. * @param amount defines the gradient to use
  5304. * @param result defines the target quaternion
  5305. */
  5306. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5307. var num2;
  5308. var num3;
  5309. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5310. var flag = false;
  5311. if (num4 < 0) {
  5312. flag = true;
  5313. num4 = -num4;
  5314. }
  5315. if (num4 > 0.999999) {
  5316. num3 = 1 - amount;
  5317. num2 = flag ? -amount : amount;
  5318. }
  5319. else {
  5320. var num5 = Math.acos(num4);
  5321. var num6 = (1.0 / Math.sin(num5));
  5322. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5323. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5324. }
  5325. result.x = (num3 * left.x) + (num2 * right.x);
  5326. result.y = (num3 * left.y) + (num2 * right.y);
  5327. result.z = (num3 * left.z) + (num2 * right.z);
  5328. result.w = (num3 * left.w) + (num2 * right.w);
  5329. };
  5330. /**
  5331. * Interpolate between two quaternions using Hermite interpolation
  5332. * @param value1 defines first quaternion
  5333. * @param tangent1 defines the incoming tangent
  5334. * @param value2 defines second quaternion
  5335. * @param tangent2 defines the outgoing tangent
  5336. * @param amount defines the target quaternion
  5337. * @returns the new interpolated quaternion
  5338. */
  5339. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5340. var squared = amount * amount;
  5341. var cubed = amount * squared;
  5342. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5343. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5344. var part3 = (cubed - (2.0 * squared)) + amount;
  5345. var part4 = cubed - squared;
  5346. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5347. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5348. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5349. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5350. return new Quaternion(x, y, z, w);
  5351. };
  5352. return Quaternion;
  5353. }());
  5354. BABYLON.Quaternion = Quaternion;
  5355. /**
  5356. * Class used to store matrix data (4x4)
  5357. */
  5358. var Matrix = /** @class */ (function () {
  5359. /**
  5360. * Creates an empty matrix (filled with zeros)
  5361. */
  5362. function Matrix() {
  5363. this._isIdentity = false;
  5364. this._isIdentityDirty = true;
  5365. /**
  5366. * Gets or sets the internal data of the matrix
  5367. */
  5368. this.m = new Float32Array(16);
  5369. this._markAsUpdated();
  5370. }
  5371. /** @hidden */
  5372. Matrix.prototype._markAsUpdated = function () {
  5373. this.updateFlag = Matrix._updateFlagSeed++;
  5374. this._isIdentityDirty = true;
  5375. };
  5376. // Properties
  5377. /**
  5378. * Check if the current matrix is indentity
  5379. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5380. * @returns true is the matrix is the identity matrix
  5381. */
  5382. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5383. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5384. if (this._isIdentityDirty) {
  5385. this._isIdentityDirty = false;
  5386. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5387. this._isIdentity = false;
  5388. }
  5389. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5390. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5391. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5392. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5393. this._isIdentity = false;
  5394. }
  5395. else {
  5396. this._isIdentity = true;
  5397. }
  5398. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5399. this._isIdentity = false;
  5400. }
  5401. }
  5402. return this._isIdentity;
  5403. };
  5404. /**
  5405. * Gets the determinant of the matrix
  5406. * @returns the matrix determinant
  5407. */
  5408. Matrix.prototype.determinant = function () {
  5409. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5410. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5411. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5412. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5413. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5414. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5415. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5416. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5417. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5418. };
  5419. // Methods
  5420. /**
  5421. * Returns the matrix as a Float32Array
  5422. * @returns the matrix underlying array
  5423. */
  5424. Matrix.prototype.toArray = function () {
  5425. return this.m;
  5426. };
  5427. /**
  5428. * Returns the matrix as a Float32Array
  5429. * @returns the matrix underlying array.
  5430. */
  5431. Matrix.prototype.asArray = function () {
  5432. return this.toArray();
  5433. };
  5434. /**
  5435. * Inverts the current matrix in place
  5436. * @returns the current inverted matrix
  5437. */
  5438. Matrix.prototype.invert = function () {
  5439. this.invertToRef(this);
  5440. return this;
  5441. };
  5442. /**
  5443. * Sets all the matrix elements to zero
  5444. * @returns the current matrix
  5445. */
  5446. Matrix.prototype.reset = function () {
  5447. for (var index = 0; index < 16; index++) {
  5448. this.m[index] = 0.0;
  5449. }
  5450. this._markAsUpdated();
  5451. return this;
  5452. };
  5453. /**
  5454. * Adds the current matrix with a second one
  5455. * @param other defines the matrix to add
  5456. * @returns a new matrix as the addition of the current matrix and the given one
  5457. */
  5458. Matrix.prototype.add = function (other) {
  5459. var result = new Matrix();
  5460. this.addToRef(other, result);
  5461. return result;
  5462. };
  5463. /**
  5464. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5465. * @param other defines the matrix to add
  5466. * @param result defines the target matrix
  5467. * @returns the current matrix
  5468. */
  5469. Matrix.prototype.addToRef = function (other, result) {
  5470. for (var index = 0; index < 16; index++) {
  5471. result.m[index] = this.m[index] + other.m[index];
  5472. }
  5473. result._markAsUpdated();
  5474. return this;
  5475. };
  5476. /**
  5477. * Adds in place the given matrix to the current matrix
  5478. * @param other defines the second operand
  5479. * @returns the current updated matrix
  5480. */
  5481. Matrix.prototype.addToSelf = function (other) {
  5482. for (var index = 0; index < 16; index++) {
  5483. this.m[index] += other.m[index];
  5484. }
  5485. this._markAsUpdated();
  5486. return this;
  5487. };
  5488. /**
  5489. * Sets the given matrix to the current inverted Matrix
  5490. * @param other defines the target matrix
  5491. * @returns the unmodified current matrix
  5492. */
  5493. Matrix.prototype.invertToRef = function (other) {
  5494. var l1 = this.m[0];
  5495. var l2 = this.m[1];
  5496. var l3 = this.m[2];
  5497. var l4 = this.m[3];
  5498. var l5 = this.m[4];
  5499. var l6 = this.m[5];
  5500. var l7 = this.m[6];
  5501. var l8 = this.m[7];
  5502. var l9 = this.m[8];
  5503. var l10 = this.m[9];
  5504. var l11 = this.m[10];
  5505. var l12 = this.m[11];
  5506. var l13 = this.m[12];
  5507. var l14 = this.m[13];
  5508. var l15 = this.m[14];
  5509. var l16 = this.m[15];
  5510. var l17 = (l11 * l16) - (l12 * l15);
  5511. var l18 = (l10 * l16) - (l12 * l14);
  5512. var l19 = (l10 * l15) - (l11 * l14);
  5513. var l20 = (l9 * l16) - (l12 * l13);
  5514. var l21 = (l9 * l15) - (l11 * l13);
  5515. var l22 = (l9 * l14) - (l10 * l13);
  5516. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5517. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5518. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5519. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5520. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5521. var l28 = (l7 * l16) - (l8 * l15);
  5522. var l29 = (l6 * l16) - (l8 * l14);
  5523. var l30 = (l6 * l15) - (l7 * l14);
  5524. var l31 = (l5 * l16) - (l8 * l13);
  5525. var l32 = (l5 * l15) - (l7 * l13);
  5526. var l33 = (l5 * l14) - (l6 * l13);
  5527. var l34 = (l7 * l12) - (l8 * l11);
  5528. var l35 = (l6 * l12) - (l8 * l10);
  5529. var l36 = (l6 * l11) - (l7 * l10);
  5530. var l37 = (l5 * l12) - (l8 * l9);
  5531. var l38 = (l5 * l11) - (l7 * l9);
  5532. var l39 = (l5 * l10) - (l6 * l9);
  5533. other.m[0] = l23 * l27;
  5534. other.m[4] = l24 * l27;
  5535. other.m[8] = l25 * l27;
  5536. other.m[12] = l26 * l27;
  5537. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5538. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5539. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5540. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5541. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5542. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5543. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5544. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5545. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5546. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5547. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5548. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5549. other._markAsUpdated();
  5550. return this;
  5551. };
  5552. /**
  5553. * Inserts the translation vector (using 3 floats) in the current matrix
  5554. * @param x defines the 1st component of the translation
  5555. * @param y defines the 2nd component of the translation
  5556. * @param z defines the 3rd component of the translation
  5557. * @returns the current updated matrix
  5558. */
  5559. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5560. this.m[12] = x;
  5561. this.m[13] = y;
  5562. this.m[14] = z;
  5563. this._markAsUpdated();
  5564. return this;
  5565. };
  5566. /**
  5567. * Inserts the translation vector in the current matrix
  5568. * @param vector3 defines the translation to insert
  5569. * @returns the current updated matrix
  5570. */
  5571. Matrix.prototype.setTranslation = function (vector3) {
  5572. this.m[12] = vector3.x;
  5573. this.m[13] = vector3.y;
  5574. this.m[14] = vector3.z;
  5575. this._markAsUpdated();
  5576. return this;
  5577. };
  5578. /**
  5579. * Gets the translation value of the current matrix
  5580. * @returns a new Vector3 as the extracted translation from the matrix
  5581. */
  5582. Matrix.prototype.getTranslation = function () {
  5583. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5584. };
  5585. /**
  5586. * Fill a Vector3 with the extracted translation from the matrix
  5587. * @param result defines the Vector3 where to store the translation
  5588. * @returns the current matrix
  5589. */
  5590. Matrix.prototype.getTranslationToRef = function (result) {
  5591. result.x = this.m[12];
  5592. result.y = this.m[13];
  5593. result.z = this.m[14];
  5594. return this;
  5595. };
  5596. /**
  5597. * Remove rotation and scaling part from the matrix
  5598. * @returns the updated matrix
  5599. */
  5600. Matrix.prototype.removeRotationAndScaling = function () {
  5601. this.setRowFromFloats(0, 1, 0, 0, 0);
  5602. this.setRowFromFloats(1, 0, 1, 0, 0);
  5603. this.setRowFromFloats(2, 0, 0, 1, 0);
  5604. return this;
  5605. };
  5606. /**
  5607. * Multiply two matrices
  5608. * @param other defines the second operand
  5609. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5610. */
  5611. Matrix.prototype.multiply = function (other) {
  5612. var result = new Matrix();
  5613. this.multiplyToRef(other, result);
  5614. return result;
  5615. };
  5616. /**
  5617. * Copy the current matrix from the given one
  5618. * @param other defines the source matrix
  5619. * @returns the current updated matrix
  5620. */
  5621. Matrix.prototype.copyFrom = function (other) {
  5622. for (var index = 0; index < 16; index++) {
  5623. this.m[index] = other.m[index];
  5624. }
  5625. this._markAsUpdated();
  5626. return this;
  5627. };
  5628. /**
  5629. * Populates the given array from the starting index with the current matrix values
  5630. * @param array defines the target array
  5631. * @param offset defines the offset in the target array where to start storing values
  5632. * @returns the current matrix
  5633. */
  5634. Matrix.prototype.copyToArray = function (array, offset) {
  5635. if (offset === void 0) { offset = 0; }
  5636. for (var index = 0; index < 16; index++) {
  5637. array[offset + index] = this.m[index];
  5638. }
  5639. return this;
  5640. };
  5641. /**
  5642. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5643. * @param other defines the second operand
  5644. * @param result defines the matrix where to store the multiplication
  5645. * @returns the current matrix
  5646. */
  5647. Matrix.prototype.multiplyToRef = function (other, result) {
  5648. this.multiplyToArray(other, result.m, 0);
  5649. result._markAsUpdated();
  5650. return this;
  5651. };
  5652. /**
  5653. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5654. * @param other defines the second operand
  5655. * @param result defines the array where to store the multiplication
  5656. * @param offset defines the offset in the target array where to start storing values
  5657. * @returns the current matrix
  5658. */
  5659. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5660. var tm0 = this.m[0];
  5661. var tm1 = this.m[1];
  5662. var tm2 = this.m[2];
  5663. var tm3 = this.m[3];
  5664. var tm4 = this.m[4];
  5665. var tm5 = this.m[5];
  5666. var tm6 = this.m[6];
  5667. var tm7 = this.m[7];
  5668. var tm8 = this.m[8];
  5669. var tm9 = this.m[9];
  5670. var tm10 = this.m[10];
  5671. var tm11 = this.m[11];
  5672. var tm12 = this.m[12];
  5673. var tm13 = this.m[13];
  5674. var tm14 = this.m[14];
  5675. var tm15 = this.m[15];
  5676. var om0 = other.m[0];
  5677. var om1 = other.m[1];
  5678. var om2 = other.m[2];
  5679. var om3 = other.m[3];
  5680. var om4 = other.m[4];
  5681. var om5 = other.m[5];
  5682. var om6 = other.m[6];
  5683. var om7 = other.m[7];
  5684. var om8 = other.m[8];
  5685. var om9 = other.m[9];
  5686. var om10 = other.m[10];
  5687. var om11 = other.m[11];
  5688. var om12 = other.m[12];
  5689. var om13 = other.m[13];
  5690. var om14 = other.m[14];
  5691. var om15 = other.m[15];
  5692. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5693. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5694. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5695. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5696. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5697. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5698. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5699. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5700. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5701. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5702. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5703. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5704. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5705. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5706. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5707. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5708. return this;
  5709. };
  5710. /**
  5711. * Check equality between this matrix and a second one
  5712. * @param value defines the second matrix to compare
  5713. * @returns true is the current matrix and the given one values are strictly equal
  5714. */
  5715. Matrix.prototype.equals = function (value) {
  5716. return value &&
  5717. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5718. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5719. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5720. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5721. };
  5722. /**
  5723. * Clone the current matrix
  5724. * @returns a new matrix from the current matrix
  5725. */
  5726. Matrix.prototype.clone = function () {
  5727. 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]);
  5728. };
  5729. /**
  5730. * Returns the name of the current matrix class
  5731. * @returns the string "Matrix"
  5732. */
  5733. Matrix.prototype.getClassName = function () {
  5734. return "Matrix";
  5735. };
  5736. /**
  5737. * Gets the hash code of the current matrix
  5738. * @returns the hash code
  5739. */
  5740. Matrix.prototype.getHashCode = function () {
  5741. var hash = this.m[0] || 0;
  5742. for (var i = 1; i < 16; i++) {
  5743. hash = (hash * 397) ^ (this.m[i] || 0);
  5744. }
  5745. return hash;
  5746. };
  5747. /**
  5748. * Decomposes the current Matrix into a translation, rotation and scaling components
  5749. * @param scale defines the scale vector3 given as a reference to update
  5750. * @param rotation defines the rotation quaternion given as a reference to update
  5751. * @param translation defines the translation vector3 given as a reference to update
  5752. * @returns true if operation was successful
  5753. */
  5754. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5755. if (translation) {
  5756. translation.x = this.m[12];
  5757. translation.y = this.m[13];
  5758. translation.z = this.m[14];
  5759. }
  5760. scale = scale || MathTmp.Vector3[0];
  5761. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5762. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5763. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5764. if (this.determinant() <= 0) {
  5765. scale.y *= -1;
  5766. }
  5767. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5768. if (rotation) {
  5769. rotation.x = 0;
  5770. rotation.y = 0;
  5771. rotation.z = 0;
  5772. rotation.w = 1;
  5773. }
  5774. return false;
  5775. }
  5776. if (rotation) {
  5777. 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]);
  5778. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5779. }
  5780. return true;
  5781. };
  5782. /**
  5783. * Gets specific row of the matrix
  5784. * @param index defines the number of the row to get
  5785. * @returns the index-th row of the current matrix as a new Vector4
  5786. */
  5787. Matrix.prototype.getRow = function (index) {
  5788. if (index < 0 || index > 3) {
  5789. return null;
  5790. }
  5791. var i = index * 4;
  5792. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5793. };
  5794. /**
  5795. * Sets the index-th row of the current matrix to the vector4 values
  5796. * @param index defines the number of the row to set
  5797. * @param row defines the target vector4
  5798. * @returns the updated current matrix
  5799. */
  5800. Matrix.prototype.setRow = function (index, row) {
  5801. if (index < 0 || index > 3) {
  5802. return this;
  5803. }
  5804. var i = index * 4;
  5805. this.m[i + 0] = row.x;
  5806. this.m[i + 1] = row.y;
  5807. this.m[i + 2] = row.z;
  5808. this.m[i + 3] = row.w;
  5809. this._markAsUpdated();
  5810. return this;
  5811. };
  5812. /**
  5813. * Compute the transpose of the matrix
  5814. * @returns the new transposed matrix
  5815. */
  5816. Matrix.prototype.transpose = function () {
  5817. return Matrix.Transpose(this);
  5818. };
  5819. /**
  5820. * Compute the transpose of the matrix and store it in a given matrix
  5821. * @param result defines the target matrix
  5822. * @returns the current matrix
  5823. */
  5824. Matrix.prototype.transposeToRef = function (result) {
  5825. Matrix.TransposeToRef(this, result);
  5826. return this;
  5827. };
  5828. /**
  5829. * Sets the index-th row of the current matrix with the given 4 x float values
  5830. * @param index defines the row index
  5831. * @param x defines the x component to set
  5832. * @param y defines the y component to set
  5833. * @param z defines the z component to set
  5834. * @param w defines the w component to set
  5835. * @returns the updated current matrix
  5836. */
  5837. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5838. if (index < 0 || index > 3) {
  5839. return this;
  5840. }
  5841. var i = index * 4;
  5842. this.m[i + 0] = x;
  5843. this.m[i + 1] = y;
  5844. this.m[i + 2] = z;
  5845. this.m[i + 3] = w;
  5846. this._markAsUpdated();
  5847. return this;
  5848. };
  5849. /**
  5850. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5851. * @param scale defines the scale factor
  5852. * @returns a new matrix
  5853. */
  5854. Matrix.prototype.scale = function (scale) {
  5855. var result = new Matrix();
  5856. this.scaleToRef(scale, result);
  5857. return result;
  5858. };
  5859. /**
  5860. * Scale the current matrix values by a factor to a given result matrix
  5861. * @param scale defines the scale factor
  5862. * @param result defines the matrix to store the result
  5863. * @returns the current matrix
  5864. */
  5865. Matrix.prototype.scaleToRef = function (scale, result) {
  5866. for (var index = 0; index < 16; index++) {
  5867. result.m[index] = this.m[index] * scale;
  5868. }
  5869. result._markAsUpdated();
  5870. return this;
  5871. };
  5872. /**
  5873. * Scale the current matrix values by a factor and add the result to a given matrix
  5874. * @param scale defines the scale factor
  5875. * @param result defines the Matrix to store the result
  5876. * @returns the current matrix
  5877. */
  5878. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5879. for (var index = 0; index < 16; index++) {
  5880. result.m[index] += this.m[index] * scale;
  5881. }
  5882. result._markAsUpdated();
  5883. return this;
  5884. };
  5885. /**
  5886. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5887. * @param ref matrix to store the result
  5888. */
  5889. Matrix.prototype.toNormalMatrix = function (ref) {
  5890. this.invertToRef(ref);
  5891. ref.transpose();
  5892. var m = ref.m;
  5893. 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);
  5894. };
  5895. /**
  5896. * Gets only rotation part of the current matrix
  5897. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5898. */
  5899. Matrix.prototype.getRotationMatrix = function () {
  5900. var result = Matrix.Identity();
  5901. this.getRotationMatrixToRef(result);
  5902. return result;
  5903. };
  5904. /**
  5905. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5906. * @param result defines the target matrix to store data to
  5907. * @returns the current matrix
  5908. */
  5909. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5910. var m = this.m;
  5911. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5912. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5913. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5914. if (this.determinant() <= 0) {
  5915. sy *= -1;
  5916. }
  5917. if (sx === 0 || sy === 0 || sz === 0) {
  5918. Matrix.IdentityToRef(result);
  5919. }
  5920. else {
  5921. 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);
  5922. }
  5923. return this;
  5924. };
  5925. // Statics
  5926. /**
  5927. * Creates a matrix from an array
  5928. * @param array defines the source array
  5929. * @param offset defines an offset in the source array
  5930. * @returns a new Matrix set from the starting index of the given array
  5931. */
  5932. Matrix.FromArray = function (array, offset) {
  5933. var result = new Matrix();
  5934. if (!offset) {
  5935. offset = 0;
  5936. }
  5937. Matrix.FromArrayToRef(array, offset, result);
  5938. return result;
  5939. };
  5940. /**
  5941. * Copy the content of an array into a given matrix
  5942. * @param array defines the source array
  5943. * @param offset defines an offset in the source array
  5944. * @param result defines the target matrix
  5945. */
  5946. Matrix.FromArrayToRef = function (array, offset, result) {
  5947. for (var index = 0; index < 16; index++) {
  5948. result.m[index] = array[index + offset];
  5949. }
  5950. result._markAsUpdated();
  5951. };
  5952. /**
  5953. * Stores an array into a matrix after having multiplied each component by a given factor
  5954. * @param array defines the source array
  5955. * @param offset defines the offset in the source array
  5956. * @param scale defines the scaling factor
  5957. * @param result defines the target matrix
  5958. */
  5959. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5960. for (var index = 0; index < 16; index++) {
  5961. result.m[index] = array[index + offset] * scale;
  5962. }
  5963. result._markAsUpdated();
  5964. };
  5965. /**
  5966. * Stores a list of values (16) inside a given matrix
  5967. * @param initialM11 defines 1st value of 1st row
  5968. * @param initialM12 defines 2nd value of 1st row
  5969. * @param initialM13 defines 3rd value of 1st row
  5970. * @param initialM14 defines 4th value of 1st row
  5971. * @param initialM21 defines 1st value of 2nd row
  5972. * @param initialM22 defines 2nd value of 2nd row
  5973. * @param initialM23 defines 3rd value of 2nd row
  5974. * @param initialM24 defines 4th value of 2nd row
  5975. * @param initialM31 defines 1st value of 3rd row
  5976. * @param initialM32 defines 2nd value of 3rd row
  5977. * @param initialM33 defines 3rd value of 3rd row
  5978. * @param initialM34 defines 4th value of 3rd row
  5979. * @param initialM41 defines 1st value of 4th row
  5980. * @param initialM42 defines 2nd value of 4th row
  5981. * @param initialM43 defines 3rd value of 4th row
  5982. * @param initialM44 defines 4th value of 4th row
  5983. * @param result defines the target matrix
  5984. */
  5985. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5986. result.m[0] = initialM11;
  5987. result.m[1] = initialM12;
  5988. result.m[2] = initialM13;
  5989. result.m[3] = initialM14;
  5990. result.m[4] = initialM21;
  5991. result.m[5] = initialM22;
  5992. result.m[6] = initialM23;
  5993. result.m[7] = initialM24;
  5994. result.m[8] = initialM31;
  5995. result.m[9] = initialM32;
  5996. result.m[10] = initialM33;
  5997. result.m[11] = initialM34;
  5998. result.m[12] = initialM41;
  5999. result.m[13] = initialM42;
  6000. result.m[14] = initialM43;
  6001. result.m[15] = initialM44;
  6002. result._markAsUpdated();
  6003. };
  6004. Object.defineProperty(Matrix, "IdentityReadOnly", {
  6005. /**
  6006. * Gets an identity matrix that must not be updated
  6007. */
  6008. get: function () {
  6009. return Matrix._identityReadOnly;
  6010. },
  6011. enumerable: true,
  6012. configurable: true
  6013. });
  6014. /**
  6015. * Creates new matrix from a list of values (16)
  6016. * @param initialM11 defines 1st value of 1st row
  6017. * @param initialM12 defines 2nd value of 1st row
  6018. * @param initialM13 defines 3rd value of 1st row
  6019. * @param initialM14 defines 4th value of 1st row
  6020. * @param initialM21 defines 1st value of 2nd row
  6021. * @param initialM22 defines 2nd value of 2nd row
  6022. * @param initialM23 defines 3rd value of 2nd row
  6023. * @param initialM24 defines 4th value of 2nd row
  6024. * @param initialM31 defines 1st value of 3rd row
  6025. * @param initialM32 defines 2nd value of 3rd row
  6026. * @param initialM33 defines 3rd value of 3rd row
  6027. * @param initialM34 defines 4th value of 3rd row
  6028. * @param initialM41 defines 1st value of 4th row
  6029. * @param initialM42 defines 2nd value of 4th row
  6030. * @param initialM43 defines 3rd value of 4th row
  6031. * @param initialM44 defines 4th value of 4th row
  6032. * @returns the new matrix
  6033. */
  6034. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  6035. var result = new Matrix();
  6036. result.m[0] = initialM11;
  6037. result.m[1] = initialM12;
  6038. result.m[2] = initialM13;
  6039. result.m[3] = initialM14;
  6040. result.m[4] = initialM21;
  6041. result.m[5] = initialM22;
  6042. result.m[6] = initialM23;
  6043. result.m[7] = initialM24;
  6044. result.m[8] = initialM31;
  6045. result.m[9] = initialM32;
  6046. result.m[10] = initialM33;
  6047. result.m[11] = initialM34;
  6048. result.m[12] = initialM41;
  6049. result.m[13] = initialM42;
  6050. result.m[14] = initialM43;
  6051. result.m[15] = initialM44;
  6052. return result;
  6053. };
  6054. /**
  6055. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6056. * @param scale defines the scale vector3
  6057. * @param rotation defines the rotation quaternion
  6058. * @param translation defines the translation vector3
  6059. * @returns a new matrix
  6060. */
  6061. Matrix.Compose = function (scale, rotation, translation) {
  6062. var result = Matrix.Identity();
  6063. Matrix.ComposeToRef(scale, rotation, translation, result);
  6064. return result;
  6065. };
  6066. /**
  6067. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6068. * @param scale defines the scale vector3
  6069. * @param rotation defines the rotation quaternion
  6070. * @param translation defines the translation vector3
  6071. * @param result defines the target matrix
  6072. */
  6073. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  6074. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  6075. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  6076. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  6077. result.setTranslation(translation);
  6078. };
  6079. /**
  6080. * Creates a new identity matrix
  6081. * @returns a new identity matrix
  6082. */
  6083. Matrix.Identity = function () {
  6084. 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);
  6085. };
  6086. /**
  6087. * Creates a new identity matrix and stores the result in a given matrix
  6088. * @param result defines the target matrix
  6089. */
  6090. Matrix.IdentityToRef = function (result) {
  6091. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  6092. };
  6093. /**
  6094. * Creates a new zero matrix
  6095. * @returns a new zero matrix
  6096. */
  6097. Matrix.Zero = function () {
  6098. 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);
  6099. };
  6100. /**
  6101. * Creates a new rotation matrix for "angle" radians around the X axis
  6102. * @param angle defines the angle (in radians) to use
  6103. * @return the new matrix
  6104. */
  6105. Matrix.RotationX = function (angle) {
  6106. var result = new Matrix();
  6107. Matrix.RotationXToRef(angle, result);
  6108. return result;
  6109. };
  6110. /**
  6111. * Creates a new matrix as the invert of a given matrix
  6112. * @param source defines the source matrix
  6113. * @returns the new matrix
  6114. */
  6115. Matrix.Invert = function (source) {
  6116. var result = new Matrix();
  6117. source.invertToRef(result);
  6118. return result;
  6119. };
  6120. /**
  6121. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  6122. * @param angle defines the angle (in radians) to use
  6123. * @param result defines the target matrix
  6124. */
  6125. Matrix.RotationXToRef = function (angle, result) {
  6126. var s = Math.sin(angle);
  6127. var c = Math.cos(angle);
  6128. result.m[0] = 1.0;
  6129. result.m[15] = 1.0;
  6130. result.m[5] = c;
  6131. result.m[10] = c;
  6132. result.m[9] = -s;
  6133. result.m[6] = s;
  6134. result.m[1] = 0.0;
  6135. result.m[2] = 0.0;
  6136. result.m[3] = 0.0;
  6137. result.m[4] = 0.0;
  6138. result.m[7] = 0.0;
  6139. result.m[8] = 0.0;
  6140. result.m[11] = 0.0;
  6141. result.m[12] = 0.0;
  6142. result.m[13] = 0.0;
  6143. result.m[14] = 0.0;
  6144. result._markAsUpdated();
  6145. };
  6146. /**
  6147. * Creates a new rotation matrix for "angle" radians around the Y axis
  6148. * @param angle defines the angle (in radians) to use
  6149. * @return the new matrix
  6150. */
  6151. Matrix.RotationY = function (angle) {
  6152. var result = new Matrix();
  6153. Matrix.RotationYToRef(angle, result);
  6154. return result;
  6155. };
  6156. /**
  6157. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  6158. * @param angle defines the angle (in radians) to use
  6159. * @param result defines the target matrix
  6160. */
  6161. Matrix.RotationYToRef = function (angle, result) {
  6162. var s = Math.sin(angle);
  6163. var c = Math.cos(angle);
  6164. result.m[5] = 1.0;
  6165. result.m[15] = 1.0;
  6166. result.m[0] = c;
  6167. result.m[2] = -s;
  6168. result.m[8] = s;
  6169. result.m[10] = c;
  6170. result.m[1] = 0.0;
  6171. result.m[3] = 0.0;
  6172. result.m[4] = 0.0;
  6173. result.m[6] = 0.0;
  6174. result.m[7] = 0.0;
  6175. result.m[9] = 0.0;
  6176. result.m[11] = 0.0;
  6177. result.m[12] = 0.0;
  6178. result.m[13] = 0.0;
  6179. result.m[14] = 0.0;
  6180. result._markAsUpdated();
  6181. };
  6182. /**
  6183. * Creates a new rotation matrix for "angle" radians around the Z axis
  6184. * @param angle defines the angle (in radians) to use
  6185. * @return the new matrix
  6186. */
  6187. Matrix.RotationZ = function (angle) {
  6188. var result = new Matrix();
  6189. Matrix.RotationZToRef(angle, result);
  6190. return result;
  6191. };
  6192. /**
  6193. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  6194. * @param angle defines the angle (in radians) to use
  6195. * @param result defines the target matrix
  6196. */
  6197. Matrix.RotationZToRef = function (angle, result) {
  6198. var s = Math.sin(angle);
  6199. var c = Math.cos(angle);
  6200. result.m[10] = 1.0;
  6201. result.m[15] = 1.0;
  6202. result.m[0] = c;
  6203. result.m[1] = s;
  6204. result.m[4] = -s;
  6205. result.m[5] = c;
  6206. result.m[2] = 0.0;
  6207. result.m[3] = 0.0;
  6208. result.m[6] = 0.0;
  6209. result.m[7] = 0.0;
  6210. result.m[8] = 0.0;
  6211. result.m[9] = 0.0;
  6212. result.m[11] = 0.0;
  6213. result.m[12] = 0.0;
  6214. result.m[13] = 0.0;
  6215. result.m[14] = 0.0;
  6216. result._markAsUpdated();
  6217. };
  6218. /**
  6219. * Creates a new rotation matrix for "angle" radians around the given axis
  6220. * @param axis defines the axis to use
  6221. * @param angle defines the angle (in radians) to use
  6222. * @return the new matrix
  6223. */
  6224. Matrix.RotationAxis = function (axis, angle) {
  6225. var result = Matrix.Zero();
  6226. Matrix.RotationAxisToRef(axis, angle, result);
  6227. return result;
  6228. };
  6229. /**
  6230. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  6231. * @param axis defines the axis to use
  6232. * @param angle defines the angle (in radians) to use
  6233. * @param result defines the target matrix
  6234. */
  6235. Matrix.RotationAxisToRef = function (axis, angle, result) {
  6236. var s = Math.sin(-angle);
  6237. var c = Math.cos(-angle);
  6238. var c1 = 1 - c;
  6239. axis.normalize();
  6240. result.m[0] = (axis.x * axis.x) * c1 + c;
  6241. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  6242. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  6243. result.m[3] = 0.0;
  6244. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6245. result.m[5] = (axis.y * axis.y) * c1 + c;
  6246. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6247. result.m[7] = 0.0;
  6248. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6249. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6250. result.m[10] = (axis.z * axis.z) * c1 + c;
  6251. result.m[11] = 0.0;
  6252. result.m[15] = 1.0;
  6253. result._markAsUpdated();
  6254. };
  6255. /**
  6256. * Creates a rotation matrix
  6257. * @param yaw defines the yaw angle in radians (Y axis)
  6258. * @param pitch defines the pitch angle in radians (X axis)
  6259. * @param roll defines the roll angle in radians (X axis)
  6260. * @returns the new rotation matrix
  6261. */
  6262. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6263. var result = new Matrix();
  6264. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6265. return result;
  6266. };
  6267. /**
  6268. * Creates a rotation matrix and stores it in a given matrix
  6269. * @param yaw defines the yaw angle in radians (Y axis)
  6270. * @param pitch defines the pitch angle in radians (X axis)
  6271. * @param roll defines the roll angle in radians (X axis)
  6272. * @param result defines the target matrix
  6273. */
  6274. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6275. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6276. this._tempQuaternion.toRotationMatrix(result);
  6277. };
  6278. /**
  6279. * Creates a scaling matrix
  6280. * @param x defines the scale factor on X axis
  6281. * @param y defines the scale factor on Y axis
  6282. * @param z defines the scale factor on Z axis
  6283. * @returns the new matrix
  6284. */
  6285. Matrix.Scaling = function (x, y, z) {
  6286. var result = Matrix.Zero();
  6287. Matrix.ScalingToRef(x, y, z, result);
  6288. return result;
  6289. };
  6290. /**
  6291. * Creates a scaling matrix and stores it in a given matrix
  6292. * @param x defines the scale factor on X axis
  6293. * @param y defines the scale factor on Y axis
  6294. * @param z defines the scale factor on Z axis
  6295. * @param result defines the target matrix
  6296. */
  6297. Matrix.ScalingToRef = function (x, y, z, result) {
  6298. result.m[0] = x;
  6299. result.m[1] = 0.0;
  6300. result.m[2] = 0.0;
  6301. result.m[3] = 0.0;
  6302. result.m[4] = 0.0;
  6303. result.m[5] = y;
  6304. result.m[6] = 0.0;
  6305. result.m[7] = 0.0;
  6306. result.m[8] = 0.0;
  6307. result.m[9] = 0.0;
  6308. result.m[10] = z;
  6309. result.m[11] = 0.0;
  6310. result.m[12] = 0.0;
  6311. result.m[13] = 0.0;
  6312. result.m[14] = 0.0;
  6313. result.m[15] = 1.0;
  6314. result._markAsUpdated();
  6315. };
  6316. /**
  6317. * Creates a translation matrix
  6318. * @param x defines the translation on X axis
  6319. * @param y defines the translation on Y axis
  6320. * @param z defines the translationon Z axis
  6321. * @returns the new matrix
  6322. */
  6323. Matrix.Translation = function (x, y, z) {
  6324. var result = Matrix.Identity();
  6325. Matrix.TranslationToRef(x, y, z, result);
  6326. return result;
  6327. };
  6328. /**
  6329. * Creates a translation matrix and stores it in a given matrix
  6330. * @param x defines the translation on X axis
  6331. * @param y defines the translation on Y axis
  6332. * @param z defines the translationon Z axis
  6333. * @param result defines the target matrix
  6334. */
  6335. Matrix.TranslationToRef = function (x, y, z, result) {
  6336. 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);
  6337. };
  6338. /**
  6339. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6340. * @param startValue defines the start value
  6341. * @param endValue defines the end value
  6342. * @param gradient defines the gradient factor
  6343. * @returns the new matrix
  6344. */
  6345. Matrix.Lerp = function (startValue, endValue, gradient) {
  6346. var result = Matrix.Zero();
  6347. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6348. return result;
  6349. };
  6350. /**
  6351. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6352. * @param startValue defines the start value
  6353. * @param endValue defines the end value
  6354. * @param gradient defines the gradient factor
  6355. * @param result defines the Matrix object where to store data
  6356. */
  6357. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6358. for (var index = 0; index < 16; index++) {
  6359. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6360. }
  6361. result._markAsUpdated();
  6362. };
  6363. /**
  6364. * Builds a new matrix whose values are computed by:
  6365. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6366. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6367. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6368. * @param startValue defines the first matrix
  6369. * @param endValue defines the second matrix
  6370. * @param gradient defines the gradient between the two matrices
  6371. * @returns the new matrix
  6372. */
  6373. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6374. var result = Matrix.Zero();
  6375. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6376. return result;
  6377. };
  6378. /**
  6379. * Update a matrix to values which are computed by:
  6380. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6381. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6382. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6383. * @param startValue defines the first matrix
  6384. * @param endValue defines the second matrix
  6385. * @param gradient defines the gradient between the two matrices
  6386. * @param result defines the target matrix
  6387. */
  6388. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6389. var startScale = MathTmp.Vector3[0];
  6390. var startRotation = MathTmp.Quaternion[0];
  6391. var startTranslation = MathTmp.Vector3[1];
  6392. startValue.decompose(startScale, startRotation, startTranslation);
  6393. var endScale = MathTmp.Vector3[2];
  6394. var endRotation = MathTmp.Quaternion[1];
  6395. var endTranslation = MathTmp.Vector3[3];
  6396. endValue.decompose(endScale, endRotation, endTranslation);
  6397. var resultScale = MathTmp.Vector3[4];
  6398. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6399. var resultRotation = MathTmp.Quaternion[2];
  6400. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6401. var resultTranslation = MathTmp.Vector3[5];
  6402. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6403. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6404. };
  6405. /**
  6406. * 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"
  6407. * This function works in left handed mode
  6408. * @param eye defines the final position of the entity
  6409. * @param target defines where the entity should look at
  6410. * @param up defines the up vector for the entity
  6411. * @returns the new matrix
  6412. */
  6413. Matrix.LookAtLH = function (eye, target, up) {
  6414. var result = Matrix.Zero();
  6415. Matrix.LookAtLHToRef(eye, target, up, result);
  6416. return result;
  6417. };
  6418. /**
  6419. * 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".
  6420. * This function works in left handed mode
  6421. * @param eye defines the final position of the entity
  6422. * @param target defines where the entity should look at
  6423. * @param up defines the up vector for the entity
  6424. * @param result defines the target matrix
  6425. */
  6426. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6427. // Z axis
  6428. target.subtractToRef(eye, this._zAxis);
  6429. this._zAxis.normalize();
  6430. // X axis
  6431. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6432. if (this._xAxis.lengthSquared() === 0) {
  6433. this._xAxis.x = 1.0;
  6434. }
  6435. else {
  6436. this._xAxis.normalize();
  6437. }
  6438. // Y axis
  6439. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6440. this._yAxis.normalize();
  6441. // Eye angles
  6442. var ex = -Vector3.Dot(this._xAxis, eye);
  6443. var ey = -Vector3.Dot(this._yAxis, eye);
  6444. var ez = -Vector3.Dot(this._zAxis, eye);
  6445. 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);
  6446. };
  6447. /**
  6448. * 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"
  6449. * This function works in right handed mode
  6450. * @param eye defines the final position of the entity
  6451. * @param target defines where the entity should look at
  6452. * @param up defines the up vector for the entity
  6453. * @returns the new matrix
  6454. */
  6455. Matrix.LookAtRH = function (eye, target, up) {
  6456. var result = Matrix.Zero();
  6457. Matrix.LookAtRHToRef(eye, target, up, result);
  6458. return result;
  6459. };
  6460. /**
  6461. * 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".
  6462. * This function works in right handed mode
  6463. * @param eye defines the final position of the entity
  6464. * @param target defines where the entity should look at
  6465. * @param up defines the up vector for the entity
  6466. * @param result defines the target matrix
  6467. */
  6468. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6469. // Z axis
  6470. eye.subtractToRef(target, this._zAxis);
  6471. this._zAxis.normalize();
  6472. // X axis
  6473. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6474. if (this._xAxis.lengthSquared() === 0) {
  6475. this._xAxis.x = 1.0;
  6476. }
  6477. else {
  6478. this._xAxis.normalize();
  6479. }
  6480. // Y axis
  6481. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6482. this._yAxis.normalize();
  6483. // Eye angles
  6484. var ex = -Vector3.Dot(this._xAxis, eye);
  6485. var ey = -Vector3.Dot(this._yAxis, eye);
  6486. var ez = -Vector3.Dot(this._zAxis, eye);
  6487. 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);
  6488. };
  6489. /**
  6490. * Create a left-handed orthographic projection matrix
  6491. * @param width defines the viewport width
  6492. * @param height defines the viewport height
  6493. * @param znear defines the near clip plane
  6494. * @param zfar defines the far clip plane
  6495. * @returns a new matrix as a left-handed orthographic projection matrix
  6496. */
  6497. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6498. var matrix = Matrix.Zero();
  6499. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6500. return matrix;
  6501. };
  6502. /**
  6503. * Store a left-handed orthographic projection to a given matrix
  6504. * @param width defines the viewport width
  6505. * @param height defines the viewport height
  6506. * @param znear defines the near clip plane
  6507. * @param zfar defines the far clip plane
  6508. * @param result defines the target matrix
  6509. */
  6510. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6511. var n = znear;
  6512. var f = zfar;
  6513. var a = 2.0 / width;
  6514. var b = 2.0 / height;
  6515. var c = 2.0 / (f - n);
  6516. var d = -(f + n) / (f - n);
  6517. 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);
  6518. };
  6519. /**
  6520. * Create a left-handed orthographic projection matrix
  6521. * @param left defines the viewport left coordinate
  6522. * @param right defines the viewport right coordinate
  6523. * @param bottom defines the viewport bottom coordinate
  6524. * @param top defines the viewport top coordinate
  6525. * @param znear defines the near clip plane
  6526. * @param zfar defines the far clip plane
  6527. * @returns a new matrix as a left-handed orthographic projection matrix
  6528. */
  6529. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6530. var matrix = Matrix.Zero();
  6531. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6532. return matrix;
  6533. };
  6534. /**
  6535. * Stores a left-handed orthographic projection into a given matrix
  6536. * @param left defines the viewport left coordinate
  6537. * @param right defines the viewport right coordinate
  6538. * @param bottom defines the viewport bottom coordinate
  6539. * @param top defines the viewport top coordinate
  6540. * @param znear defines the near clip plane
  6541. * @param zfar defines the far clip plane
  6542. * @param result defines the target matrix
  6543. */
  6544. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6545. var n = znear;
  6546. var f = zfar;
  6547. var a = 2.0 / (right - left);
  6548. var b = 2.0 / (top - bottom);
  6549. var c = 2.0 / (f - n);
  6550. var d = -(f + n) / (f - n);
  6551. var i0 = (left + right) / (left - right);
  6552. var i1 = (top + bottom) / (bottom - top);
  6553. 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);
  6554. };
  6555. /**
  6556. * Creates a right-handed orthographic projection matrix
  6557. * @param left defines the viewport left coordinate
  6558. * @param right defines the viewport right coordinate
  6559. * @param bottom defines the viewport bottom coordinate
  6560. * @param top defines the viewport top coordinate
  6561. * @param znear defines the near clip plane
  6562. * @param zfar defines the far clip plane
  6563. * @returns a new matrix as a right-handed orthographic projection matrix
  6564. */
  6565. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6566. var matrix = Matrix.Zero();
  6567. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6568. return matrix;
  6569. };
  6570. /**
  6571. * Stores a right-handed orthographic projection into a given matrix
  6572. * @param left defines the viewport left coordinate
  6573. * @param right defines the viewport right coordinate
  6574. * @param bottom defines the viewport bottom coordinate
  6575. * @param top defines the viewport top coordinate
  6576. * @param znear defines the near clip plane
  6577. * @param zfar defines the far clip plane
  6578. * @param result defines the target matrix
  6579. */
  6580. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6581. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6582. result.m[10] *= -1.0;
  6583. };
  6584. /**
  6585. * Creates a left-handed perspective projection matrix
  6586. * @param width defines the viewport width
  6587. * @param height defines the viewport height
  6588. * @param znear defines the near clip plane
  6589. * @param zfar defines the far clip plane
  6590. * @returns a new matrix as a left-handed perspective projection matrix
  6591. */
  6592. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6593. var matrix = Matrix.Zero();
  6594. var n = znear;
  6595. var f = zfar;
  6596. var a = 2.0 * n / width;
  6597. var b = 2.0 * n / height;
  6598. var c = (f + n) / (f - n);
  6599. var d = -2.0 * f * n / (f - n);
  6600. 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);
  6601. return matrix;
  6602. };
  6603. /**
  6604. * Creates a left-handed perspective projection matrix
  6605. * @param fov defines the horizontal field of view
  6606. * @param aspect defines the aspect ratio
  6607. * @param znear defines the near clip plane
  6608. * @param zfar defines the far clip plane
  6609. * @returns a new matrix as a left-handed perspective projection matrix
  6610. */
  6611. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6612. var matrix = Matrix.Zero();
  6613. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6614. return matrix;
  6615. };
  6616. /**
  6617. * Stores a left-handed perspective projection into a given matrix
  6618. * @param fov defines the horizontal field of view
  6619. * @param aspect defines the aspect ratio
  6620. * @param znear defines the near clip plane
  6621. * @param zfar defines the far clip plane
  6622. * @param result defines the target matrix
  6623. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6624. */
  6625. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6626. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6627. var n = znear;
  6628. var f = zfar;
  6629. var t = 1.0 / (Math.tan(fov * 0.5));
  6630. var a = isVerticalFovFixed ? (t / aspect) : t;
  6631. var b = isVerticalFovFixed ? t : (t * aspect);
  6632. var c = (f + n) / (f - n);
  6633. var d = -2.0 * f * n / (f - n);
  6634. 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);
  6635. };
  6636. /**
  6637. * Creates a right-handed perspective projection matrix
  6638. * @param fov defines the horizontal field of view
  6639. * @param aspect defines the aspect ratio
  6640. * @param znear defines the near clip plane
  6641. * @param zfar defines the far clip plane
  6642. * @returns a new matrix as a right-handed perspective projection matrix
  6643. */
  6644. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6645. var matrix = Matrix.Zero();
  6646. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6647. return matrix;
  6648. };
  6649. /**
  6650. * Stores a right-handed perspective projection into a given matrix
  6651. * @param fov defines the horizontal field of view
  6652. * @param aspect defines the aspect ratio
  6653. * @param znear defines the near clip plane
  6654. * @param zfar defines the far clip plane
  6655. * @param result defines the target matrix
  6656. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6657. */
  6658. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6659. //alternatively this could be expressed as:
  6660. // m = PerspectiveFovLHToRef
  6661. // m[10] *= -1.0;
  6662. // m[11] *= -1.0;
  6663. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6664. var n = znear;
  6665. var f = zfar;
  6666. var t = 1.0 / (Math.tan(fov * 0.5));
  6667. var a = isVerticalFovFixed ? (t / aspect) : t;
  6668. var b = isVerticalFovFixed ? t : (t * aspect);
  6669. var c = -(f + n) / (f - n);
  6670. var d = -2 * f * n / (f - n);
  6671. 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);
  6672. };
  6673. /**
  6674. * Stores a perspective projection for WebVR info a given matrix
  6675. * @param fov defines the field of view
  6676. * @param znear defines the near clip plane
  6677. * @param zfar defines the far clip plane
  6678. * @param result defines the target matrix
  6679. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6680. */
  6681. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6682. if (rightHanded === void 0) { rightHanded = false; }
  6683. var rightHandedFactor = rightHanded ? -1 : 1;
  6684. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6685. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6686. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6687. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6688. var xScale = 2.0 / (leftTan + rightTan);
  6689. var yScale = 2.0 / (upTan + downTan);
  6690. result.m[0] = xScale;
  6691. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6692. result.m[5] = yScale;
  6693. result.m[6] = result.m[7] = 0.0;
  6694. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6695. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6696. result.m[10] = -zfar / (znear - zfar);
  6697. result.m[11] = 1.0 * rightHandedFactor;
  6698. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6699. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6700. result._markAsUpdated();
  6701. };
  6702. /**
  6703. * Computes a complete transformation matrix
  6704. * @param viewport defines the viewport to use
  6705. * @param world defines the world matrix
  6706. * @param view defines the view matrix
  6707. * @param projection defines the projection matrix
  6708. * @param zmin defines the near clip plane
  6709. * @param zmax defines the far clip plane
  6710. * @returns the transformation matrix
  6711. */
  6712. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6713. var cw = viewport.width;
  6714. var ch = viewport.height;
  6715. var cx = viewport.x;
  6716. var cy = viewport.y;
  6717. 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);
  6718. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6719. };
  6720. /**
  6721. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6722. * @param matrix defines the matrix to use
  6723. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6724. */
  6725. Matrix.GetAsMatrix2x2 = function (matrix) {
  6726. return new Float32Array([
  6727. matrix.m[0], matrix.m[1],
  6728. matrix.m[4], matrix.m[5]
  6729. ]);
  6730. };
  6731. /**
  6732. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6733. * @param matrix defines the matrix to use
  6734. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6735. */
  6736. Matrix.GetAsMatrix3x3 = function (matrix) {
  6737. return new Float32Array([
  6738. matrix.m[0], matrix.m[1], matrix.m[2],
  6739. matrix.m[4], matrix.m[5], matrix.m[6],
  6740. matrix.m[8], matrix.m[9], matrix.m[10]
  6741. ]);
  6742. };
  6743. /**
  6744. * Compute the transpose of a given matrix
  6745. * @param matrix defines the matrix to transpose
  6746. * @returns the new matrix
  6747. */
  6748. Matrix.Transpose = function (matrix) {
  6749. var result = new Matrix();
  6750. Matrix.TransposeToRef(matrix, result);
  6751. return result;
  6752. };
  6753. /**
  6754. * Compute the transpose of a matrix and store it in a target matrix
  6755. * @param matrix defines the matrix to transpose
  6756. * @param result defines the target matrix
  6757. */
  6758. Matrix.TransposeToRef = function (matrix, result) {
  6759. result.m[0] = matrix.m[0];
  6760. result.m[1] = matrix.m[4];
  6761. result.m[2] = matrix.m[8];
  6762. result.m[3] = matrix.m[12];
  6763. result.m[4] = matrix.m[1];
  6764. result.m[5] = matrix.m[5];
  6765. result.m[6] = matrix.m[9];
  6766. result.m[7] = matrix.m[13];
  6767. result.m[8] = matrix.m[2];
  6768. result.m[9] = matrix.m[6];
  6769. result.m[10] = matrix.m[10];
  6770. result.m[11] = matrix.m[14];
  6771. result.m[12] = matrix.m[3];
  6772. result.m[13] = matrix.m[7];
  6773. result.m[14] = matrix.m[11];
  6774. result.m[15] = matrix.m[15];
  6775. };
  6776. /**
  6777. * Computes a reflection matrix from a plane
  6778. * @param plane defines the reflection plane
  6779. * @returns a new matrix
  6780. */
  6781. Matrix.Reflection = function (plane) {
  6782. var matrix = new Matrix();
  6783. Matrix.ReflectionToRef(plane, matrix);
  6784. return matrix;
  6785. };
  6786. /**
  6787. * Computes a reflection matrix from a plane
  6788. * @param plane defines the reflection plane
  6789. * @param result defines the target matrix
  6790. */
  6791. Matrix.ReflectionToRef = function (plane, result) {
  6792. plane.normalize();
  6793. var x = plane.normal.x;
  6794. var y = plane.normal.y;
  6795. var z = plane.normal.z;
  6796. var temp = -2 * x;
  6797. var temp2 = -2 * y;
  6798. var temp3 = -2 * z;
  6799. result.m[0] = (temp * x) + 1;
  6800. result.m[1] = temp2 * x;
  6801. result.m[2] = temp3 * x;
  6802. result.m[3] = 0.0;
  6803. result.m[4] = temp * y;
  6804. result.m[5] = (temp2 * y) + 1;
  6805. result.m[6] = temp3 * y;
  6806. result.m[7] = 0.0;
  6807. result.m[8] = temp * z;
  6808. result.m[9] = temp2 * z;
  6809. result.m[10] = (temp3 * z) + 1;
  6810. result.m[11] = 0.0;
  6811. result.m[12] = temp * plane.d;
  6812. result.m[13] = temp2 * plane.d;
  6813. result.m[14] = temp3 * plane.d;
  6814. result.m[15] = 1.0;
  6815. result._markAsUpdated();
  6816. };
  6817. /**
  6818. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6819. * @param xaxis defines the value of the 1st axis
  6820. * @param yaxis defines the value of the 2nd axis
  6821. * @param zaxis defines the value of the 3rd axis
  6822. * @param result defines the target matrix
  6823. */
  6824. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6825. result.m[0] = xaxis.x;
  6826. result.m[1] = xaxis.y;
  6827. result.m[2] = xaxis.z;
  6828. result.m[3] = 0.0;
  6829. result.m[4] = yaxis.x;
  6830. result.m[5] = yaxis.y;
  6831. result.m[6] = yaxis.z;
  6832. result.m[7] = 0.0;
  6833. result.m[8] = zaxis.x;
  6834. result.m[9] = zaxis.y;
  6835. result.m[10] = zaxis.z;
  6836. result.m[11] = 0.0;
  6837. result.m[12] = 0.0;
  6838. result.m[13] = 0.0;
  6839. result.m[14] = 0.0;
  6840. result.m[15] = 1.0;
  6841. result._markAsUpdated();
  6842. };
  6843. /**
  6844. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6845. * @param quat defines the quaternion to use
  6846. * @param result defines the target matrix
  6847. */
  6848. Matrix.FromQuaternionToRef = function (quat, result) {
  6849. var xx = quat.x * quat.x;
  6850. var yy = quat.y * quat.y;
  6851. var zz = quat.z * quat.z;
  6852. var xy = quat.x * quat.y;
  6853. var zw = quat.z * quat.w;
  6854. var zx = quat.z * quat.x;
  6855. var yw = quat.y * quat.w;
  6856. var yz = quat.y * quat.z;
  6857. var xw = quat.x * quat.w;
  6858. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6859. result.m[1] = 2.0 * (xy + zw);
  6860. result.m[2] = 2.0 * (zx - yw);
  6861. result.m[3] = 0.0;
  6862. result.m[4] = 2.0 * (xy - zw);
  6863. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6864. result.m[6] = 2.0 * (yz + xw);
  6865. result.m[7] = 0.0;
  6866. result.m[8] = 2.0 * (zx + yw);
  6867. result.m[9] = 2.0 * (yz - xw);
  6868. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6869. result.m[11] = 0.0;
  6870. result.m[12] = 0.0;
  6871. result.m[13] = 0.0;
  6872. result.m[14] = 0.0;
  6873. result.m[15] = 1.0;
  6874. result._markAsUpdated();
  6875. };
  6876. Matrix._tempQuaternion = new Quaternion();
  6877. Matrix._xAxis = Vector3.Zero();
  6878. Matrix._yAxis = Vector3.Zero();
  6879. Matrix._zAxis = Vector3.Zero();
  6880. Matrix._updateFlagSeed = 0;
  6881. Matrix._identityReadOnly = Matrix.Identity();
  6882. return Matrix;
  6883. }());
  6884. BABYLON.Matrix = Matrix;
  6885. /**
  6886. * Represens a plane by the equation ax + by + cz + d = 0
  6887. */
  6888. var Plane = /** @class */ (function () {
  6889. /**
  6890. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6891. * @param a a component of the plane
  6892. * @param b b component of the plane
  6893. * @param c c component of the plane
  6894. * @param d d component of the plane
  6895. */
  6896. function Plane(a, b, c, d) {
  6897. this.normal = new Vector3(a, b, c);
  6898. this.d = d;
  6899. }
  6900. /**
  6901. * @returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6902. */
  6903. Plane.prototype.asArray = function () {
  6904. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6905. };
  6906. // Methods
  6907. /**
  6908. * @returns a new plane copied from the current Plane.
  6909. */
  6910. Plane.prototype.clone = function () {
  6911. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6912. };
  6913. /**
  6914. * @returns the string "Plane".
  6915. */
  6916. Plane.prototype.getClassName = function () {
  6917. return "Plane";
  6918. };
  6919. /**
  6920. * @returns the Plane hash code.
  6921. */
  6922. Plane.prototype.getHashCode = function () {
  6923. var hash = this.normal.getHashCode();
  6924. hash = (hash * 397) ^ (this.d || 0);
  6925. return hash;
  6926. };
  6927. /**
  6928. * Normalize the current Plane in place.
  6929. * @returns the updated Plane.
  6930. */
  6931. Plane.prototype.normalize = function () {
  6932. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6933. var magnitude = 0.0;
  6934. if (norm !== 0) {
  6935. magnitude = 1.0 / norm;
  6936. }
  6937. this.normal.x *= magnitude;
  6938. this.normal.y *= magnitude;
  6939. this.normal.z *= magnitude;
  6940. this.d *= magnitude;
  6941. return this;
  6942. };
  6943. /**
  6944. * Applies a transformation the plane and returns the result
  6945. * @param transformation the transformation matrix to be applied to the plane
  6946. * @returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6947. */
  6948. Plane.prototype.transform = function (transformation) {
  6949. var transposedMatrix = Matrix.Transpose(transformation);
  6950. var x = this.normal.x;
  6951. var y = this.normal.y;
  6952. var z = this.normal.z;
  6953. var d = this.d;
  6954. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6955. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6956. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6957. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6958. return new Plane(normalX, normalY, normalZ, finalD);
  6959. };
  6960. /**
  6961. * Calcualtte the dot product between the point and the plane normal
  6962. * @param point point to calculate the dot product with
  6963. * @returns the dot product (float) of the point coordinates and the plane normal.
  6964. */
  6965. Plane.prototype.dotCoordinate = function (point) {
  6966. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6967. };
  6968. /**
  6969. * Updates the current Plane from the plane defined by the three given points.
  6970. * @param point1 one of the points used to contruct the plane
  6971. * @param point2 one of the points used to contruct the plane
  6972. * @param point3 one of the points used to contruct the plane
  6973. * @returns the updated Plane.
  6974. */
  6975. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6976. var x1 = point2.x - point1.x;
  6977. var y1 = point2.y - point1.y;
  6978. var z1 = point2.z - point1.z;
  6979. var x2 = point3.x - point1.x;
  6980. var y2 = point3.y - point1.y;
  6981. var z2 = point3.z - point1.z;
  6982. var yz = (y1 * z2) - (z1 * y2);
  6983. var xz = (z1 * x2) - (x1 * z2);
  6984. var xy = (x1 * y2) - (y1 * x2);
  6985. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6986. var invPyth;
  6987. if (pyth !== 0) {
  6988. invPyth = 1.0 / pyth;
  6989. }
  6990. else {
  6991. invPyth = 0.0;
  6992. }
  6993. this.normal.x = yz * invPyth;
  6994. this.normal.y = xz * invPyth;
  6995. this.normal.z = xy * invPyth;
  6996. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6997. return this;
  6998. };
  6999. /**
  7000. * Checks if the plane is facing a given direction
  7001. * @param direction the direction to check if the plane is facing
  7002. * @param epsilon value the dot product is compared against (returns true if dot <= epsilon)
  7003. * @returns True is the vector "direction" is the same side than the plane normal.
  7004. */
  7005. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  7006. var dot = Vector3.Dot(this.normal, direction);
  7007. return (dot <= epsilon);
  7008. };
  7009. /**
  7010. * Calculates the distance to a point
  7011. * @param point point to calculate distance to
  7012. * @returns the signed distance (float) from the given point to the Plane.
  7013. */
  7014. Plane.prototype.signedDistanceTo = function (point) {
  7015. return Vector3.Dot(point, this.normal) + this.d;
  7016. };
  7017. // Statics
  7018. /**
  7019. * Creates a plane from an array
  7020. * @param array the array to create a plane from
  7021. * @returns a new Plane from the given array.
  7022. */
  7023. Plane.FromArray = function (array) {
  7024. return new Plane(array[0], array[1], array[2], array[3]);
  7025. };
  7026. /**
  7027. * Creates a plane from three points
  7028. * @param point1 point used to create the plane
  7029. * @param point2 point used to create the plane
  7030. * @param point3 point used to create the plane
  7031. * @returns a new Plane defined by the three given points.
  7032. */
  7033. Plane.FromPoints = function (point1, point2, point3) {
  7034. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  7035. result.copyFromPoints(point1, point2, point3);
  7036. return result;
  7037. };
  7038. /**
  7039. * Creates a plane from an origin point and a normal
  7040. * @param origin origin of the plane to be constructed
  7041. * @param normal normal of the plane to be constructed
  7042. * @returns a new Plane the normal vector to this plane at the given origin point.
  7043. * Note : the vector "normal" is updated because normalized.
  7044. */
  7045. Plane.FromPositionAndNormal = function (origin, normal) {
  7046. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  7047. normal.normalize();
  7048. result.normal = normal;
  7049. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7050. return result;
  7051. };
  7052. /**
  7053. * Calculates the distance from a plane and a point
  7054. * @param origin origin of the plane to be constructed
  7055. * @param normal normal of the plane to be constructed
  7056. * @param point point to calculate distance to
  7057. * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  7058. */
  7059. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  7060. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7061. return Vector3.Dot(point, normal) + d;
  7062. };
  7063. return Plane;
  7064. }());
  7065. BABYLON.Plane = Plane;
  7066. /**
  7067. * Class used to represent a viewport on screen
  7068. */
  7069. var Viewport = /** @class */ (function () {
  7070. /**
  7071. * Creates a Viewport object located at (x, y) and sized (width, height)
  7072. * @param x defines viewport left coordinate
  7073. * @param y defines viewport top coordinate
  7074. * @param width defines the viewport width
  7075. * @param height defines the viewport height
  7076. */
  7077. function Viewport(
  7078. /** viewport left coordinate */
  7079. x,
  7080. /** viewport top coordinate */
  7081. y,
  7082. /**viewport width */
  7083. width,
  7084. /** viewport height */
  7085. height) {
  7086. this.x = x;
  7087. this.y = y;
  7088. this.width = width;
  7089. this.height = height;
  7090. }
  7091. /**
  7092. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  7093. * @param renderWidthOrEngine defines either an engine or the rendering width
  7094. * @param renderHeight defines the rendering height
  7095. * @returns a new Viewport
  7096. */
  7097. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  7098. if (renderWidthOrEngine.getRenderWidth) {
  7099. var engine = renderWidthOrEngine;
  7100. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  7101. }
  7102. var renderWidth = renderWidthOrEngine;
  7103. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  7104. };
  7105. /**
  7106. * Returns a new Viewport copied from the current one
  7107. * @returns a new Viewport
  7108. */
  7109. Viewport.prototype.clone = function () {
  7110. return new Viewport(this.x, this.y, this.width, this.height);
  7111. };
  7112. return Viewport;
  7113. }());
  7114. BABYLON.Viewport = Viewport;
  7115. /**
  7116. * Reprasents a camera frustum
  7117. */
  7118. var Frustum = /** @class */ (function () {
  7119. function Frustum() {
  7120. }
  7121. /**
  7122. * Gets the planes representing the frustum
  7123. * @param transform matrix to be applied to the returned planes
  7124. * @returns a new array of 6 Frustum planes computed by the given transformation matrix.
  7125. */
  7126. Frustum.GetPlanes = function (transform) {
  7127. var frustumPlanes = [];
  7128. for (var index = 0; index < 6; index++) {
  7129. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  7130. }
  7131. Frustum.GetPlanesToRef(transform, frustumPlanes);
  7132. return frustumPlanes;
  7133. };
  7134. /**
  7135. * Gets the near frustum plane transformed by the transform matrix
  7136. * @param transform transformation matrix to be applied to the resulting frustum plane
  7137. * @param frustumPlane the resuling frustum plane
  7138. */
  7139. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  7140. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  7141. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  7142. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  7143. frustumPlane.d = transform.m[15] + transform.m[14];
  7144. frustumPlane.normalize();
  7145. };
  7146. /**
  7147. * Gets the far frustum plane transformed by the transform matrix
  7148. * @param transform transformation matrix to be applied to the resulting frustum plane
  7149. * @param frustumPlane the resuling frustum plane
  7150. */
  7151. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  7152. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  7153. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  7154. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  7155. frustumPlane.d = transform.m[15] - transform.m[14];
  7156. frustumPlane.normalize();
  7157. };
  7158. /**
  7159. * Gets the left frustum plane transformed by the transform matrix
  7160. * @param transform transformation matrix to be applied to the resulting frustum plane
  7161. * @param frustumPlane the resuling frustum plane
  7162. */
  7163. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  7164. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  7165. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  7166. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  7167. frustumPlane.d = transform.m[15] + transform.m[12];
  7168. frustumPlane.normalize();
  7169. };
  7170. /**
  7171. * Gets the right frustum plane transformed by the transform matrix
  7172. * @param transform transformation matrix to be applied to the resulting frustum plane
  7173. * @param frustumPlane the resuling frustum plane
  7174. */
  7175. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  7176. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  7177. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  7178. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  7179. frustumPlane.d = transform.m[15] - transform.m[12];
  7180. frustumPlane.normalize();
  7181. };
  7182. /**
  7183. * Gets the top frustum plane transformed by the transform matrix
  7184. * @param transform transformation matrix to be applied to the resulting frustum plane
  7185. * @param frustumPlane the resuling frustum plane
  7186. */
  7187. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  7188. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  7189. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  7190. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  7191. frustumPlane.d = transform.m[15] - transform.m[13];
  7192. frustumPlane.normalize();
  7193. };
  7194. /**
  7195. * Gets the bottom frustum plane transformed by the transform matrix
  7196. * @param transform transformation matrix to be applied to the resulting frustum plane
  7197. * @param frustumPlane the resuling frustum plane
  7198. */
  7199. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  7200. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  7201. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  7202. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  7203. frustumPlane.d = transform.m[15] + transform.m[13];
  7204. frustumPlane.normalize();
  7205. };
  7206. /**
  7207. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  7208. * @param transform transformation matrix to be applied to the resulting frustum planes
  7209. * @param frustumPlanes the resuling frustum planes
  7210. */
  7211. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  7212. // Near
  7213. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  7214. // Far
  7215. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  7216. // Left
  7217. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  7218. // Right
  7219. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  7220. // Top
  7221. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  7222. // Bottom
  7223. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  7224. };
  7225. return Frustum;
  7226. }());
  7227. BABYLON.Frustum = Frustum;
  7228. /** Defines supported spaces */
  7229. var Space;
  7230. (function (Space) {
  7231. /** Local (object) space */
  7232. Space[Space["LOCAL"] = 0] = "LOCAL";
  7233. /** World space */
  7234. Space[Space["WORLD"] = 1] = "WORLD";
  7235. /** Bone space */
  7236. Space[Space["BONE"] = 2] = "BONE";
  7237. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  7238. /** Defines the 3 main axes */
  7239. var Axis = /** @class */ (function () {
  7240. function Axis() {
  7241. }
  7242. /** X axis */
  7243. Axis.X = new Vector3(1.0, 0.0, 0.0);
  7244. /** Y axis */
  7245. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  7246. /** Z axis */
  7247. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  7248. return Axis;
  7249. }());
  7250. BABYLON.Axis = Axis;
  7251. /** Class used to represent a Bezier curve */
  7252. var BezierCurve = /** @class */ (function () {
  7253. function BezierCurve() {
  7254. }
  7255. /**
  7256. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  7257. * @param t defines the time
  7258. * @param x1 defines the left coordinate on X axis
  7259. * @param y1 defines the left coordinate on Y axis
  7260. * @param x2 defines the right coordinate on X axis
  7261. * @param y2 defines the right coordinate on Y axis
  7262. * @returns the interpolated value
  7263. */
  7264. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  7265. // Extract X (which is equal to time here)
  7266. var f0 = 1 - 3 * x2 + 3 * x1;
  7267. var f1 = 3 * x2 - 6 * x1;
  7268. var f2 = 3 * x1;
  7269. var refinedT = t;
  7270. for (var i = 0; i < 5; i++) {
  7271. var refinedT2 = refinedT * refinedT;
  7272. var refinedT3 = refinedT2 * refinedT;
  7273. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  7274. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  7275. refinedT -= (x - t) * slope;
  7276. refinedT = Math.min(1, Math.max(0, refinedT));
  7277. }
  7278. // Resolve cubic bezier for the given x
  7279. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  7280. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  7281. Math.pow(refinedT, 3);
  7282. };
  7283. return BezierCurve;
  7284. }());
  7285. BABYLON.BezierCurve = BezierCurve;
  7286. /**
  7287. * Defines potential orientation for back face culling
  7288. */
  7289. var Orientation;
  7290. (function (Orientation) {
  7291. /**
  7292. * Clockwise
  7293. */
  7294. Orientation[Orientation["CW"] = 0] = "CW";
  7295. /** Counter clockwise */
  7296. Orientation[Orientation["CCW"] = 1] = "CCW";
  7297. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  7298. /**
  7299. * Defines angle representation
  7300. */
  7301. var Angle = /** @class */ (function () {
  7302. /**
  7303. * Creates an Angle object of "radians" radians (float).
  7304. */
  7305. function Angle(radians) {
  7306. this._radians = radians;
  7307. if (this._radians < 0.0) {
  7308. this._radians += (2.0 * Math.PI);
  7309. }
  7310. }
  7311. /**
  7312. * Get value in degrees
  7313. * @returns the Angle value in degrees (float)
  7314. */
  7315. Angle.prototype.degrees = function () {
  7316. return this._radians * 180.0 / Math.PI;
  7317. };
  7318. /**
  7319. * Get value in radians
  7320. * @returns the Angle value in radians (float)
  7321. */
  7322. Angle.prototype.radians = function () {
  7323. return this._radians;
  7324. };
  7325. /**
  7326. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  7327. * @param a defines first vector
  7328. * @param b defines second vector
  7329. * @returns a new Angle
  7330. */
  7331. Angle.BetweenTwoPoints = function (a, b) {
  7332. var delta = b.subtract(a);
  7333. var theta = Math.atan2(delta.y, delta.x);
  7334. return new Angle(theta);
  7335. };
  7336. /**
  7337. * Gets a new Angle object from the given float in radians
  7338. * @param radians defines the angle value in radians
  7339. * @returns a new Angle
  7340. */
  7341. Angle.FromRadians = function (radians) {
  7342. return new Angle(radians);
  7343. };
  7344. /**
  7345. * Gets a new Angle object from the given float in degrees
  7346. * @param degrees defines the angle value in degrees
  7347. * @returns a new Angle
  7348. */
  7349. Angle.FromDegrees = function (degrees) {
  7350. return new Angle(degrees * Math.PI / 180.0);
  7351. };
  7352. return Angle;
  7353. }());
  7354. BABYLON.Angle = Angle;
  7355. /**
  7356. * This represents an arc in a 2d space.
  7357. */
  7358. var Arc2 = /** @class */ (function () {
  7359. /**
  7360. * Creates an Arc object from the three given points : start, middle and end.
  7361. * @param startPoint Defines the start point of the arc
  7362. * @param midPoint Defines the midlle point of the arc
  7363. * @param endPoint Defines the end point of the arc
  7364. */
  7365. function Arc2(
  7366. /** Defines the start point of the arc */
  7367. startPoint,
  7368. /** Defines the mid point of the arc */
  7369. midPoint,
  7370. /** Defines the end point of the arc */
  7371. endPoint) {
  7372. this.startPoint = startPoint;
  7373. this.midPoint = midPoint;
  7374. this.endPoint = endPoint;
  7375. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7376. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7377. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7378. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7379. 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);
  7380. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7381. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7382. var a1 = this.startAngle.degrees();
  7383. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7384. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7385. // angles correction
  7386. if (a2 - a1 > +180.0) {
  7387. a2 -= 360.0;
  7388. }
  7389. if (a2 - a1 < -180.0) {
  7390. a2 += 360.0;
  7391. }
  7392. if (a3 - a2 > +180.0) {
  7393. a3 -= 360.0;
  7394. }
  7395. if (a3 - a2 < -180.0) {
  7396. a3 += 360.0;
  7397. }
  7398. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7399. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7400. }
  7401. return Arc2;
  7402. }());
  7403. BABYLON.Arc2 = Arc2;
  7404. /**
  7405. * Represents a 2D path made up of multiple 2D points
  7406. */
  7407. var Path2 = /** @class */ (function () {
  7408. /**
  7409. * Creates a Path2 object from the starting 2D coordinates x and y.
  7410. * @param x the starting points x value
  7411. * @param y the starting points y value
  7412. */
  7413. function Path2(x, y) {
  7414. this._points = new Array();
  7415. this._length = 0.0;
  7416. /**
  7417. * If the path start and end point are the same
  7418. */
  7419. this.closed = false;
  7420. this._points.push(new Vector2(x, y));
  7421. }
  7422. /**
  7423. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7424. * @param x the added points x value
  7425. * @param y the added points y value
  7426. * @returns the updated Path2.
  7427. */
  7428. Path2.prototype.addLineTo = function (x, y) {
  7429. if (this.closed) {
  7430. return this;
  7431. }
  7432. var newPoint = new Vector2(x, y);
  7433. var previousPoint = this._points[this._points.length - 1];
  7434. this._points.push(newPoint);
  7435. this._length += newPoint.subtract(previousPoint).length();
  7436. return this;
  7437. };
  7438. /**
  7439. * 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.
  7440. * @param midX middle point x value
  7441. * @param midY middle point y value
  7442. * @param endX end point x value
  7443. * @param endY end point y value
  7444. * @param numberOfSegments (default: 36)
  7445. * @returns the updated Path2.
  7446. */
  7447. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7448. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7449. if (this.closed) {
  7450. return this;
  7451. }
  7452. var startPoint = this._points[this._points.length - 1];
  7453. var midPoint = new Vector2(midX, midY);
  7454. var endPoint = new Vector2(endX, endY);
  7455. var arc = new Arc2(startPoint, midPoint, endPoint);
  7456. var increment = arc.angle.radians() / numberOfSegments;
  7457. if (arc.orientation === Orientation.CW) {
  7458. increment *= -1;
  7459. }
  7460. var currentAngle = arc.startAngle.radians() + increment;
  7461. for (var i = 0; i < numberOfSegments; i++) {
  7462. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7463. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7464. this.addLineTo(x, y);
  7465. currentAngle += increment;
  7466. }
  7467. return this;
  7468. };
  7469. /**
  7470. * Closes the Path2.
  7471. * @returns the Path2.
  7472. */
  7473. Path2.prototype.close = function () {
  7474. this.closed = true;
  7475. return this;
  7476. };
  7477. /**
  7478. * Gets the sum of the distance between each sequential point in the path
  7479. * @returns the Path2 total length (float).
  7480. */
  7481. Path2.prototype.length = function () {
  7482. var result = this._length;
  7483. if (!this.closed) {
  7484. var lastPoint = this._points[this._points.length - 1];
  7485. var firstPoint = this._points[0];
  7486. result += (firstPoint.subtract(lastPoint).length());
  7487. }
  7488. return result;
  7489. };
  7490. /**
  7491. * Gets the points which construct the path
  7492. * @returns the Path2 internal array of points.
  7493. */
  7494. Path2.prototype.getPoints = function () {
  7495. return this._points;
  7496. };
  7497. /**
  7498. * Retreives the point at the distance aways from the starting point
  7499. * @param normalizedLengthPosition the length along the path to retreive the point from
  7500. * @returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7501. */
  7502. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7503. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7504. return Vector2.Zero();
  7505. }
  7506. var lengthPosition = normalizedLengthPosition * this.length();
  7507. var previousOffset = 0;
  7508. for (var i = 0; i < this._points.length; i++) {
  7509. var j = (i + 1) % this._points.length;
  7510. var a = this._points[i];
  7511. var b = this._points[j];
  7512. var bToA = b.subtract(a);
  7513. var nextOffset = (bToA.length() + previousOffset);
  7514. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7515. var dir = bToA.normalize();
  7516. var localOffset = lengthPosition - previousOffset;
  7517. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7518. }
  7519. previousOffset = nextOffset;
  7520. }
  7521. return Vector2.Zero();
  7522. };
  7523. /**
  7524. * Creates a new path starting from an x and y position
  7525. * @param x starting x value
  7526. * @param y starting y value
  7527. * @returns a new Path2 starting at the coordinates (x, y).
  7528. */
  7529. Path2.StartingAt = function (x, y) {
  7530. return new Path2(x, y);
  7531. };
  7532. return Path2;
  7533. }());
  7534. BABYLON.Path2 = Path2;
  7535. /**
  7536. * Represents a 3D path made up of multiple 3D points
  7537. */
  7538. var Path3D = /** @class */ (function () {
  7539. /**
  7540. * new Path3D(path, normal, raw)
  7541. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7542. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7543. * @param path an array of Vector3, the curve axis of the Path3D
  7544. * @param normal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7545. * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7546. */
  7547. function Path3D(
  7548. /**
  7549. * an array of Vector3, the curve axis of the Path3D
  7550. */
  7551. path, firstNormal, raw) {
  7552. if (firstNormal === void 0) { firstNormal = null; }
  7553. this.path = path;
  7554. this._curve = new Array();
  7555. this._distances = new Array();
  7556. this._tangents = new Array();
  7557. this._normals = new Array();
  7558. this._binormals = new Array();
  7559. for (var p = 0; p < path.length; p++) {
  7560. this._curve[p] = path[p].clone(); // hard copy
  7561. }
  7562. this._raw = raw || false;
  7563. this._compute(firstNormal);
  7564. }
  7565. /**
  7566. * Returns the Path3D array of successive Vector3 designing its curve.
  7567. * @returns the Path3D array of successive Vector3 designing its curve.
  7568. */
  7569. Path3D.prototype.getCurve = function () {
  7570. return this._curve;
  7571. };
  7572. /**
  7573. * Returns an array populated with tangent vectors on each Path3D curve point.
  7574. * @returns an array populated with tangent vectors on each Path3D curve point.
  7575. */
  7576. Path3D.prototype.getTangents = function () {
  7577. return this._tangents;
  7578. };
  7579. /**
  7580. * Returns an array populated with normal vectors on each Path3D curve point.
  7581. * @returns an array populated with normal vectors on each Path3D curve point.
  7582. */
  7583. Path3D.prototype.getNormals = function () {
  7584. return this._normals;
  7585. };
  7586. /**
  7587. * Returns an array populated with binormal vectors on each Path3D curve point.
  7588. * @returns an array populated with binormal vectors on each Path3D curve point.
  7589. */
  7590. Path3D.prototype.getBinormals = function () {
  7591. return this._binormals;
  7592. };
  7593. /**
  7594. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7595. * @returns an array populated with distances (float) of the i-th point from the first curve point.
  7596. */
  7597. Path3D.prototype.getDistances = function () {
  7598. return this._distances;
  7599. };
  7600. /**
  7601. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7602. * @param path path which all values are copied into the curves points
  7603. * @param firstNormal which should be projected onto the curve
  7604. * @returns the same object updated.
  7605. */
  7606. Path3D.prototype.update = function (path, firstNormal) {
  7607. if (firstNormal === void 0) { firstNormal = null; }
  7608. for (var p = 0; p < path.length; p++) {
  7609. this._curve[p].x = path[p].x;
  7610. this._curve[p].y = path[p].y;
  7611. this._curve[p].z = path[p].z;
  7612. }
  7613. this._compute(firstNormal);
  7614. return this;
  7615. };
  7616. // private function compute() : computes tangents, normals and binormals
  7617. Path3D.prototype._compute = function (firstNormal) {
  7618. var l = this._curve.length;
  7619. // first and last tangents
  7620. this._tangents[0] = this._getFirstNonNullVector(0);
  7621. if (!this._raw) {
  7622. this._tangents[0].normalize();
  7623. }
  7624. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7625. if (!this._raw) {
  7626. this._tangents[l - 1].normalize();
  7627. }
  7628. // normals and binormals at first point : arbitrary vector with _normalVector()
  7629. var tg0 = this._tangents[0];
  7630. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7631. this._normals[0] = pp0;
  7632. if (!this._raw) {
  7633. this._normals[0].normalize();
  7634. }
  7635. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7636. if (!this._raw) {
  7637. this._binormals[0].normalize();
  7638. }
  7639. this._distances[0] = 0.0;
  7640. // normals and binormals : next points
  7641. var prev; // previous vector (segment)
  7642. var cur; // current vector (segment)
  7643. var curTang; // current tangent
  7644. // previous normal
  7645. var prevBinor; // previous binormal
  7646. for (var i = 1; i < l; i++) {
  7647. // tangents
  7648. prev = this._getLastNonNullVector(i);
  7649. if (i < l - 1) {
  7650. cur = this._getFirstNonNullVector(i);
  7651. this._tangents[i] = prev.add(cur);
  7652. this._tangents[i].normalize();
  7653. }
  7654. this._distances[i] = this._distances[i - 1] + prev.length();
  7655. // normals and binormals
  7656. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7657. curTang = this._tangents[i];
  7658. prevBinor = this._binormals[i - 1];
  7659. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7660. if (!this._raw) {
  7661. this._normals[i].normalize();
  7662. }
  7663. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7664. if (!this._raw) {
  7665. this._binormals[i].normalize();
  7666. }
  7667. }
  7668. };
  7669. // private function getFirstNonNullVector(index)
  7670. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7671. Path3D.prototype._getFirstNonNullVector = function (index) {
  7672. var i = 1;
  7673. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7674. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7675. i++;
  7676. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7677. }
  7678. return nNVector;
  7679. };
  7680. // private function getLastNonNullVector(index)
  7681. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7682. Path3D.prototype._getLastNonNullVector = function (index) {
  7683. var i = 1;
  7684. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7685. while (nLVector.length() === 0 && index > i + 1) {
  7686. i++;
  7687. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7688. }
  7689. return nLVector;
  7690. };
  7691. // private function normalVector(v0, vt, va) :
  7692. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7693. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7694. Path3D.prototype._normalVector = function (v0, vt, va) {
  7695. var normal0;
  7696. var tgl = vt.length();
  7697. if (tgl === 0.0) {
  7698. tgl = 1.0;
  7699. }
  7700. if (va === undefined || va === null) {
  7701. var point;
  7702. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7703. point = new Vector3(0.0, -1.0, 0.0);
  7704. }
  7705. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7706. point = new Vector3(1.0, 0.0, 0.0);
  7707. }
  7708. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7709. point = new Vector3(0.0, 0.0, 1.0);
  7710. }
  7711. else {
  7712. point = Vector3.Zero();
  7713. }
  7714. normal0 = Vector3.Cross(vt, point);
  7715. }
  7716. else {
  7717. normal0 = Vector3.Cross(vt, va);
  7718. Vector3.CrossToRef(normal0, vt, normal0);
  7719. }
  7720. normal0.normalize();
  7721. return normal0;
  7722. };
  7723. return Path3D;
  7724. }());
  7725. BABYLON.Path3D = Path3D;
  7726. /**
  7727. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7728. * A Curve3 is designed from a series of successive Vector3.
  7729. * @see https://doc.babylonjs.com/how_to/how_to_use_curve3
  7730. */
  7731. var Curve3 = /** @class */ (function () {
  7732. /**
  7733. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7734. * A Curve3 is designed from a series of successive Vector3.
  7735. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7736. * @param points points which make up the curve
  7737. */
  7738. function Curve3(points) {
  7739. this._length = 0.0;
  7740. this._points = points;
  7741. this._length = this._computeLength(points);
  7742. }
  7743. /**
  7744. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7745. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7746. * @param v1 (Vector3) the control point
  7747. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7748. * @param nbPoints (integer) the wanted number of points in the curve
  7749. * @returns the created Curve3
  7750. */
  7751. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7752. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7753. var bez = new Array();
  7754. var equation = function (t, val0, val1, val2) {
  7755. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7756. return res;
  7757. };
  7758. for (var i = 0; i <= nbPoints; i++) {
  7759. 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)));
  7760. }
  7761. return new Curve3(bez);
  7762. };
  7763. /**
  7764. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7765. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7766. * @param v1 (Vector3) the first control point
  7767. * @param v2 (Vector3) the second control point
  7768. * @param v3 (Vector3) the end point of the Cubic Bezier
  7769. * @param nbPoints (integer) the wanted number of points in the curve
  7770. * @returns the created Curve3
  7771. */
  7772. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7773. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7774. var bez = new Array();
  7775. var equation = function (t, val0, val1, val2, val3) {
  7776. 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;
  7777. return res;
  7778. };
  7779. for (var i = 0; i <= nbPoints; i++) {
  7780. 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)));
  7781. }
  7782. return new Curve3(bez);
  7783. };
  7784. /**
  7785. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7786. * @param p1 (Vector3) the origin point of the Hermite Spline
  7787. * @param t1 (Vector3) the tangent vector at the origin point
  7788. * @param p2 (Vector3) the end point of the Hermite Spline
  7789. * @param t2 (Vector3) the tangent vector at the end point
  7790. * @param nbPoints (integer) the wanted number of points in the curve
  7791. * @returns the created Curve3
  7792. */
  7793. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7794. var hermite = new Array();
  7795. var step = 1.0 / nbPoints;
  7796. for (var i = 0; i <= nbPoints; i++) {
  7797. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7798. }
  7799. return new Curve3(hermite);
  7800. };
  7801. /**
  7802. * Returns a Curve3 object along a CatmullRom Spline curve :
  7803. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7804. * @param nbPoints (integer) the wanted number of points between each curve control points
  7805. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7806. * @returns the created Curve3
  7807. */
  7808. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7809. var catmullRom = new Array();
  7810. var step = 1.0 / nbPoints;
  7811. var amount = 0.0;
  7812. if (closed) {
  7813. var pointsCount = points.length;
  7814. for (var i = 0; i < pointsCount; i++) {
  7815. amount = 0;
  7816. for (var c = 0; c < nbPoints; c++) {
  7817. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7818. amount += step;
  7819. }
  7820. }
  7821. catmullRom.push(catmullRom[0]);
  7822. }
  7823. else {
  7824. var totalPoints = new Array();
  7825. totalPoints.push(points[0].clone());
  7826. Array.prototype.push.apply(totalPoints, points);
  7827. totalPoints.push(points[points.length - 1].clone());
  7828. for (var i = 0; i < totalPoints.length - 3; i++) {
  7829. amount = 0;
  7830. for (var c = 0; c < nbPoints; c++) {
  7831. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7832. amount += step;
  7833. }
  7834. }
  7835. i--;
  7836. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7837. }
  7838. return new Curve3(catmullRom);
  7839. };
  7840. /**
  7841. * @returns the Curve3 stored array of successive Vector3
  7842. */
  7843. Curve3.prototype.getPoints = function () {
  7844. return this._points;
  7845. };
  7846. /**
  7847. * @returns the computed length (float) of the curve.
  7848. */
  7849. Curve3.prototype.length = function () {
  7850. return this._length;
  7851. };
  7852. /**
  7853. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7854. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7855. * curveA and curveB keep unchanged.
  7856. * @param curve the curve to continue from this curve
  7857. * @returns the newly constructed curve
  7858. */
  7859. Curve3.prototype.continue = function (curve) {
  7860. var lastPoint = this._points[this._points.length - 1];
  7861. var continuedPoints = this._points.slice();
  7862. var curvePoints = curve.getPoints();
  7863. for (var i = 1; i < curvePoints.length; i++) {
  7864. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7865. }
  7866. var continuedCurve = new Curve3(continuedPoints);
  7867. return continuedCurve;
  7868. };
  7869. Curve3.prototype._computeLength = function (path) {
  7870. var l = 0;
  7871. for (var i = 1; i < path.length; i++) {
  7872. l += (path[i].subtract(path[i - 1])).length();
  7873. }
  7874. return l;
  7875. };
  7876. return Curve3;
  7877. }());
  7878. BABYLON.Curve3 = Curve3;
  7879. // Vertex formats
  7880. /**
  7881. * Contains position and normal vectors for a vertex
  7882. */
  7883. var PositionNormalVertex = /** @class */ (function () {
  7884. /**
  7885. * Creates a PositionNormalVertex
  7886. * @param position the position of the vertex (defaut: 0,0,0)
  7887. * @param normal the normal of the vertex (defaut: 0,1,0)
  7888. */
  7889. function PositionNormalVertex(
  7890. /** the position of the vertex (defaut: 0,0,0) */
  7891. position,
  7892. /** the normal of the vertex (defaut: 0,1,0) */
  7893. normal) {
  7894. if (position === void 0) { position = Vector3.Zero(); }
  7895. if (normal === void 0) { normal = Vector3.Up(); }
  7896. this.position = position;
  7897. this.normal = normal;
  7898. }
  7899. /**
  7900. * Clones the PositionNormalVertex
  7901. * @returns the cloned PositionNormalVertex
  7902. */
  7903. PositionNormalVertex.prototype.clone = function () {
  7904. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7905. };
  7906. return PositionNormalVertex;
  7907. }());
  7908. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7909. /**
  7910. * Contains position, normal and uv vectors for a vertex
  7911. */
  7912. var PositionNormalTextureVertex = /** @class */ (function () {
  7913. /**
  7914. * Creates a PositionNormalTextureVertex
  7915. * @param position the position of the vertex (defaut: 0,0,0)
  7916. * @param normal the normal of the vertex (defaut: 0,1,0)
  7917. * @param uv the uv of the vertex (default: 0,0)
  7918. */
  7919. function PositionNormalTextureVertex(
  7920. /** the position of the vertex (defaut: 0,0,0) */
  7921. position,
  7922. /** the normal of the vertex (defaut: 0,1,0) */
  7923. normal,
  7924. /** the uv of the vertex (default: 0,0) */
  7925. uv) {
  7926. if (position === void 0) { position = Vector3.Zero(); }
  7927. if (normal === void 0) { normal = Vector3.Up(); }
  7928. if (uv === void 0) { uv = Vector2.Zero(); }
  7929. this.position = position;
  7930. this.normal = normal;
  7931. this.uv = uv;
  7932. }
  7933. /**
  7934. * Clones the PositionNormalTextureVertex
  7935. * @returns the cloned PositionNormalTextureVertex
  7936. */
  7937. PositionNormalTextureVertex.prototype.clone = function () {
  7938. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7939. };
  7940. return PositionNormalTextureVertex;
  7941. }());
  7942. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7943. // Temporary pre-allocated objects for engine internal use
  7944. // usage in any internal function :
  7945. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7946. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7947. /**
  7948. * @hidden
  7949. */
  7950. var Tmp = /** @class */ (function () {
  7951. function Tmp() {
  7952. }
  7953. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7954. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7955. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7956. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7957. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7958. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7959. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7960. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7961. Matrix.Zero(), Matrix.Zero(),
  7962. Matrix.Zero(), Matrix.Zero(),
  7963. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7964. return Tmp;
  7965. }());
  7966. BABYLON.Tmp = Tmp;
  7967. /**
  7968. * @hidden
  7969. * Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7970. */
  7971. var MathTmp = /** @class */ (function () {
  7972. function MathTmp() {
  7973. }
  7974. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7975. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7976. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7977. return MathTmp;
  7978. }());
  7979. })(BABYLON || (BABYLON = {}));
  7980. //# sourceMappingURL=babylon.math.js.map
  7981. var BABYLON;
  7982. (function (BABYLON) {
  7983. /**
  7984. * Scalar computation library
  7985. */
  7986. var Scalar = /** @class */ (function () {
  7987. function Scalar() {
  7988. }
  7989. /**
  7990. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7991. * @param a number
  7992. * @param b number
  7993. * @param epsilon (default = 1.401298E-45)
  7994. * @returns true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7995. */
  7996. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7997. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7998. var num = a - b;
  7999. return -epsilon <= num && num <= epsilon;
  8000. };
  8001. /**
  8002. * Returns a string : the upper case translation of the number i to hexadecimal.
  8003. * @param i number
  8004. * @returns the upper case translation of the number i to hexadecimal.
  8005. */
  8006. Scalar.ToHex = function (i) {
  8007. var str = i.toString(16);
  8008. if (i <= 15) {
  8009. return ("0" + str).toUpperCase();
  8010. }
  8011. return str.toUpperCase();
  8012. };
  8013. /**
  8014. * Returns -1 if value is negative and +1 is value is positive.
  8015. * @param value the value
  8016. * @returns the value itself if it's equal to zero.
  8017. */
  8018. Scalar.Sign = function (value) {
  8019. value = +value; // convert to a number
  8020. if (value === 0 || isNaN(value)) {
  8021. return value;
  8022. }
  8023. return value > 0 ? 1 : -1;
  8024. };
  8025. /**
  8026. * Returns the value itself if it's between min and max.
  8027. * Returns min if the value is lower than min.
  8028. * Returns max if the value is greater than max.
  8029. * @param value the value to clmap
  8030. * @param min the min value to clamp to (default: 0)
  8031. * @param max the max value to clamp to (default: 1)
  8032. * @returns the clamped value
  8033. */
  8034. Scalar.Clamp = function (value, min, max) {
  8035. if (min === void 0) { min = 0; }
  8036. if (max === void 0) { max = 1; }
  8037. return Math.min(max, Math.max(min, value));
  8038. };
  8039. /**
  8040. * the log2 of value.
  8041. * @param value the value to compute log2 of
  8042. * @returns the log2 of value.
  8043. */
  8044. Scalar.Log2 = function (value) {
  8045. return Math.log(value) * Math.LOG2E;
  8046. };
  8047. /**
  8048. * Loops the value, so that it is never larger than length and never smaller than 0.
  8049. *
  8050. * This is similar to the modulo operator but it works with floating point numbers.
  8051. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  8052. * With t = 5 and length = 2.5, the result would be 0.0.
  8053. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  8054. * @param value the value
  8055. * @param length the length
  8056. * @returns the looped value
  8057. */
  8058. Scalar.Repeat = function (value, length) {
  8059. return value - Math.floor(value / length) * length;
  8060. };
  8061. /**
  8062. * Normalize the value between 0.0 and 1.0 using min and max values
  8063. * @param value value to normalize
  8064. * @param min max to normalize between
  8065. * @param max min to normalize between
  8066. * @returns the normalized value
  8067. */
  8068. Scalar.Normalize = function (value, min, max) {
  8069. return (value - min) / (max - min);
  8070. };
  8071. /**
  8072. * Denormalize the value from 0.0 and 1.0 using min and max values
  8073. * @param normalized value to denormalize
  8074. * @param min max to denormalize between
  8075. * @param max min to denormalize between
  8076. * @returns the denormalized value
  8077. */
  8078. Scalar.Denormalize = function (normalized, min, max) {
  8079. return (normalized * (max - min) + min);
  8080. };
  8081. /**
  8082. * Calculates the shortest difference between two given angles given in degrees.
  8083. * @param current current angle in degrees
  8084. * @param target target angle in degrees
  8085. * @returns the delta
  8086. */
  8087. Scalar.DeltaAngle = function (current, target) {
  8088. var num = Scalar.Repeat(target - current, 360.0);
  8089. if (num > 180.0) {
  8090. num -= 360.0;
  8091. }
  8092. return num;
  8093. };
  8094. /**
  8095. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  8096. * @param tx value
  8097. * @param length length
  8098. * @returns The returned value will move back and forth between 0 and length
  8099. */
  8100. Scalar.PingPong = function (tx, length) {
  8101. var t = Scalar.Repeat(tx, length * 2.0);
  8102. return length - Math.abs(t - length);
  8103. };
  8104. /**
  8105. * Interpolates between min and max with smoothing at the limits.
  8106. *
  8107. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  8108. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  8109. * @param from from
  8110. * @param to to
  8111. * @param tx value
  8112. * @returns the smooth stepped value
  8113. */
  8114. Scalar.SmoothStep = function (from, to, tx) {
  8115. var t = Scalar.Clamp(tx);
  8116. t = -2.0 * t * t * t + 3.0 * t * t;
  8117. return to * t + from * (1.0 - t);
  8118. };
  8119. /**
  8120. * Moves a value current towards target.
  8121. *
  8122. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  8123. * Negative values of maxDelta pushes the value away from target.
  8124. * @param current current value
  8125. * @param target target value
  8126. * @param maxDelta max distance to move
  8127. * @returns resulting value
  8128. */
  8129. Scalar.MoveTowards = function (current, target, maxDelta) {
  8130. var result = 0;
  8131. if (Math.abs(target - current) <= maxDelta) {
  8132. result = target;
  8133. }
  8134. else {
  8135. result = current + Scalar.Sign(target - current) * maxDelta;
  8136. }
  8137. return result;
  8138. };
  8139. /**
  8140. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8141. *
  8142. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  8143. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  8144. * @param current current value
  8145. * @param target target value
  8146. * @param maxDelta max distance to move
  8147. * @returns resulting angle
  8148. */
  8149. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  8150. var num = Scalar.DeltaAngle(current, target);
  8151. var result = 0;
  8152. if (-maxDelta < num && num < maxDelta) {
  8153. result = target;
  8154. }
  8155. else {
  8156. target = current + num;
  8157. result = Scalar.MoveTowards(current, target, maxDelta);
  8158. }
  8159. return result;
  8160. };
  8161. /**
  8162. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  8163. * @param start start value
  8164. * @param end target value
  8165. * @param amount amount to lerp between
  8166. * @returns the lerped value
  8167. */
  8168. Scalar.Lerp = function (start, end, amount) {
  8169. return start + ((end - start) * amount);
  8170. };
  8171. /**
  8172. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8173. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  8174. * @param start start value
  8175. * @param end target value
  8176. * @param amount amount to lerp between
  8177. * @returns the lerped value
  8178. */
  8179. Scalar.LerpAngle = function (start, end, amount) {
  8180. var num = Scalar.Repeat(end - start, 360.0);
  8181. if (num > 180.0) {
  8182. num -= 360.0;
  8183. }
  8184. return start + num * Scalar.Clamp(amount);
  8185. };
  8186. /**
  8187. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  8188. * @param a start value
  8189. * @param b target value
  8190. * @param value value between a and b
  8191. * @returns the inverseLerp value
  8192. */
  8193. Scalar.InverseLerp = function (a, b, value) {
  8194. var result = 0;
  8195. if (a != b) {
  8196. result = Scalar.Clamp((value - a) / (b - a));
  8197. }
  8198. else {
  8199. result = 0.0;
  8200. }
  8201. return result;
  8202. };
  8203. /**
  8204. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  8205. * @see http://mathworld.wolfram.com/HermitePolynomial.html
  8206. * @param value1 spline value
  8207. * @param tangent1 spline value
  8208. * @param value2 spline value
  8209. * @param tangent2 spline value
  8210. * @param amount input value
  8211. * @returns hermite result
  8212. */
  8213. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  8214. var squared = amount * amount;
  8215. var cubed = amount * squared;
  8216. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  8217. var part2 = (-2.0 * cubed) + (3.0 * squared);
  8218. var part3 = (cubed - (2.0 * squared)) + amount;
  8219. var part4 = cubed - squared;
  8220. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  8221. };
  8222. /**
  8223. * Returns a random float number between and min and max values
  8224. * @param min min value of random
  8225. * @param max max value of random
  8226. * @returns random value
  8227. */
  8228. Scalar.RandomRange = function (min, max) {
  8229. if (min === max) {
  8230. return min;
  8231. }
  8232. return ((Math.random() * (max - min)) + min);
  8233. };
  8234. /**
  8235. * This function returns percentage of a number in a given range.
  8236. *
  8237. * RangeToPercent(40,20,60) will return 0.5 (50%)
  8238. * RangeToPercent(34,0,100) will return 0.34 (34%)
  8239. * @param number to convert to percentage
  8240. * @param min min range
  8241. * @param max max range
  8242. * @returns the percentage
  8243. */
  8244. Scalar.RangeToPercent = function (number, min, max) {
  8245. return ((number - min) / (max - min));
  8246. };
  8247. /**
  8248. * This function returns number that corresponds to the percentage in a given range.
  8249. *
  8250. * PercentToRange(0.34,0,100) will return 34.
  8251. * @param percent to convert to number
  8252. * @param min min range
  8253. * @param max max range
  8254. * @returns the number
  8255. */
  8256. Scalar.PercentToRange = function (percent, min, max) {
  8257. return ((max - min) * percent + min);
  8258. };
  8259. /**
  8260. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  8261. * @param angle The angle to normalize in radian.
  8262. * @return The converted angle.
  8263. */
  8264. Scalar.NormalizeRadians = function (angle) {
  8265. // More precise but slower version kept for reference.
  8266. // angle = angle % Tools.TwoPi;
  8267. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  8268. //if (angle > Math.PI) {
  8269. // angle -= Tools.TwoPi;
  8270. //}
  8271. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  8272. return angle;
  8273. };
  8274. /**
  8275. * Two pi constants convenient for computation.
  8276. */
  8277. Scalar.TwoPi = Math.PI * 2;
  8278. return Scalar;
  8279. }());
  8280. BABYLON.Scalar = Scalar;
  8281. })(BABYLON || (BABYLON = {}));
  8282. //# sourceMappingURL=babylon.math.scalar.js.map
  8283. //# sourceMappingURL=babylon.mixins.js.map
  8284. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  8285. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  8286. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  8287. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  8288. //# sourceMappingURL=babylon.webgl2.js.map
  8289. var BABYLON;
  8290. (function (BABYLON) {
  8291. var __decoratorInitialStore = {};
  8292. var __mergedStore = {};
  8293. var _copySource = function (creationFunction, source, instanciate) {
  8294. var destination = creationFunction();
  8295. // Tags
  8296. if (BABYLON.Tags) {
  8297. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8298. }
  8299. var classStore = getMergedStore(destination);
  8300. // Properties
  8301. for (var property in classStore) {
  8302. var propertyDescriptor = classStore[property];
  8303. var sourceProperty = source[property];
  8304. var propertyType = propertyDescriptor.type;
  8305. if (sourceProperty !== undefined && sourceProperty !== null) {
  8306. switch (propertyType) {
  8307. case 0: // Value
  8308. case 6: // Mesh reference
  8309. case 11: // Camera reference
  8310. destination[property] = sourceProperty;
  8311. break;
  8312. case 1: // Texture
  8313. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  8314. break;
  8315. case 2: // Color3
  8316. case 3: // FresnelParameters
  8317. case 4: // Vector2
  8318. case 5: // Vector3
  8319. case 7: // Color Curves
  8320. case 10: // Quaternion
  8321. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  8322. break;
  8323. }
  8324. }
  8325. }
  8326. return destination;
  8327. };
  8328. function getDirectStore(target) {
  8329. var classKey = target.getClassName();
  8330. if (!__decoratorInitialStore[classKey]) {
  8331. __decoratorInitialStore[classKey] = {};
  8332. }
  8333. return __decoratorInitialStore[classKey];
  8334. }
  8335. /**
  8336. * Return the list of properties flagged as serializable
  8337. * @param target: host object
  8338. */
  8339. function getMergedStore(target) {
  8340. var classKey = target.getClassName();
  8341. if (__mergedStore[classKey]) {
  8342. return __mergedStore[classKey];
  8343. }
  8344. __mergedStore[classKey] = {};
  8345. var store = __mergedStore[classKey];
  8346. var currentTarget = target;
  8347. var currentKey = classKey;
  8348. while (currentKey) {
  8349. var initialStore = __decoratorInitialStore[currentKey];
  8350. for (var property in initialStore) {
  8351. store[property] = initialStore[property];
  8352. }
  8353. var parent_1 = void 0;
  8354. var done = false;
  8355. do {
  8356. parent_1 = Object.getPrototypeOf(currentTarget);
  8357. if (!parent_1.getClassName) {
  8358. done = true;
  8359. break;
  8360. }
  8361. if (parent_1.getClassName() !== currentKey) {
  8362. break;
  8363. }
  8364. currentTarget = parent_1;
  8365. } while (parent_1);
  8366. if (done) {
  8367. break;
  8368. }
  8369. currentKey = parent_1.getClassName();
  8370. currentTarget = parent_1;
  8371. }
  8372. return store;
  8373. }
  8374. function generateSerializableMember(type, sourceName) {
  8375. return function (target, propertyKey) {
  8376. var classStore = getDirectStore(target);
  8377. if (!classStore[propertyKey]) {
  8378. classStore[propertyKey] = { type: type, sourceName: sourceName };
  8379. }
  8380. };
  8381. }
  8382. function generateExpandMember(setCallback, targetKey) {
  8383. if (targetKey === void 0) { targetKey = null; }
  8384. return function (target, propertyKey) {
  8385. var key = targetKey || ("_" + propertyKey);
  8386. Object.defineProperty(target, propertyKey, {
  8387. get: function () {
  8388. return this[key];
  8389. },
  8390. set: function (value) {
  8391. if (this[key] === value) {
  8392. return;
  8393. }
  8394. this[key] = value;
  8395. target[setCallback].apply(this);
  8396. },
  8397. enumerable: true,
  8398. configurable: true
  8399. });
  8400. };
  8401. }
  8402. function expandToProperty(callback, targetKey) {
  8403. if (targetKey === void 0) { targetKey = null; }
  8404. return generateExpandMember(callback, targetKey);
  8405. }
  8406. BABYLON.expandToProperty = expandToProperty;
  8407. function serialize(sourceName) {
  8408. return generateSerializableMember(0, sourceName); // value member
  8409. }
  8410. BABYLON.serialize = serialize;
  8411. function serializeAsTexture(sourceName) {
  8412. return generateSerializableMember(1, sourceName); // texture member
  8413. }
  8414. BABYLON.serializeAsTexture = serializeAsTexture;
  8415. function serializeAsColor3(sourceName) {
  8416. return generateSerializableMember(2, sourceName); // color3 member
  8417. }
  8418. BABYLON.serializeAsColor3 = serializeAsColor3;
  8419. function serializeAsFresnelParameters(sourceName) {
  8420. return generateSerializableMember(3, sourceName); // fresnel parameters member
  8421. }
  8422. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  8423. function serializeAsVector2(sourceName) {
  8424. return generateSerializableMember(4, sourceName); // vector2 member
  8425. }
  8426. BABYLON.serializeAsVector2 = serializeAsVector2;
  8427. function serializeAsVector3(sourceName) {
  8428. return generateSerializableMember(5, sourceName); // vector3 member
  8429. }
  8430. BABYLON.serializeAsVector3 = serializeAsVector3;
  8431. function serializeAsMeshReference(sourceName) {
  8432. return generateSerializableMember(6, sourceName); // mesh reference member
  8433. }
  8434. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  8435. function serializeAsColorCurves(sourceName) {
  8436. return generateSerializableMember(7, sourceName); // color curves
  8437. }
  8438. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  8439. function serializeAsColor4(sourceName) {
  8440. return generateSerializableMember(8, sourceName); // color 4
  8441. }
  8442. BABYLON.serializeAsColor4 = serializeAsColor4;
  8443. function serializeAsImageProcessingConfiguration(sourceName) {
  8444. return generateSerializableMember(9, sourceName); // image processing
  8445. }
  8446. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  8447. function serializeAsQuaternion(sourceName) {
  8448. return generateSerializableMember(10, sourceName); // quaternion member
  8449. }
  8450. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  8451. /**
  8452. * Decorator used to define property that can be serialized as reference to a camera
  8453. * @param sourceName defines the name of the property to decorate
  8454. */
  8455. function serializeAsCameraReference(sourceName) {
  8456. return generateSerializableMember(11, sourceName); // camera reference member
  8457. }
  8458. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  8459. /**
  8460. * Class used to help serialization objects
  8461. */
  8462. var SerializationHelper = /** @class */ (function () {
  8463. function SerializationHelper() {
  8464. }
  8465. /**
  8466. * Static function used to serialized a specific entity
  8467. * @param entity defines the entity to serialize
  8468. * @param serializationObject defines the optional target obecjt where serialization data will be stored
  8469. * @returns a JSON compatible object representing the serialization of the entity
  8470. */
  8471. SerializationHelper.Serialize = function (entity, serializationObject) {
  8472. if (!serializationObject) {
  8473. serializationObject = {};
  8474. }
  8475. // Tags
  8476. if (BABYLON.Tags) {
  8477. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  8478. }
  8479. var serializedProperties = getMergedStore(entity);
  8480. // Properties
  8481. for (var property in serializedProperties) {
  8482. var propertyDescriptor = serializedProperties[property];
  8483. var targetPropertyName = propertyDescriptor.sourceName || property;
  8484. var propertyType = propertyDescriptor.type;
  8485. var sourceProperty = entity[property];
  8486. if (sourceProperty !== undefined && sourceProperty !== null) {
  8487. switch (propertyType) {
  8488. case 0: // Value
  8489. serializationObject[targetPropertyName] = sourceProperty;
  8490. break;
  8491. case 1: // Texture
  8492. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8493. break;
  8494. case 2: // Color3
  8495. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8496. break;
  8497. case 3: // FresnelParameters
  8498. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8499. break;
  8500. case 4: // Vector2
  8501. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8502. break;
  8503. case 5: // Vector3
  8504. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8505. break;
  8506. case 6: // Mesh reference
  8507. serializationObject[targetPropertyName] = sourceProperty.id;
  8508. break;
  8509. case 7: // Color Curves
  8510. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8511. break;
  8512. case 8: // Color 4
  8513. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8514. break;
  8515. case 9: // Image Processing
  8516. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8517. break;
  8518. case 10: // Quaternion
  8519. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8520. break;
  8521. case 11: // Camera reference
  8522. serializationObject[targetPropertyName] = sourceProperty.id;
  8523. break;
  8524. }
  8525. }
  8526. }
  8527. return serializationObject;
  8528. };
  8529. /**
  8530. * Creates a new entity from a serialization data object
  8531. * @param creationFunction defines a function used to instanciated the new entity
  8532. * @param source defines the source serialization data
  8533. * @param scene defines the hosting scene
  8534. * @param rootUrl defines the root url for resources
  8535. * @returns a new entity
  8536. */
  8537. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  8538. if (rootUrl === void 0) { rootUrl = null; }
  8539. var destination = creationFunction();
  8540. if (!rootUrl) {
  8541. rootUrl = "";
  8542. }
  8543. // Tags
  8544. if (BABYLON.Tags) {
  8545. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8546. }
  8547. var classStore = getMergedStore(destination);
  8548. // Properties
  8549. for (var property in classStore) {
  8550. var propertyDescriptor = classStore[property];
  8551. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8552. var propertyType = propertyDescriptor.type;
  8553. if (sourceProperty !== undefined && sourceProperty !== null) {
  8554. var dest = destination;
  8555. switch (propertyType) {
  8556. case 0: // Value
  8557. dest[property] = sourceProperty;
  8558. break;
  8559. case 1: // Texture
  8560. if (scene) {
  8561. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8562. }
  8563. break;
  8564. case 2: // Color3
  8565. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8566. break;
  8567. case 3: // FresnelParameters
  8568. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8569. break;
  8570. case 4: // Vector2
  8571. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8572. break;
  8573. case 5: // Vector3
  8574. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8575. break;
  8576. case 6: // Mesh reference
  8577. if (scene) {
  8578. dest[property] = scene.getLastMeshByID(sourceProperty);
  8579. }
  8580. break;
  8581. case 7: // Color Curves
  8582. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8583. break;
  8584. case 8: // Color 4
  8585. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8586. break;
  8587. case 9: // Image Processing
  8588. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8589. break;
  8590. case 10: // Quaternion
  8591. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8592. break;
  8593. case 11: // Camera reference
  8594. if (scene) {
  8595. dest[property] = scene.getCameraByID(sourceProperty);
  8596. }
  8597. break;
  8598. }
  8599. }
  8600. }
  8601. return destination;
  8602. };
  8603. /**
  8604. * Clones an object
  8605. * @param creationFunction defines the function used to instanciate the new object
  8606. * @param source defines the source object
  8607. * @returns the cloned object
  8608. */
  8609. SerializationHelper.Clone = function (creationFunction, source) {
  8610. return _copySource(creationFunction, source, false);
  8611. };
  8612. /**
  8613. * Instanciates a new object based on a source one (some data will be shared between both object)
  8614. * @param creationFunction defines the function used to instanciate the new object
  8615. * @param source defines the source object
  8616. * @returns the new object
  8617. */
  8618. SerializationHelper.Instanciate = function (creationFunction, source) {
  8619. return _copySource(creationFunction, source, true);
  8620. };
  8621. return SerializationHelper;
  8622. }());
  8623. BABYLON.SerializationHelper = SerializationHelper;
  8624. })(BABYLON || (BABYLON = {}));
  8625. //# sourceMappingURL=babylon.decorators.js.map
  8626. var BABYLON;
  8627. (function (BABYLON) {
  8628. /**
  8629. * Wrapper class for promise with external resolve and reject.
  8630. */
  8631. var Deferred = /** @class */ (function () {
  8632. /**
  8633. * Constructor for this deferred object.
  8634. */
  8635. function Deferred() {
  8636. var _this = this;
  8637. this.promise = new Promise(function (resolve, reject) {
  8638. _this._resolve = resolve;
  8639. _this._reject = reject;
  8640. });
  8641. }
  8642. Object.defineProperty(Deferred.prototype, "resolve", {
  8643. /**
  8644. * The resolve method of the promise associated with this deferred object.
  8645. */
  8646. get: function () {
  8647. return this._resolve;
  8648. },
  8649. enumerable: true,
  8650. configurable: true
  8651. });
  8652. Object.defineProperty(Deferred.prototype, "reject", {
  8653. /**
  8654. * The reject method of the promise associated with this deferred object.
  8655. */
  8656. get: function () {
  8657. return this._reject;
  8658. },
  8659. enumerable: true,
  8660. configurable: true
  8661. });
  8662. return Deferred;
  8663. }());
  8664. BABYLON.Deferred = Deferred;
  8665. })(BABYLON || (BABYLON = {}));
  8666. //# sourceMappingURL=babylon.deferred.js.map
  8667. var BABYLON;
  8668. (function (BABYLON) {
  8669. /**
  8670. * A class serves as a medium between the observable and its observers
  8671. */
  8672. var EventState = /** @class */ (function () {
  8673. /**
  8674. * Create a new EventState
  8675. * @param mask defines the mask associated with this state
  8676. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8677. * @param target defines the original target of the state
  8678. * @param currentTarget defines the current target of the state
  8679. */
  8680. function EventState(mask, skipNextObservers, target, currentTarget) {
  8681. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8682. this.initalize(mask, skipNextObservers, target, currentTarget);
  8683. }
  8684. /**
  8685. * Initialize the current event state
  8686. * @param mask defines the mask associated with this state
  8687. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8688. * @param target defines the original target of the state
  8689. * @param currentTarget defines the current target of the state
  8690. * @returns the current event state
  8691. */
  8692. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8693. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8694. this.mask = mask;
  8695. this.skipNextObservers = skipNextObservers;
  8696. this.target = target;
  8697. this.currentTarget = currentTarget;
  8698. return this;
  8699. };
  8700. return EventState;
  8701. }());
  8702. BABYLON.EventState = EventState;
  8703. /**
  8704. * Represent an Observer registered to a given Observable object.
  8705. */
  8706. var Observer = /** @class */ (function () {
  8707. /**
  8708. * Creates a new observer
  8709. * @param callback defines the callback to call when the observer is notified
  8710. * @param mask defines the mask of the observer (used to filter notifications)
  8711. * @param scope defines the current scope used to restore the JS context
  8712. */
  8713. function Observer(
  8714. /**
  8715. * Defines the callback to call when the observer is notified
  8716. */
  8717. callback,
  8718. /**
  8719. * Defines the mask of the observer (used to filter notifications)
  8720. */
  8721. mask,
  8722. /**
  8723. * Defines the current scope used to restore the JS context
  8724. */
  8725. scope) {
  8726. if (scope === void 0) { scope = null; }
  8727. this.callback = callback;
  8728. this.mask = mask;
  8729. this.scope = scope;
  8730. /** @hidden */
  8731. this._willBeUnregistered = false;
  8732. /**
  8733. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8734. */
  8735. this.unregisterOnNextCall = false;
  8736. }
  8737. return Observer;
  8738. }());
  8739. BABYLON.Observer = Observer;
  8740. /**
  8741. * Represent a list of observers registered to multiple Observables object.
  8742. */
  8743. var MultiObserver = /** @class */ (function () {
  8744. function MultiObserver() {
  8745. }
  8746. /**
  8747. * Release associated resources
  8748. */
  8749. MultiObserver.prototype.dispose = function () {
  8750. if (this._observers && this._observables) {
  8751. for (var index = 0; index < this._observers.length; index++) {
  8752. this._observables[index].remove(this._observers[index]);
  8753. }
  8754. }
  8755. this._observers = null;
  8756. this._observables = null;
  8757. };
  8758. /**
  8759. * Raise a callback when one of the observable will notify
  8760. * @param observables defines a list of observables to watch
  8761. * @param callback defines the callback to call on notification
  8762. * @param mask defines the mask used to filter notifications
  8763. * @param scope defines the current scope used to restore the JS context
  8764. * @returns the new MultiObserver
  8765. */
  8766. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8767. if (mask === void 0) { mask = -1; }
  8768. if (scope === void 0) { scope = null; }
  8769. var result = new MultiObserver();
  8770. result._observers = new Array();
  8771. result._observables = observables;
  8772. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8773. var observable = observables_1[_i];
  8774. var observer = observable.add(callback, mask, false, scope);
  8775. if (observer) {
  8776. result._observers.push(observer);
  8777. }
  8778. }
  8779. return result;
  8780. };
  8781. return MultiObserver;
  8782. }());
  8783. BABYLON.MultiObserver = MultiObserver;
  8784. /**
  8785. * The Observable class is a simple implementation of the Observable pattern.
  8786. *
  8787. * 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.
  8788. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8789. * 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).
  8790. * 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.
  8791. */
  8792. var Observable = /** @class */ (function () {
  8793. /**
  8794. * Creates a new observable
  8795. * @param onObserverAdded defines a callback to call when a new observer is added
  8796. */
  8797. function Observable(onObserverAdded) {
  8798. this._observers = new Array();
  8799. this._eventState = new EventState(0);
  8800. if (onObserverAdded) {
  8801. this._onObserverAdded = onObserverAdded;
  8802. }
  8803. }
  8804. /**
  8805. * Create a new Observer with the specified callback
  8806. * @param callback the callback that will be executed for that Observer
  8807. * @param mask the mask used to filter observers
  8808. * @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.
  8809. * @param scope optional scope for the callback to be called from
  8810. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8811. * @returns the new observer created for the callback
  8812. */
  8813. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8814. if (mask === void 0) { mask = -1; }
  8815. if (insertFirst === void 0) { insertFirst = false; }
  8816. if (scope === void 0) { scope = null; }
  8817. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8818. if (!callback) {
  8819. return null;
  8820. }
  8821. var observer = new Observer(callback, mask, scope);
  8822. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8823. if (insertFirst) {
  8824. this._observers.unshift(observer);
  8825. }
  8826. else {
  8827. this._observers.push(observer);
  8828. }
  8829. if (this._onObserverAdded) {
  8830. this._onObserverAdded(observer);
  8831. }
  8832. return observer;
  8833. };
  8834. /**
  8835. * Create a new Observer with the specified callback and unregisters after the next notification
  8836. * @param callback the callback that will be executed for that Observer
  8837. * @returns the new observer created for the callback
  8838. */
  8839. Observable.prototype.addOnce = function (callback) {
  8840. return this.add(callback, undefined, undefined, undefined, true);
  8841. };
  8842. /**
  8843. * Remove an Observer from the Observable object
  8844. * @param observer the instance of the Observer to remove
  8845. * @returns false if it doesn't belong to this Observable
  8846. */
  8847. Observable.prototype.remove = function (observer) {
  8848. if (!observer) {
  8849. return false;
  8850. }
  8851. var index = this._observers.indexOf(observer);
  8852. if (index !== -1) {
  8853. this._deferUnregister(observer);
  8854. return true;
  8855. }
  8856. return false;
  8857. };
  8858. /**
  8859. * Remove a callback from the Observable object
  8860. * @param callback the callback to remove
  8861. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8862. * @returns false if it doesn't belong to this Observable
  8863. */
  8864. Observable.prototype.removeCallback = function (callback, scope) {
  8865. for (var index = 0; index < this._observers.length; index++) {
  8866. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8867. this._deferUnregister(this._observers[index]);
  8868. return true;
  8869. }
  8870. }
  8871. return false;
  8872. };
  8873. Observable.prototype._deferUnregister = function (observer) {
  8874. var _this = this;
  8875. observer.unregisterOnNextCall = false;
  8876. observer._willBeUnregistered = true;
  8877. BABYLON.Tools.SetImmediate(function () {
  8878. _this._remove(observer);
  8879. });
  8880. };
  8881. // This should only be called when not iterating over _observers to avoid callback skipping.
  8882. // Removes an observer from the _observer Array.
  8883. Observable.prototype._remove = function (observer) {
  8884. if (!observer) {
  8885. return false;
  8886. }
  8887. var index = this._observers.indexOf(observer);
  8888. if (index !== -1) {
  8889. this._observers.splice(index, 1);
  8890. return true;
  8891. }
  8892. return false;
  8893. };
  8894. /**
  8895. * Notify all Observers by calling their respective callback with the given data
  8896. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8897. * @param eventData defines the data to send to all observers
  8898. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8899. * @param target defines the original target of the state
  8900. * @param currentTarget defines the current target of the state
  8901. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8902. */
  8903. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8904. if (mask === void 0) { mask = -1; }
  8905. if (!this._observers.length) {
  8906. return true;
  8907. }
  8908. var state = this._eventState;
  8909. state.mask = mask;
  8910. state.target = target;
  8911. state.currentTarget = currentTarget;
  8912. state.skipNextObservers = false;
  8913. state.lastReturnValue = eventData;
  8914. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8915. var obs = _a[_i];
  8916. if (obs._willBeUnregistered) {
  8917. continue;
  8918. }
  8919. if (obs.mask & mask) {
  8920. if (obs.scope) {
  8921. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8922. }
  8923. else {
  8924. state.lastReturnValue = obs.callback(eventData, state);
  8925. }
  8926. if (obs.unregisterOnNextCall) {
  8927. this._deferUnregister(obs);
  8928. }
  8929. }
  8930. if (state.skipNextObservers) {
  8931. return false;
  8932. }
  8933. }
  8934. return true;
  8935. };
  8936. /**
  8937. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8938. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8939. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8940. * and it is crucial that all callbacks will be executed.
  8941. * The order of the callbacks is kept, callbacks are not executed parallel.
  8942. *
  8943. * @param eventData The data to be sent to each callback
  8944. * @param mask is used to filter observers defaults to -1
  8945. * @param target defines the callback target (see EventState)
  8946. * @param currentTarget defines he current object in the bubbling phase
  8947. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8948. */
  8949. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8950. var _this = this;
  8951. if (mask === void 0) { mask = -1; }
  8952. // create an empty promise
  8953. var p = Promise.resolve(eventData);
  8954. // no observers? return this promise.
  8955. if (!this._observers.length) {
  8956. return p;
  8957. }
  8958. var state = this._eventState;
  8959. state.mask = mask;
  8960. state.target = target;
  8961. state.currentTarget = currentTarget;
  8962. state.skipNextObservers = false;
  8963. // execute one callback after another (not using Promise.all, the order is important)
  8964. this._observers.forEach(function (obs) {
  8965. if (state.skipNextObservers) {
  8966. return;
  8967. }
  8968. if (obs._willBeUnregistered) {
  8969. return;
  8970. }
  8971. if (obs.mask & mask) {
  8972. if (obs.scope) {
  8973. p = p.then(function (lastReturnedValue) {
  8974. state.lastReturnValue = lastReturnedValue;
  8975. return obs.callback.apply(obs.scope, [eventData, state]);
  8976. });
  8977. }
  8978. else {
  8979. p = p.then(function (lastReturnedValue) {
  8980. state.lastReturnValue = lastReturnedValue;
  8981. return obs.callback(eventData, state);
  8982. });
  8983. }
  8984. if (obs.unregisterOnNextCall) {
  8985. _this._deferUnregister(obs);
  8986. }
  8987. }
  8988. });
  8989. // return the eventData
  8990. return p.then(function () { return eventData; });
  8991. };
  8992. /**
  8993. * Notify a specific observer
  8994. * @param observer defines the observer to notify
  8995. * @param eventData defines the data to be sent to each callback
  8996. * @param mask is used to filter observers defaults to -1
  8997. */
  8998. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8999. if (mask === void 0) { mask = -1; }
  9000. var state = this._eventState;
  9001. state.mask = mask;
  9002. state.skipNextObservers = false;
  9003. observer.callback(eventData, state);
  9004. };
  9005. /**
  9006. * Gets a boolean indicating if the observable has at least one observer
  9007. * @returns true is the Observable has at least one Observer registered
  9008. */
  9009. Observable.prototype.hasObservers = function () {
  9010. return this._observers.length > 0;
  9011. };
  9012. /**
  9013. * Clear the list of observers
  9014. */
  9015. Observable.prototype.clear = function () {
  9016. this._observers = new Array();
  9017. this._onObserverAdded = null;
  9018. };
  9019. /**
  9020. * Clone the current observable
  9021. * @returns a new observable
  9022. */
  9023. Observable.prototype.clone = function () {
  9024. var result = new Observable();
  9025. result._observers = this._observers.slice(0);
  9026. return result;
  9027. };
  9028. /**
  9029. * Does this observable handles observer registered with a given mask
  9030. * @param mask defines the mask to be tested
  9031. * @return whether or not one observer registered with the given mask is handeled
  9032. **/
  9033. Observable.prototype.hasSpecificMask = function (mask) {
  9034. if (mask === void 0) { mask = -1; }
  9035. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  9036. var obs = _a[_i];
  9037. if (obs.mask & mask || obs.mask === mask) {
  9038. return true;
  9039. }
  9040. }
  9041. return false;
  9042. };
  9043. return Observable;
  9044. }());
  9045. BABYLON.Observable = Observable;
  9046. })(BABYLON || (BABYLON = {}));
  9047. //# sourceMappingURL=babylon.observable.js.map
  9048. var BABYLON;
  9049. (function (BABYLON) {
  9050. /**
  9051. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  9052. */
  9053. var SmartArray = /** @class */ (function () {
  9054. /**
  9055. * Instantiates a Smart Array.
  9056. * @param capacity defines the default capacity of the array.
  9057. */
  9058. function SmartArray(capacity) {
  9059. /**
  9060. * The active length of the array.
  9061. */
  9062. this.length = 0;
  9063. this.data = new Array(capacity);
  9064. this._id = SmartArray._GlobalId++;
  9065. }
  9066. /**
  9067. * Pushes a value at the end of the active data.
  9068. * @param value defines the object to push in the array.
  9069. */
  9070. SmartArray.prototype.push = function (value) {
  9071. this.data[this.length++] = value;
  9072. if (this.length > this.data.length) {
  9073. this.data.length *= 2;
  9074. }
  9075. };
  9076. /**
  9077. * Iterates over the active data and apply the lambda to them.
  9078. * @param func defines the action to apply on each value.
  9079. */
  9080. SmartArray.prototype.forEach = function (func) {
  9081. for (var index = 0; index < this.length; index++) {
  9082. func(this.data[index]);
  9083. }
  9084. };
  9085. /**
  9086. * Sorts the full sets of data.
  9087. * @param compareFn defines the comparison function to apply.
  9088. */
  9089. SmartArray.prototype.sort = function (compareFn) {
  9090. this.data.sort(compareFn);
  9091. };
  9092. /**
  9093. * Resets the active data to an empty array.
  9094. */
  9095. SmartArray.prototype.reset = function () {
  9096. this.length = 0;
  9097. };
  9098. /**
  9099. * Releases all the data from the array as well as the array.
  9100. */
  9101. SmartArray.prototype.dispose = function () {
  9102. this.reset();
  9103. if (this.data) {
  9104. this.data.length = 0;
  9105. this.data = [];
  9106. }
  9107. };
  9108. /**
  9109. * Concats the active data with a given array.
  9110. * @param array defines the data to concatenate with.
  9111. */
  9112. SmartArray.prototype.concat = function (array) {
  9113. if (array.length === 0) {
  9114. return;
  9115. }
  9116. if (this.length + array.length > this.data.length) {
  9117. this.data.length = (this.length + array.length) * 2;
  9118. }
  9119. for (var index = 0; index < array.length; index++) {
  9120. this.data[this.length++] = (array.data || array)[index];
  9121. }
  9122. };
  9123. /**
  9124. * Returns the position of a value in the active data.
  9125. * @param value defines the value to find the index for
  9126. * @returns the index if found in the active data otherwise -1
  9127. */
  9128. SmartArray.prototype.indexOf = function (value) {
  9129. var position = this.data.indexOf(value);
  9130. if (position >= this.length) {
  9131. return -1;
  9132. }
  9133. return position;
  9134. };
  9135. /**
  9136. * Returns whether an element is part of the active data.
  9137. * @param value defines the value to look for
  9138. * @returns true if found in the active data otherwise false
  9139. */
  9140. SmartArray.prototype.contains = function (value) {
  9141. return this.indexOf(value) !== -1;
  9142. };
  9143. // Statics
  9144. SmartArray._GlobalId = 0;
  9145. return SmartArray;
  9146. }());
  9147. BABYLON.SmartArray = SmartArray;
  9148. /**
  9149. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  9150. * The data in this array can only be present once
  9151. */
  9152. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  9153. __extends(SmartArrayNoDuplicate, _super);
  9154. function SmartArrayNoDuplicate() {
  9155. var _this = _super !== null && _super.apply(this, arguments) || this;
  9156. _this._duplicateId = 0;
  9157. return _this;
  9158. }
  9159. /**
  9160. * Pushes a value at the end of the active data.
  9161. * THIS DOES NOT PREVENT DUPPLICATE DATA
  9162. * @param value defines the object to push in the array.
  9163. */
  9164. SmartArrayNoDuplicate.prototype.push = function (value) {
  9165. _super.prototype.push.call(this, value);
  9166. if (!value.__smartArrayFlags) {
  9167. value.__smartArrayFlags = {};
  9168. }
  9169. value.__smartArrayFlags[this._id] = this._duplicateId;
  9170. };
  9171. /**
  9172. * Pushes a value at the end of the active data.
  9173. * If the data is already present, it won t be added again
  9174. * @param value defines the object to push in the array.
  9175. * @returns true if added false if it was already present
  9176. */
  9177. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  9178. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  9179. return false;
  9180. }
  9181. this.push(value);
  9182. return true;
  9183. };
  9184. /**
  9185. * Resets the active data to an empty array.
  9186. */
  9187. SmartArrayNoDuplicate.prototype.reset = function () {
  9188. _super.prototype.reset.call(this);
  9189. this._duplicateId++;
  9190. };
  9191. /**
  9192. * Concats the active data with a given array.
  9193. * This ensures no dupplicate will be present in the result.
  9194. * @param array defines the data to concatenate with.
  9195. */
  9196. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  9197. if (array.length === 0) {
  9198. return;
  9199. }
  9200. if (this.length + array.length > this.data.length) {
  9201. this.data.length = (this.length + array.length) * 2;
  9202. }
  9203. for (var index = 0; index < array.length; index++) {
  9204. var item = (array.data || array)[index];
  9205. this.pushNoDuplicate(item);
  9206. }
  9207. };
  9208. return SmartArrayNoDuplicate;
  9209. }(SmartArray));
  9210. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  9211. })(BABYLON || (BABYLON = {}));
  9212. //# sourceMappingURL=babylon.smartArray.js.map
  9213. var BABYLON;
  9214. (function (BABYLON) {
  9215. /** Class used to store color4 gradient */
  9216. var ColorGradient = /** @class */ (function () {
  9217. function ColorGradient() {
  9218. }
  9219. /**
  9220. * Will get a color picked randomly between color1 and color2.
  9221. * If color2 is undefined then color1 will be used
  9222. * @param result defines the target Color4 to store the result in
  9223. */
  9224. ColorGradient.prototype.getColorToRef = function (result) {
  9225. if (!this.color2) {
  9226. result.copyFrom(this.color1);
  9227. return;
  9228. }
  9229. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  9230. };
  9231. return ColorGradient;
  9232. }());
  9233. BABYLON.ColorGradient = ColorGradient;
  9234. /** Class used to store color 3 gradient */
  9235. var Color3Gradient = /** @class */ (function () {
  9236. function Color3Gradient() {
  9237. }
  9238. return Color3Gradient;
  9239. }());
  9240. BABYLON.Color3Gradient = Color3Gradient;
  9241. /** Class used to store factor gradient */
  9242. var FactorGradient = /** @class */ (function () {
  9243. function FactorGradient() {
  9244. }
  9245. /**
  9246. * Will get a number picked randomly between factor1 and factor2.
  9247. * If factor2 is undefined then factor1 will be used
  9248. * @returns the picked number
  9249. */
  9250. FactorGradient.prototype.getFactor = function () {
  9251. if (this.factor2 === undefined) {
  9252. return this.factor1;
  9253. }
  9254. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  9255. };
  9256. return FactorGradient;
  9257. }());
  9258. BABYLON.FactorGradient = FactorGradient;
  9259. /**
  9260. * @ignore
  9261. * Application error to support additional information when loading a file
  9262. */
  9263. var LoadFileError = /** @class */ (function (_super) {
  9264. __extends(LoadFileError, _super);
  9265. /**
  9266. * Creates a new LoadFileError
  9267. * @param message defines the message of the error
  9268. * @param request defines the optional XHR request
  9269. */
  9270. function LoadFileError(message,
  9271. /** defines the optional XHR request */
  9272. request) {
  9273. var _this = _super.call(this, message) || this;
  9274. _this.request = request;
  9275. _this.name = "LoadFileError";
  9276. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  9277. return _this;
  9278. }
  9279. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  9280. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  9281. // Polyfill for Object.setPrototypeOf if necessary.
  9282. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  9283. return LoadFileError;
  9284. }(Error));
  9285. BABYLON.LoadFileError = LoadFileError;
  9286. /**
  9287. * Class used to define a retry strategy when error happens while loading assets
  9288. */
  9289. var RetryStrategy = /** @class */ (function () {
  9290. function RetryStrategy() {
  9291. }
  9292. /**
  9293. * Function used to defines an exponential back off strategy
  9294. * @param maxRetries defines the maximum number of retries (3 by default)
  9295. * @param baseInterval defines the interval between retries
  9296. * @returns the strategy function to use
  9297. */
  9298. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  9299. if (maxRetries === void 0) { maxRetries = 3; }
  9300. if (baseInterval === void 0) { baseInterval = 500; }
  9301. return function (url, request, retryIndex) {
  9302. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  9303. return -1;
  9304. }
  9305. return Math.pow(2, retryIndex) * baseInterval;
  9306. };
  9307. };
  9308. return RetryStrategy;
  9309. }());
  9310. BABYLON.RetryStrategy = RetryStrategy;
  9311. // Screenshots
  9312. var screenshotCanvas;
  9313. var cloneValue = function (source, destinationObject) {
  9314. if (!source) {
  9315. return null;
  9316. }
  9317. if (source instanceof BABYLON.Mesh) {
  9318. return null;
  9319. }
  9320. if (source instanceof BABYLON.SubMesh) {
  9321. return source.clone(destinationObject);
  9322. }
  9323. else if (source.clone) {
  9324. return source.clone();
  9325. }
  9326. return null;
  9327. };
  9328. /**
  9329. * Class containing a set of static utilities functions
  9330. */
  9331. var Tools = /** @class */ (function () {
  9332. function Tools() {
  9333. }
  9334. /**
  9335. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  9336. * @param u defines the coordinate on X axis
  9337. * @param v defines the coordinate on Y axis
  9338. * @param width defines the width of the source data
  9339. * @param height defines the height of the source data
  9340. * @param pixels defines the source byte array
  9341. * @param color defines the output color
  9342. */
  9343. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  9344. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  9345. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  9346. var position = (wrappedU + wrappedV * width) * 4;
  9347. color.r = pixels[position] / 255;
  9348. color.g = pixels[position + 1] / 255;
  9349. color.b = pixels[position + 2] / 255;
  9350. color.a = pixels[position + 3] / 255;
  9351. };
  9352. /**
  9353. * Interpolates between a and b via alpha
  9354. * @param a The lower value (returned when alpha = 0)
  9355. * @param b The upper value (returned when alpha = 1)
  9356. * @param alpha The interpolation-factor
  9357. * @return The mixed value
  9358. */
  9359. Tools.Mix = function (a, b, alpha) {
  9360. return a * (1 - alpha) + b * alpha;
  9361. };
  9362. /**
  9363. * Tries to instantiate a new object from a given class name
  9364. * @param className defines the class name to instantiate
  9365. * @returns the new object or null if the system was not able to do the instantiation
  9366. */
  9367. Tools.Instantiate = function (className) {
  9368. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  9369. return Tools.RegisteredExternalClasses[className];
  9370. }
  9371. var arr = className.split(".");
  9372. var fn = (window || this);
  9373. for (var i = 0, len = arr.length; i < len; i++) {
  9374. fn = fn[arr[i]];
  9375. }
  9376. if (typeof fn !== "function") {
  9377. return null;
  9378. }
  9379. return fn;
  9380. };
  9381. /**
  9382. * Provides a slice function that will work even on IE
  9383. * @param data defines the array to slice
  9384. * @param start defines the start of the data (optional)
  9385. * @param end defines the end of the data (optional)
  9386. * @returns the new sliced array
  9387. */
  9388. Tools.Slice = function (data, start, end) {
  9389. if (data.slice) {
  9390. return data.slice(start, end);
  9391. }
  9392. return Array.prototype.slice.call(data, start, end);
  9393. };
  9394. /**
  9395. * Polyfill for setImmediate
  9396. * @param action defines the action to execute after the current execution block
  9397. */
  9398. Tools.SetImmediate = function (action) {
  9399. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  9400. window.setImmediate(action);
  9401. }
  9402. else {
  9403. setTimeout(action, 1);
  9404. }
  9405. };
  9406. /**
  9407. * Function indicating if a number is an exponent of 2
  9408. * @param value defines the value to test
  9409. * @returns true if the value is an exponent of 2
  9410. */
  9411. Tools.IsExponentOfTwo = function (value) {
  9412. var count = 1;
  9413. do {
  9414. count *= 2;
  9415. } while (count < value);
  9416. return count === value;
  9417. };
  9418. /**
  9419. * Returns the nearest 32-bit single precision float representation of a Number
  9420. * @param value A Number. If the parameter is of a different type, it will get converted
  9421. * to a number or to NaN if it cannot be converted
  9422. * @returns number
  9423. */
  9424. Tools.FloatRound = function (value) {
  9425. if (Math.fround) {
  9426. return Math.fround(value);
  9427. }
  9428. return (Tools._tmpFloatArray[0] = value);
  9429. };
  9430. /**
  9431. * Find the next highest power of two.
  9432. * @param x Number to start search from.
  9433. * @return Next highest power of two.
  9434. */
  9435. Tools.CeilingPOT = function (x) {
  9436. x--;
  9437. x |= x >> 1;
  9438. x |= x >> 2;
  9439. x |= x >> 4;
  9440. x |= x >> 8;
  9441. x |= x >> 16;
  9442. x++;
  9443. return x;
  9444. };
  9445. /**
  9446. * Find the next lowest power of two.
  9447. * @param x Number to start search from.
  9448. * @return Next lowest power of two.
  9449. */
  9450. Tools.FloorPOT = function (x) {
  9451. x = x | (x >> 1);
  9452. x = x | (x >> 2);
  9453. x = x | (x >> 4);
  9454. x = x | (x >> 8);
  9455. x = x | (x >> 16);
  9456. return x - (x >> 1);
  9457. };
  9458. /**
  9459. * Find the nearest power of two.
  9460. * @param x Number to start search from.
  9461. * @return Next nearest power of two.
  9462. */
  9463. Tools.NearestPOT = function (x) {
  9464. var c = Tools.CeilingPOT(x);
  9465. var f = Tools.FloorPOT(x);
  9466. return (c - x) > (x - f) ? f : c;
  9467. };
  9468. /**
  9469. * Get the closest exponent of two
  9470. * @param value defines the value to approximate
  9471. * @param max defines the maximum value to return
  9472. * @param mode defines how to define the closest value
  9473. * @returns closest exponent of two of the given value
  9474. */
  9475. Tools.GetExponentOfTwo = function (value, max, mode) {
  9476. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  9477. var pot;
  9478. switch (mode) {
  9479. case BABYLON.Engine.SCALEMODE_FLOOR:
  9480. pot = Tools.FloorPOT(value);
  9481. break;
  9482. case BABYLON.Engine.SCALEMODE_NEAREST:
  9483. pot = Tools.NearestPOT(value);
  9484. break;
  9485. case BABYLON.Engine.SCALEMODE_CEILING:
  9486. default:
  9487. pot = Tools.CeilingPOT(value);
  9488. break;
  9489. }
  9490. return Math.min(pot, max);
  9491. };
  9492. /**
  9493. * Extracts the filename from a path
  9494. * @param path defines the path to use
  9495. * @returns the filename
  9496. */
  9497. Tools.GetFilename = function (path) {
  9498. var index = path.lastIndexOf("/");
  9499. if (index < 0) {
  9500. return path;
  9501. }
  9502. return path.substring(index + 1);
  9503. };
  9504. /**
  9505. * Extracts the "folder" part of a path (everything before the filename).
  9506. * @param uri The URI to extract the info from
  9507. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  9508. * @returns The "folder" part of the path
  9509. */
  9510. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  9511. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  9512. var index = uri.lastIndexOf("/");
  9513. if (index < 0) {
  9514. if (returnUnchangedIfNoSlash) {
  9515. return uri;
  9516. }
  9517. return "";
  9518. }
  9519. return uri.substring(0, index + 1);
  9520. };
  9521. /**
  9522. * Extracts text content from a DOM element hierarchy
  9523. * @param element defines the root element
  9524. * @returns a string
  9525. */
  9526. Tools.GetDOMTextContent = function (element) {
  9527. var result = "";
  9528. var child = element.firstChild;
  9529. while (child) {
  9530. if (child.nodeType === 3) {
  9531. result += child.textContent;
  9532. }
  9533. child = child.nextSibling;
  9534. }
  9535. return result;
  9536. };
  9537. /**
  9538. * Convert an angle in radians to degrees
  9539. * @param angle defines the angle to convert
  9540. * @returns the angle in degrees
  9541. */
  9542. Tools.ToDegrees = function (angle) {
  9543. return angle * 180 / Math.PI;
  9544. };
  9545. /**
  9546. * Convert an angle in degrees to radians
  9547. * @param angle defines the angle to convert
  9548. * @returns the angle in radians
  9549. */
  9550. Tools.ToRadians = function (angle) {
  9551. return angle * Math.PI / 180;
  9552. };
  9553. /**
  9554. * Encode a buffer to a base64 string
  9555. * @param buffer defines the buffer to encode
  9556. * @returns the encoded string
  9557. */
  9558. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  9559. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  9560. var output = "";
  9561. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  9562. var i = 0;
  9563. var bytes = new Uint8Array(buffer);
  9564. while (i < bytes.length) {
  9565. chr1 = bytes[i++];
  9566. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  9567. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  9568. enc1 = chr1 >> 2;
  9569. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  9570. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  9571. enc4 = chr3 & 63;
  9572. if (isNaN(chr2)) {
  9573. enc3 = enc4 = 64;
  9574. }
  9575. else if (isNaN(chr3)) {
  9576. enc4 = 64;
  9577. }
  9578. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  9579. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  9580. }
  9581. return "data:image/png;base64," + output;
  9582. };
  9583. /**
  9584. * Extracts minimum and maximum values from a list of indexed positions
  9585. * @param positions defines the positions to use
  9586. * @param indices defines the indices to the positions
  9587. * @param indexStart defines the start index
  9588. * @param indexCount defines the end index
  9589. * @param bias defines bias value to add to the result
  9590. * @return minimum and maximum values
  9591. */
  9592. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  9593. if (bias === void 0) { bias = null; }
  9594. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9595. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9596. for (var index = indexStart; index < indexStart + indexCount; index++) {
  9597. var offset = indices[index] * 3;
  9598. var x = positions[offset];
  9599. var y = positions[offset + 1];
  9600. var z = positions[offset + 2];
  9601. minimum.minimizeInPlaceFromFloats(x, y, z);
  9602. maximum.maximizeInPlaceFromFloats(x, y, z);
  9603. }
  9604. if (bias) {
  9605. minimum.x -= minimum.x * bias.x + bias.y;
  9606. minimum.y -= minimum.y * bias.x + bias.y;
  9607. minimum.z -= minimum.z * bias.x + bias.y;
  9608. maximum.x += maximum.x * bias.x + bias.y;
  9609. maximum.y += maximum.y * bias.x + bias.y;
  9610. maximum.z += maximum.z * bias.x + bias.y;
  9611. }
  9612. return {
  9613. minimum: minimum,
  9614. maximum: maximum
  9615. };
  9616. };
  9617. /**
  9618. * Extracts minimum and maximum values from a list of positions
  9619. * @param positions defines the positions to use
  9620. * @param start defines the start index in the positions array
  9621. * @param count defines the number of positions to handle
  9622. * @param bias defines bias value to add to the result
  9623. * @param stride defines the stride size to use (distance between two positions in the positions array)
  9624. * @return minimum and maximum values
  9625. */
  9626. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  9627. if (bias === void 0) { bias = null; }
  9628. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9629. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9630. if (!stride) {
  9631. stride = 3;
  9632. }
  9633. for (var index = start, offset = start * stride; index < start + count; index++, offset += stride) {
  9634. var x = positions[offset];
  9635. var y = positions[offset + 1];
  9636. var z = positions[offset + 2];
  9637. minimum.minimizeInPlaceFromFloats(x, y, z);
  9638. maximum.maximizeInPlaceFromFloats(x, y, z);
  9639. }
  9640. if (bias) {
  9641. minimum.x -= minimum.x * bias.x + bias.y;
  9642. minimum.y -= minimum.y * bias.x + bias.y;
  9643. minimum.z -= minimum.z * bias.x + bias.y;
  9644. maximum.x += maximum.x * bias.x + bias.y;
  9645. maximum.y += maximum.y * bias.x + bias.y;
  9646. maximum.z += maximum.z * bias.x + bias.y;
  9647. }
  9648. return {
  9649. minimum: minimum,
  9650. maximum: maximum
  9651. };
  9652. };
  9653. /**
  9654. * Returns an array if obj is not an array
  9655. * @param obj defines the object to evaluate as an array
  9656. * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
  9657. * @returns either obj directly if obj is an array or a new array containing obj
  9658. */
  9659. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9660. if (allowsNullUndefined !== true && (obj === undefined || obj == null)) {
  9661. return null;
  9662. }
  9663. return Array.isArray(obj) ? obj : [obj];
  9664. };
  9665. /**
  9666. * Gets the pointer prefix to use
  9667. * @returns "pointer" if touch is enabled. Else returns "mouse"
  9668. */
  9669. Tools.GetPointerPrefix = function () {
  9670. var eventPrefix = "pointer";
  9671. // Check if pointer events are supported
  9672. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9673. eventPrefix = "mouse";
  9674. }
  9675. return eventPrefix;
  9676. };
  9677. /**
  9678. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  9679. * @param func - the function to be called
  9680. * @param requester - the object that will request the next frame. Falls back to window.
  9681. * @returns frame number
  9682. */
  9683. Tools.QueueNewFrame = function (func, requester) {
  9684. if (!Tools.IsWindowObjectExist()) {
  9685. return setTimeout(func, 16);
  9686. }
  9687. if (!requester) {
  9688. requester = window;
  9689. }
  9690. if (requester.requestAnimationFrame) {
  9691. return requester.requestAnimationFrame(func);
  9692. }
  9693. else if (requester.msRequestAnimationFrame) {
  9694. return requester.msRequestAnimationFrame(func);
  9695. }
  9696. else if (requester.webkitRequestAnimationFrame) {
  9697. return requester.webkitRequestAnimationFrame(func);
  9698. }
  9699. else if (requester.mozRequestAnimationFrame) {
  9700. return requester.mozRequestAnimationFrame(func);
  9701. }
  9702. else if (requester.oRequestAnimationFrame) {
  9703. return requester.oRequestAnimationFrame(func);
  9704. }
  9705. else {
  9706. return window.setTimeout(func, 16);
  9707. }
  9708. };
  9709. /**
  9710. * Ask the browser to promote the current element to fullscreen rendering mode
  9711. * @param element defines the DOM element to promote
  9712. */
  9713. Tools.RequestFullscreen = function (element) {
  9714. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9715. if (!requestFunction) {
  9716. return;
  9717. }
  9718. requestFunction.call(element);
  9719. };
  9720. /**
  9721. * Asks the browser to exit fullscreen mode
  9722. */
  9723. Tools.ExitFullscreen = function () {
  9724. if (document.exitFullscreen) {
  9725. document.exitFullscreen();
  9726. }
  9727. else if (document.mozCancelFullScreen) {
  9728. document.mozCancelFullScreen();
  9729. }
  9730. else if (document.webkitCancelFullScreen) {
  9731. document.webkitCancelFullScreen();
  9732. }
  9733. else if (document.msCancelFullScreen) {
  9734. document.msCancelFullScreen();
  9735. }
  9736. };
  9737. /**
  9738. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  9739. * @param url define the url we are trying
  9740. * @param element define the dom element where to configure the cors policy
  9741. */
  9742. Tools.SetCorsBehavior = function (url, element) {
  9743. if (url && url.indexOf("data:") === 0) {
  9744. return;
  9745. }
  9746. if (Tools.CorsBehavior) {
  9747. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9748. element.crossOrigin = Tools.CorsBehavior;
  9749. }
  9750. else {
  9751. var result = Tools.CorsBehavior(url);
  9752. if (result) {
  9753. element.crossOrigin = result;
  9754. }
  9755. }
  9756. }
  9757. };
  9758. // External files
  9759. /**
  9760. * Removes unwanted characters from an url
  9761. * @param url defines the url to clean
  9762. * @returns the cleaned url
  9763. */
  9764. Tools.CleanUrl = function (url) {
  9765. url = url.replace(/#/mg, "%23");
  9766. return url;
  9767. };
  9768. /**
  9769. * Loads an image as an HTMLImageElement.
  9770. * @param input url string, ArrayBuffer, or Blob to load
  9771. * @param onLoad callback called when the image successfully loads
  9772. * @param onError callback called when the image fails to load
  9773. * @param database database for caching
  9774. * @returns the HTMLImageElement of the loaded image
  9775. */
  9776. Tools.LoadImage = function (input, onLoad, onError, database) {
  9777. var url;
  9778. var usingObjectURL = false;
  9779. if (input instanceof ArrayBuffer) {
  9780. url = URL.createObjectURL(new Blob([input]));
  9781. usingObjectURL = true;
  9782. }
  9783. else if (input instanceof Blob) {
  9784. url = URL.createObjectURL(input);
  9785. usingObjectURL = true;
  9786. }
  9787. else {
  9788. url = Tools.CleanUrl(input);
  9789. url = Tools.PreprocessUrl(input);
  9790. }
  9791. var img = new Image();
  9792. Tools.SetCorsBehavior(url, img);
  9793. var loadHandler = function () {
  9794. if (usingObjectURL && img.src) {
  9795. URL.revokeObjectURL(img.src);
  9796. }
  9797. img.removeEventListener("load", loadHandler);
  9798. img.removeEventListener("error", errorHandler);
  9799. onLoad(img);
  9800. };
  9801. var errorHandler = function (err) {
  9802. if (usingObjectURL && img.src) {
  9803. URL.revokeObjectURL(img.src);
  9804. }
  9805. img.removeEventListener("load", loadHandler);
  9806. img.removeEventListener("error", errorHandler);
  9807. Tools.Error("Error while trying to load image: " + input);
  9808. if (onError) {
  9809. onError("Error while trying to load image: " + input, err);
  9810. }
  9811. };
  9812. img.addEventListener("load", loadHandler);
  9813. img.addEventListener("error", errorHandler);
  9814. var noIndexedDB = function () {
  9815. img.src = url;
  9816. };
  9817. var loadFromIndexedDB = function () {
  9818. if (database) {
  9819. database.loadImageFromDB(url, img);
  9820. }
  9821. };
  9822. //ANY database to do!
  9823. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9824. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9825. }
  9826. else {
  9827. if (url.indexOf("file:") !== -1) {
  9828. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9829. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9830. try {
  9831. var blobURL;
  9832. try {
  9833. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9834. }
  9835. catch (ex) {
  9836. // Chrome doesn't support oneTimeOnly parameter
  9837. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9838. }
  9839. img.src = blobURL;
  9840. usingObjectURL = true;
  9841. }
  9842. catch (e) {
  9843. img.src = "";
  9844. }
  9845. return img;
  9846. }
  9847. }
  9848. noIndexedDB();
  9849. }
  9850. return img;
  9851. };
  9852. /**
  9853. * Loads a file
  9854. * @param url url string, ArrayBuffer, or Blob to load
  9855. * @param onSuccess callback called when the file successfully loads
  9856. * @param onProgress callback called while file is loading (if the server supports this mode)
  9857. * @param database database for caching
  9858. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  9859. * @param onError callback called when the file fails to load
  9860. * @returns a file request object
  9861. */
  9862. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9863. url = Tools.CleanUrl(url);
  9864. url = Tools.PreprocessUrl(url);
  9865. // If file and file input are set
  9866. if (url.indexOf("file:") !== -1) {
  9867. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9868. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9869. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9870. }
  9871. }
  9872. var loadUrl = Tools.BaseUrl + url;
  9873. var aborted = false;
  9874. var fileRequest = {
  9875. onCompleteObservable: new BABYLON.Observable(),
  9876. abort: function () { return aborted = true; },
  9877. };
  9878. var requestFile = function () {
  9879. var request = new XMLHttpRequest();
  9880. var retryHandle = null;
  9881. fileRequest.abort = function () {
  9882. aborted = true;
  9883. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9884. request.abort();
  9885. }
  9886. if (retryHandle !== null) {
  9887. clearTimeout(retryHandle);
  9888. retryHandle = null;
  9889. }
  9890. };
  9891. var retryLoop = function (retryIndex) {
  9892. request.open('GET', loadUrl, true);
  9893. if (useArrayBuffer) {
  9894. request.responseType = "arraybuffer";
  9895. }
  9896. if (onProgress) {
  9897. request.addEventListener("progress", onProgress);
  9898. }
  9899. var onLoadEnd = function () {
  9900. request.removeEventListener("loadend", onLoadEnd);
  9901. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9902. fileRequest.onCompleteObservable.clear();
  9903. };
  9904. request.addEventListener("loadend", onLoadEnd);
  9905. var onReadyStateChange = function () {
  9906. if (aborted) {
  9907. return;
  9908. }
  9909. // In case of undefined state in some browsers.
  9910. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9911. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9912. request.removeEventListener("readystatechange", onReadyStateChange);
  9913. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9914. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9915. return;
  9916. }
  9917. var retryStrategy = Tools.DefaultRetryStrategy;
  9918. if (retryStrategy) {
  9919. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9920. if (waitTime !== -1) {
  9921. // Prevent the request from completing for retry.
  9922. request.removeEventListener("loadend", onLoadEnd);
  9923. request = new XMLHttpRequest();
  9924. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9925. return;
  9926. }
  9927. }
  9928. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9929. if (onError) {
  9930. onError(request, e);
  9931. }
  9932. else {
  9933. throw e;
  9934. }
  9935. }
  9936. };
  9937. request.addEventListener("readystatechange", onReadyStateChange);
  9938. request.send();
  9939. };
  9940. retryLoop(0);
  9941. };
  9942. // Caching all files
  9943. if (database && database.enableSceneOffline) {
  9944. var noIndexedDB_1 = function (request) {
  9945. if (request && request.status > 400) {
  9946. if (onError) {
  9947. onError(request);
  9948. }
  9949. }
  9950. else {
  9951. if (!aborted) {
  9952. requestFile();
  9953. }
  9954. }
  9955. };
  9956. var loadFromIndexedDB = function () {
  9957. // TODO: database needs to support aborting and should return a IFileRequest
  9958. if (aborted) {
  9959. return;
  9960. }
  9961. if (database) {
  9962. database.loadFileFromDB(url, function (data) {
  9963. if (!aborted) {
  9964. onSuccess(data);
  9965. }
  9966. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9967. }, onProgress ? function (event) {
  9968. if (!aborted) {
  9969. onProgress(event);
  9970. }
  9971. } : undefined, noIndexedDB_1, useArrayBuffer);
  9972. }
  9973. };
  9974. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9975. }
  9976. else {
  9977. requestFile();
  9978. }
  9979. return fileRequest;
  9980. };
  9981. /**
  9982. * Load a script (identified by an url). When the url returns, the
  9983. * content of this file is added into a new script element, attached to the DOM (body element)
  9984. * @param scriptUrl defines the url of the script to laod
  9985. * @param onSuccess defines the callback called when the script is loaded
  9986. * @param onError defines the callback to call if an error occurs
  9987. */
  9988. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9989. if (!Tools.IsWindowObjectExist()) {
  9990. return;
  9991. }
  9992. var head = document.getElementsByTagName('head')[0];
  9993. var script = document.createElement('script');
  9994. script.type = 'text/javascript';
  9995. script.src = scriptUrl;
  9996. script.onload = function () {
  9997. if (onSuccess) {
  9998. onSuccess();
  9999. }
  10000. };
  10001. script.onerror = function (e) {
  10002. if (onError) {
  10003. onError("Unable to load script '" + scriptUrl + "'", e);
  10004. }
  10005. };
  10006. head.appendChild(script);
  10007. };
  10008. /**
  10009. * Loads a file from a blob
  10010. * @param fileToLoad defines the blob to use
  10011. * @param callback defines the callback to call when data is loaded
  10012. * @param progressCallback defines the callback to call during loading process
  10013. * @returns a file request object
  10014. */
  10015. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  10016. var reader = new FileReader();
  10017. var request = {
  10018. onCompleteObservable: new BABYLON.Observable(),
  10019. abort: function () { return reader.abort(); },
  10020. };
  10021. reader.onloadend = function (e) {
  10022. request.onCompleteObservable.notifyObservers(request);
  10023. };
  10024. reader.onload = function (e) {
  10025. //target doesn't have result from ts 1.3
  10026. callback(e.target['result']);
  10027. };
  10028. reader.onprogress = progressCallback;
  10029. reader.readAsDataURL(fileToLoad);
  10030. return request;
  10031. };
  10032. /**
  10033. * Loads a file
  10034. * @param fileToLoad defines the file to load
  10035. * @param callback defines the callback to call when data is loaded
  10036. * @param progressCallBack defines the callback to call during loading process
  10037. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  10038. * @returns a file request object
  10039. */
  10040. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  10041. var reader = new FileReader();
  10042. var request = {
  10043. onCompleteObservable: new BABYLON.Observable(),
  10044. abort: function () { return reader.abort(); },
  10045. };
  10046. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  10047. reader.onerror = function (e) {
  10048. Tools.Log("Error while reading file: " + fileToLoad.name);
  10049. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  10050. };
  10051. reader.onload = function (e) {
  10052. //target doesn't have result from ts 1.3
  10053. callback(e.target['result']);
  10054. };
  10055. if (progressCallBack) {
  10056. reader.onprogress = progressCallBack;
  10057. }
  10058. if (!useArrayBuffer) {
  10059. // Asynchronous read
  10060. reader.readAsText(fileToLoad);
  10061. }
  10062. else {
  10063. reader.readAsArrayBuffer(fileToLoad);
  10064. }
  10065. return request;
  10066. };
  10067. /**
  10068. * Creates a data url from a given string content
  10069. * @param content defines the content to convert
  10070. * @returns the new data url link
  10071. */
  10072. Tools.FileAsURL = function (content) {
  10073. var fileBlob = new Blob([content]);
  10074. var url = window.URL || window.webkitURL;
  10075. var link = url.createObjectURL(fileBlob);
  10076. return link;
  10077. };
  10078. /**
  10079. * Format the given number to a specific decimal format
  10080. * @param value defines the number to format
  10081. * @param decimals defines the number of decimals to use
  10082. * @returns the formatted string
  10083. */
  10084. Tools.Format = function (value, decimals) {
  10085. if (decimals === void 0) { decimals = 2; }
  10086. return value.toFixed(decimals);
  10087. };
  10088. /**
  10089. * Checks if a given vector is inside a specific range
  10090. * @param v defines the vector to test
  10091. * @param min defines the minimum range
  10092. * @param max defines the maximum range
  10093. */
  10094. Tools.CheckExtends = function (v, min, max) {
  10095. if (v.x < min.x) {
  10096. min.x = v.x;
  10097. }
  10098. if (v.y < min.y) {
  10099. min.y = v.y;
  10100. }
  10101. if (v.z < min.z) {
  10102. min.z = v.z;
  10103. }
  10104. if (v.x > max.x) {
  10105. max.x = v.x;
  10106. }
  10107. if (v.y > max.y) {
  10108. max.y = v.y;
  10109. }
  10110. if (v.z > max.z) {
  10111. max.z = v.z;
  10112. }
  10113. };
  10114. /**
  10115. * Tries to copy an object by duplicating every property
  10116. * @param source defines the source object
  10117. * @param destination defines the target object
  10118. * @param doNotCopyList defines a list of properties to avoid
  10119. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  10120. */
  10121. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  10122. for (var prop in source) {
  10123. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  10124. continue;
  10125. }
  10126. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  10127. continue;
  10128. }
  10129. var sourceValue = source[prop];
  10130. var typeOfSourceValue = typeof sourceValue;
  10131. if (typeOfSourceValue === "function") {
  10132. continue;
  10133. }
  10134. try {
  10135. if (typeOfSourceValue === "object") {
  10136. if (sourceValue instanceof Array) {
  10137. destination[prop] = [];
  10138. if (sourceValue.length > 0) {
  10139. if (typeof sourceValue[0] == "object") {
  10140. for (var index = 0; index < sourceValue.length; index++) {
  10141. var clonedValue = cloneValue(sourceValue[index], destination);
  10142. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  10143. destination[prop].push(clonedValue);
  10144. }
  10145. }
  10146. }
  10147. else {
  10148. destination[prop] = sourceValue.slice(0);
  10149. }
  10150. }
  10151. }
  10152. else {
  10153. destination[prop] = cloneValue(sourceValue, destination);
  10154. }
  10155. }
  10156. else {
  10157. destination[prop] = sourceValue;
  10158. }
  10159. }
  10160. catch (e) {
  10161. // Just ignore error (it could be because of a read-only property)
  10162. }
  10163. }
  10164. };
  10165. /**
  10166. * Gets a boolean indicating if the given object has no own property
  10167. * @param obj defines the object to test
  10168. * @returns true if object has no own property
  10169. */
  10170. Tools.IsEmpty = function (obj) {
  10171. for (var i in obj) {
  10172. if (obj.hasOwnProperty(i)) {
  10173. return false;
  10174. }
  10175. }
  10176. return true;
  10177. };
  10178. /**
  10179. * Function used to register events at window level
  10180. * @param events defines the events to register
  10181. */
  10182. Tools.RegisterTopRootEvents = function (events) {
  10183. for (var index = 0; index < events.length; index++) {
  10184. var event = events[index];
  10185. window.addEventListener(event.name, event.handler, false);
  10186. try {
  10187. if (window.parent) {
  10188. window.parent.addEventListener(event.name, event.handler, false);
  10189. }
  10190. }
  10191. catch (e) {
  10192. // Silently fails...
  10193. }
  10194. }
  10195. };
  10196. /**
  10197. * Function used to unregister events from window level
  10198. * @param events defines the events to unregister
  10199. */
  10200. Tools.UnregisterTopRootEvents = function (events) {
  10201. for (var index = 0; index < events.length; index++) {
  10202. var event = events[index];
  10203. window.removeEventListener(event.name, event.handler);
  10204. try {
  10205. if (window.parent) {
  10206. window.parent.removeEventListener(event.name, event.handler);
  10207. }
  10208. }
  10209. catch (e) {
  10210. // Silently fails...
  10211. }
  10212. }
  10213. };
  10214. /**
  10215. * Dumps the current bound framebuffer
  10216. * @param width defines the rendering width
  10217. * @param height defines the rendering height
  10218. * @param engine defines the hosting engine
  10219. * @param successCallback defines the callback triggered once the data are available
  10220. * @param mimeType defines the mime type of the result
  10221. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  10222. */
  10223. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  10224. if (mimeType === void 0) { mimeType = "image/png"; }
  10225. // Read the contents of the framebuffer
  10226. var numberOfChannelsByLine = width * 4;
  10227. var halfHeight = height / 2;
  10228. //Reading datas from WebGL
  10229. var data = engine.readPixels(0, 0, width, height);
  10230. //To flip image on Y axis.
  10231. for (var i = 0; i < halfHeight; i++) {
  10232. for (var j = 0; j < numberOfChannelsByLine; j++) {
  10233. var currentCell = j + i * numberOfChannelsByLine;
  10234. var targetLine = height - i - 1;
  10235. var targetCell = j + targetLine * numberOfChannelsByLine;
  10236. var temp = data[currentCell];
  10237. data[currentCell] = data[targetCell];
  10238. data[targetCell] = temp;
  10239. }
  10240. }
  10241. // Create a 2D canvas to store the result
  10242. if (!screenshotCanvas) {
  10243. screenshotCanvas = document.createElement('canvas');
  10244. }
  10245. screenshotCanvas.width = width;
  10246. screenshotCanvas.height = height;
  10247. var context = screenshotCanvas.getContext('2d');
  10248. if (context) {
  10249. // Copy the pixels to a 2D canvas
  10250. var imageData = context.createImageData(width, height);
  10251. var castData = (imageData.data);
  10252. castData.set(data);
  10253. context.putImageData(imageData, 0, 0);
  10254. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  10255. }
  10256. };
  10257. /**
  10258. * Converts the canvas data to blob.
  10259. * This acts as a polyfill for browsers not supporting the to blob function.
  10260. * @param canvas Defines the canvas to extract the data from
  10261. * @param successCallback Defines the callback triggered once the data are available
  10262. * @param mimeType Defines the mime type of the result
  10263. */
  10264. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  10265. if (mimeType === void 0) { mimeType = "image/png"; }
  10266. // We need HTMLCanvasElement.toBlob for HD screenshots
  10267. if (!canvas.toBlob) {
  10268. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  10269. canvas.toBlob = function (callback, type, quality) {
  10270. var _this = this;
  10271. setTimeout(function () {
  10272. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  10273. for (var i = 0; i < len; i++) {
  10274. arr[i] = binStr.charCodeAt(i);
  10275. }
  10276. callback(new Blob([arr]));
  10277. });
  10278. };
  10279. }
  10280. canvas.toBlob(function (blob) {
  10281. successCallback(blob);
  10282. }, mimeType);
  10283. };
  10284. /**
  10285. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  10286. * @param successCallback defines the callback triggered once the data are available
  10287. * @param mimeType defines the mime type of the result
  10288. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  10289. */
  10290. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  10291. if (mimeType === void 0) { mimeType = "image/png"; }
  10292. if (successCallback) {
  10293. var base64Image = screenshotCanvas.toDataURL(mimeType);
  10294. successCallback(base64Image);
  10295. }
  10296. else {
  10297. this.ToBlob(screenshotCanvas, function (blob) {
  10298. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  10299. if (("download" in document.createElement("a"))) {
  10300. if (!fileName) {
  10301. var date = new Date();
  10302. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  10303. fileName = "screenshot_" + stringDate + ".png";
  10304. }
  10305. Tools.Download(blob, fileName);
  10306. }
  10307. else {
  10308. var url = URL.createObjectURL(blob);
  10309. var newWindow = window.open("");
  10310. if (!newWindow) {
  10311. return;
  10312. }
  10313. var img = newWindow.document.createElement("img");
  10314. img.onload = function () {
  10315. // no longer need to read the blob so it's revoked
  10316. URL.revokeObjectURL(url);
  10317. };
  10318. img.src = url;
  10319. newWindow.document.body.appendChild(img);
  10320. }
  10321. }, mimeType);
  10322. }
  10323. };
  10324. /**
  10325. * Downloads a blob in the browser
  10326. * @param blob defines the blob to download
  10327. * @param fileName defines the name of the downloaded file
  10328. */
  10329. Tools.Download = function (blob, fileName) {
  10330. if (navigator && navigator.msSaveBlob) {
  10331. navigator.msSaveBlob(blob, fileName);
  10332. return;
  10333. }
  10334. var url = window.URL.createObjectURL(blob);
  10335. var a = document.createElement("a");
  10336. document.body.appendChild(a);
  10337. a.style.display = "none";
  10338. a.href = url;
  10339. a.download = fileName;
  10340. a.addEventListener("click", function () {
  10341. if (a.parentElement) {
  10342. a.parentElement.removeChild(a);
  10343. }
  10344. });
  10345. a.click();
  10346. window.URL.revokeObjectURL(url);
  10347. };
  10348. /**
  10349. * Captures a screenshot of the current rendering
  10350. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10351. * @param engine defines the rendering engine
  10352. * @param camera defines the source camera
  10353. * @param size This parameter can be set to a single number or to an object with the
  10354. * following (optional) properties: precision, width, height. If a single number is passed,
  10355. * it will be used for both width and height. If an object is passed, the screenshot size
  10356. * will be derived from the parameters. The precision property is a multiplier allowing
  10357. * rendering at a higher or lower resolution
  10358. * @param successCallback defines the callback receives a single parameter which contains the
  10359. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10360. * src parameter of an <img> to display it
  10361. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  10362. * Check your browser for supported MIME types
  10363. */
  10364. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  10365. if (mimeType === void 0) { mimeType = "image/png"; }
  10366. var width;
  10367. var height;
  10368. // If a precision value is specified
  10369. if (size.precision) {
  10370. width = Math.round(engine.getRenderWidth() * size.precision);
  10371. height = Math.round(width / engine.getAspectRatio(camera));
  10372. }
  10373. else if (size.width && size.height) {
  10374. width = size.width;
  10375. height = size.height;
  10376. }
  10377. //If passing only width, computing height to keep display canvas ratio.
  10378. else if (size.width && !size.height) {
  10379. width = size.width;
  10380. height = Math.round(width / engine.getAspectRatio(camera));
  10381. }
  10382. //If passing only height, computing width to keep display canvas ratio.
  10383. else if (size.height && !size.width) {
  10384. height = size.height;
  10385. width = Math.round(height * engine.getAspectRatio(camera));
  10386. }
  10387. //Assuming here that "size" parameter is a number
  10388. else if (!isNaN(size)) {
  10389. height = size;
  10390. width = size;
  10391. }
  10392. else {
  10393. Tools.Error("Invalid 'size' parameter !");
  10394. return;
  10395. }
  10396. if (!screenshotCanvas) {
  10397. screenshotCanvas = document.createElement('canvas');
  10398. }
  10399. screenshotCanvas.width = width;
  10400. screenshotCanvas.height = height;
  10401. var renderContext = screenshotCanvas.getContext("2d");
  10402. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  10403. var newWidth = width;
  10404. var newHeight = newWidth / ratio;
  10405. if (newHeight > height) {
  10406. newHeight = height;
  10407. newWidth = newHeight * ratio;
  10408. }
  10409. var offsetX = Math.max(0, width - newWidth) / 2;
  10410. var offsetY = Math.max(0, height - newHeight) / 2;
  10411. var renderingCanvas = engine.getRenderingCanvas();
  10412. if (renderContext && renderingCanvas) {
  10413. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  10414. }
  10415. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  10416. };
  10417. /**
  10418. * Generates an image screenshot from the specified camera.
  10419. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10420. * @param engine The engine to use for rendering
  10421. * @param camera The camera to use for rendering
  10422. * @param size This parameter can be set to a single number or to an object with the
  10423. * following (optional) properties: precision, width, height. If a single number is passed,
  10424. * it will be used for both width and height. If an object is passed, the screenshot size
  10425. * will be derived from the parameters. The precision property is a multiplier allowing
  10426. * rendering at a higher or lower resolution
  10427. * @param successCallback The callback receives a single parameter which contains the
  10428. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10429. * src parameter of an <img> to display it
  10430. * @param mimeType The MIME type of the screenshot image (default: image/png).
  10431. * Check your browser for supported MIME types
  10432. * @param samples Texture samples (default: 1)
  10433. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  10434. * @param fileName A name for for the downloaded file.
  10435. */
  10436. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  10437. if (mimeType === void 0) { mimeType = "image/png"; }
  10438. if (samples === void 0) { samples = 1; }
  10439. if (antialiasing === void 0) { antialiasing = false; }
  10440. var width;
  10441. var height;
  10442. //If a precision value is specified
  10443. if (size.precision) {
  10444. width = Math.round(engine.getRenderWidth() * size.precision);
  10445. height = Math.round(width / engine.getAspectRatio(camera));
  10446. size = { width: width, height: height };
  10447. }
  10448. else if (size.width && size.height) {
  10449. width = size.width;
  10450. height = size.height;
  10451. }
  10452. //If passing only width, computing height to keep display canvas ratio.
  10453. else if (size.width && !size.height) {
  10454. width = size.width;
  10455. height = Math.round(width / engine.getAspectRatio(camera));
  10456. size = { width: width, height: height };
  10457. }
  10458. //If passing only height, computing width to keep display canvas ratio.
  10459. else if (size.height && !size.width) {
  10460. height = size.height;
  10461. width = Math.round(height * engine.getAspectRatio(camera));
  10462. size = { width: width, height: height };
  10463. }
  10464. //Assuming here that "size" parameter is a number
  10465. else if (!isNaN(size)) {
  10466. height = size;
  10467. width = size;
  10468. }
  10469. else {
  10470. Tools.Error("Invalid 'size' parameter !");
  10471. return;
  10472. }
  10473. var scene = camera.getScene();
  10474. var previousCamera = null;
  10475. if (scene.activeCamera !== camera) {
  10476. previousCamera = scene.activeCamera;
  10477. scene.activeCamera = camera;
  10478. }
  10479. // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  10480. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10481. texture.renderList = null;
  10482. texture.samples = samples;
  10483. if (antialiasing) {
  10484. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  10485. }
  10486. texture.onAfterRenderObservable.add(function () {
  10487. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  10488. });
  10489. scene.incrementRenderId();
  10490. scene.resetCachedMaterial();
  10491. texture.render(true);
  10492. texture.dispose();
  10493. if (previousCamera) {
  10494. scene.activeCamera = previousCamera;
  10495. }
  10496. camera.getProjectionMatrix(true); // Force cache refresh;
  10497. };
  10498. /**
  10499. * Validates if xhr data is correct
  10500. * @param xhr defines the request to validate
  10501. * @param dataType defines the expected data type
  10502. * @returns true if data is correct
  10503. */
  10504. Tools.ValidateXHRData = function (xhr, dataType) {
  10505. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  10506. if (dataType === void 0) { dataType = 7; }
  10507. try {
  10508. if (dataType & 1) {
  10509. if (xhr.responseText && xhr.responseText.length > 0) {
  10510. return true;
  10511. }
  10512. else if (dataType === 1) {
  10513. return false;
  10514. }
  10515. }
  10516. if (dataType & 2) {
  10517. // Check header width and height since there is no "TGA" magic number
  10518. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  10519. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  10520. return true;
  10521. }
  10522. else if (dataType === 2) {
  10523. return false;
  10524. }
  10525. }
  10526. if (dataType & 4) {
  10527. // Check for the "DDS" magic number
  10528. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  10529. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  10530. return true;
  10531. }
  10532. else {
  10533. return false;
  10534. }
  10535. }
  10536. }
  10537. catch (e) {
  10538. // Global protection
  10539. }
  10540. return false;
  10541. };
  10542. /**
  10543. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  10544. * Be aware Math.random() could cause collisions, but:
  10545. * "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"
  10546. * @returns a pseudo random id
  10547. */
  10548. Tools.RandomId = function () {
  10549. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  10550. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  10551. return v.toString(16);
  10552. });
  10553. };
  10554. /**
  10555. * Test if the given uri is a base64 string
  10556. * @param uri The uri to test
  10557. * @return True if the uri is a base64 string or false otherwise
  10558. */
  10559. Tools.IsBase64 = function (uri) {
  10560. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  10561. };
  10562. /**
  10563. * Decode the given base64 uri.
  10564. * @param uri The uri to decode
  10565. * @return The decoded base64 data.
  10566. */
  10567. Tools.DecodeBase64 = function (uri) {
  10568. var decodedString = atob(uri.split(",")[1]);
  10569. var bufferLength = decodedString.length;
  10570. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  10571. for (var i = 0; i < bufferLength; i++) {
  10572. bufferView[i] = decodedString.charCodeAt(i);
  10573. }
  10574. return bufferView.buffer;
  10575. };
  10576. Tools._AddLogEntry = function (entry) {
  10577. Tools._LogCache = entry + Tools._LogCache;
  10578. if (Tools.OnNewCacheEntry) {
  10579. Tools.OnNewCacheEntry(entry);
  10580. }
  10581. };
  10582. Tools._FormatMessage = function (message) {
  10583. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  10584. var date = new Date();
  10585. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  10586. };
  10587. Tools._LogDisabled = function (message) {
  10588. // nothing to do
  10589. };
  10590. Tools._LogEnabled = function (message) {
  10591. var formattedMessage = Tools._FormatMessage(message);
  10592. console.log("BJS - " + formattedMessage);
  10593. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  10594. Tools._AddLogEntry(entry);
  10595. };
  10596. Tools._WarnDisabled = function (message) {
  10597. // nothing to do
  10598. };
  10599. Tools._WarnEnabled = function (message) {
  10600. var formattedMessage = Tools._FormatMessage(message);
  10601. console.warn("BJS - " + formattedMessage);
  10602. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  10603. Tools._AddLogEntry(entry);
  10604. };
  10605. Tools._ErrorDisabled = function (message) {
  10606. // nothing to do
  10607. };
  10608. Tools._ErrorEnabled = function (message) {
  10609. Tools.errorsCount++;
  10610. var formattedMessage = Tools._FormatMessage(message);
  10611. console.error("BJS - " + formattedMessage);
  10612. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  10613. Tools._AddLogEntry(entry);
  10614. };
  10615. Object.defineProperty(Tools, "LogCache", {
  10616. /**
  10617. * Gets current log cache (list of logs)
  10618. */
  10619. get: function () {
  10620. return Tools._LogCache;
  10621. },
  10622. enumerable: true,
  10623. configurable: true
  10624. });
  10625. /**
  10626. * Clears the log cache
  10627. */
  10628. Tools.ClearLogCache = function () {
  10629. Tools._LogCache = "";
  10630. Tools.errorsCount = 0;
  10631. };
  10632. Object.defineProperty(Tools, "LogLevels", {
  10633. /**
  10634. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  10635. */
  10636. set: function (level) {
  10637. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  10638. Tools.Log = Tools._LogEnabled;
  10639. }
  10640. else {
  10641. Tools.Log = Tools._LogDisabled;
  10642. }
  10643. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  10644. Tools.Warn = Tools._WarnEnabled;
  10645. }
  10646. else {
  10647. Tools.Warn = Tools._WarnDisabled;
  10648. }
  10649. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  10650. Tools.Error = Tools._ErrorEnabled;
  10651. }
  10652. else {
  10653. Tools.Error = Tools._ErrorDisabled;
  10654. }
  10655. },
  10656. enumerable: true,
  10657. configurable: true
  10658. });
  10659. /**
  10660. * Checks if the loaded document was accessed via `file:`-Protocol.
  10661. * @returns boolean
  10662. */
  10663. Tools.IsFileURL = function () {
  10664. return location.protocol === "file:";
  10665. };
  10666. /**
  10667. * Checks if the window object exists
  10668. * @returns true if the window object exists
  10669. */
  10670. Tools.IsWindowObjectExist = function () {
  10671. return (typeof window) !== "undefined";
  10672. };
  10673. Object.defineProperty(Tools, "PerformanceLogLevel", {
  10674. /**
  10675. * Sets the current performance log level
  10676. */
  10677. set: function (level) {
  10678. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  10679. Tools.StartPerformanceCounter = Tools._StartUserMark;
  10680. Tools.EndPerformanceCounter = Tools._EndUserMark;
  10681. return;
  10682. }
  10683. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  10684. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  10685. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  10686. return;
  10687. }
  10688. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10689. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10690. },
  10691. enumerable: true,
  10692. configurable: true
  10693. });
  10694. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  10695. };
  10696. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  10697. };
  10698. Tools._StartUserMark = function (counterName, condition) {
  10699. if (condition === void 0) { condition = true; }
  10700. if (!Tools._performance) {
  10701. if (!Tools.IsWindowObjectExist()) {
  10702. return;
  10703. }
  10704. Tools._performance = window.performance;
  10705. }
  10706. if (!condition || !Tools._performance.mark) {
  10707. return;
  10708. }
  10709. Tools._performance.mark(counterName + "-Begin");
  10710. };
  10711. Tools._EndUserMark = function (counterName, condition) {
  10712. if (condition === void 0) { condition = true; }
  10713. if (!condition || !Tools._performance.mark) {
  10714. return;
  10715. }
  10716. Tools._performance.mark(counterName + "-End");
  10717. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  10718. };
  10719. Tools._StartPerformanceConsole = function (counterName, condition) {
  10720. if (condition === void 0) { condition = true; }
  10721. if (!condition) {
  10722. return;
  10723. }
  10724. Tools._StartUserMark(counterName, condition);
  10725. if (console.time) {
  10726. console.time(counterName);
  10727. }
  10728. };
  10729. Tools._EndPerformanceConsole = function (counterName, condition) {
  10730. if (condition === void 0) { condition = true; }
  10731. if (!condition) {
  10732. return;
  10733. }
  10734. Tools._EndUserMark(counterName, condition);
  10735. if (console.time) {
  10736. console.timeEnd(counterName);
  10737. }
  10738. };
  10739. Object.defineProperty(Tools, "Now", {
  10740. /**
  10741. * Gets either window.performance.now() if supported or Date.now() else
  10742. */
  10743. get: function () {
  10744. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10745. return window.performance.now();
  10746. }
  10747. return Date.now();
  10748. },
  10749. enumerable: true,
  10750. configurable: true
  10751. });
  10752. /**
  10753. * This method will return the name of the class used to create the instance of the given object.
  10754. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10755. * @param object the object to get the class name from
  10756. * @param isType defines if the object is actually a type
  10757. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  10758. */
  10759. Tools.GetClassName = function (object, isType) {
  10760. if (isType === void 0) { isType = false; }
  10761. var name = null;
  10762. if (!isType && object.getClassName) {
  10763. name = object.getClassName();
  10764. }
  10765. else {
  10766. if (object instanceof Object) {
  10767. var classObj = isType ? object : Object.getPrototypeOf(object);
  10768. name = classObj.constructor["__bjsclassName__"];
  10769. }
  10770. if (!name) {
  10771. name = typeof object;
  10772. }
  10773. }
  10774. return name;
  10775. };
  10776. /**
  10777. * Gets the first element of an array satisfying a given predicate
  10778. * @param array defines the array to browse
  10779. * @param predicate defines the predicate to use
  10780. * @returns null if not found or the element
  10781. */
  10782. Tools.First = function (array, predicate) {
  10783. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10784. var el = array_1[_i];
  10785. if (predicate(el)) {
  10786. return el;
  10787. }
  10788. }
  10789. return null;
  10790. };
  10791. /**
  10792. * This method will return the name of the full name of the class, including its owning module (if any).
  10793. * 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).
  10794. * @param object the object to get the class name from
  10795. * @param isType defines if the object is actually a type
  10796. * @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.
  10797. * @ignorenaming
  10798. */
  10799. Tools.getFullClassName = function (object, isType) {
  10800. if (isType === void 0) { isType = false; }
  10801. var className = null;
  10802. var moduleName = null;
  10803. if (!isType && object.getClassName) {
  10804. className = object.getClassName();
  10805. }
  10806. else {
  10807. if (object instanceof Object) {
  10808. var classObj = isType ? object : Object.getPrototypeOf(object);
  10809. className = classObj.constructor["__bjsclassName__"];
  10810. moduleName = classObj.constructor["__bjsmoduleName__"];
  10811. }
  10812. if (!className) {
  10813. className = typeof object;
  10814. }
  10815. }
  10816. if (!className) {
  10817. return null;
  10818. }
  10819. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10820. };
  10821. /**
  10822. * Returns a promise that resolves after the given amount of time.
  10823. * @param delay Number of milliseconds to delay
  10824. * @returns Promise that resolves after the given amount of time
  10825. */
  10826. Tools.DelayAsync = function (delay) {
  10827. return new Promise(function (resolve) {
  10828. setTimeout(function () {
  10829. resolve();
  10830. }, delay);
  10831. });
  10832. };
  10833. /**
  10834. * Gets the current gradient from an array of IValueGradient
  10835. * @param ratio defines the current ratio to get
  10836. * @param gradients defines the array of IValueGradient
  10837. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10838. */
  10839. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10840. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10841. var currentGradient = gradients[gradientIndex];
  10842. var nextGradient = gradients[gradientIndex + 1];
  10843. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10844. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10845. updateFunc(currentGradient, nextGradient, scale);
  10846. return;
  10847. }
  10848. }
  10849. // Use last index if over
  10850. var lastIndex = gradients.length - 1;
  10851. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10852. };
  10853. /**
  10854. * Gets or sets the base URL to use to load assets
  10855. */
  10856. Tools.BaseUrl = "";
  10857. /**
  10858. * Gets or sets the retry strategy to apply when an error happens while loading an asset
  10859. */
  10860. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10861. /**
  10862. * Default behaviour for cors in the application.
  10863. * It can be a string if the expected behavior is identical in the entire app.
  10864. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10865. */
  10866. Tools.CorsBehavior = "anonymous";
  10867. /**
  10868. * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
  10869. * @ignorenaming
  10870. */
  10871. Tools.UseFallbackTexture = true;
  10872. /**
  10873. * Use this object to register external classes like custom textures or material
  10874. * to allow the laoders to instantiate them
  10875. */
  10876. Tools.RegisteredExternalClasses = {};
  10877. /**
  10878. * Texture content used if a texture cannot loaded
  10879. * @ignorenaming
  10880. */
  10881. 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";
  10882. Tools._tmpFloatArray = new Float32Array(1);
  10883. /**
  10884. * Gets or sets a function used to pre-process url before using them to load assets
  10885. */
  10886. Tools.PreprocessUrl = function (url) {
  10887. return url;
  10888. };
  10889. // Logs
  10890. /**
  10891. * No log
  10892. */
  10893. Tools.NoneLogLevel = 0;
  10894. /**
  10895. * Only message logs
  10896. */
  10897. Tools.MessageLogLevel = 1;
  10898. /**
  10899. * Only warning logs
  10900. */
  10901. Tools.WarningLogLevel = 2;
  10902. /**
  10903. * Only error logs
  10904. */
  10905. Tools.ErrorLogLevel = 4;
  10906. /**
  10907. * All logs
  10908. */
  10909. Tools.AllLogLevel = 7;
  10910. Tools._LogCache = "";
  10911. /**
  10912. * Gets a value indicating the number of loading errors
  10913. * @ignorenaming
  10914. */
  10915. Tools.errorsCount = 0;
  10916. /**
  10917. * Log a message to the console
  10918. */
  10919. Tools.Log = Tools._LogEnabled;
  10920. /**
  10921. * Write a warning message to the console
  10922. */
  10923. Tools.Warn = Tools._WarnEnabled;
  10924. /**
  10925. * Write an error message to the console
  10926. */
  10927. Tools.Error = Tools._ErrorEnabled;
  10928. // Performances
  10929. /**
  10930. * No performance log
  10931. */
  10932. Tools.PerformanceNoneLogLevel = 0;
  10933. /**
  10934. * Use user marks to log performance
  10935. */
  10936. Tools.PerformanceUserMarkLogLevel = 1;
  10937. /**
  10938. * Log performance to the console
  10939. */
  10940. Tools.PerformanceConsoleLogLevel = 2;
  10941. /**
  10942. * Starts a performance counter
  10943. */
  10944. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10945. /**
  10946. * Ends a specific performance coutner
  10947. */
  10948. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10949. return Tools;
  10950. }());
  10951. BABYLON.Tools = Tools;
  10952. /**
  10953. * This class is used to track a performance counter which is number based.
  10954. * The user has access to many properties which give statistics of different nature.
  10955. *
  10956. * The implementer can track two kinds of Performance Counter: time and count.
  10957. * 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.
  10958. * 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.
  10959. */
  10960. var PerfCounter = /** @class */ (function () {
  10961. /**
  10962. * Creates a new counter
  10963. */
  10964. function PerfCounter() {
  10965. this._startMonitoringTime = 0;
  10966. this._min = 0;
  10967. this._max = 0;
  10968. this._average = 0;
  10969. this._lastSecAverage = 0;
  10970. this._current = 0;
  10971. this._totalValueCount = 0;
  10972. this._totalAccumulated = 0;
  10973. this._lastSecAccumulated = 0;
  10974. this._lastSecTime = 0;
  10975. this._lastSecValueCount = 0;
  10976. }
  10977. Object.defineProperty(PerfCounter.prototype, "min", {
  10978. /**
  10979. * Returns the smallest value ever
  10980. */
  10981. get: function () {
  10982. return this._min;
  10983. },
  10984. enumerable: true,
  10985. configurable: true
  10986. });
  10987. Object.defineProperty(PerfCounter.prototype, "max", {
  10988. /**
  10989. * Returns the biggest value ever
  10990. */
  10991. get: function () {
  10992. return this._max;
  10993. },
  10994. enumerable: true,
  10995. configurable: true
  10996. });
  10997. Object.defineProperty(PerfCounter.prototype, "average", {
  10998. /**
  10999. * Returns the average value since the performance counter is running
  11000. */
  11001. get: function () {
  11002. return this._average;
  11003. },
  11004. enumerable: true,
  11005. configurable: true
  11006. });
  11007. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  11008. /**
  11009. * Returns the average value of the last second the counter was monitored
  11010. */
  11011. get: function () {
  11012. return this._lastSecAverage;
  11013. },
  11014. enumerable: true,
  11015. configurable: true
  11016. });
  11017. Object.defineProperty(PerfCounter.prototype, "current", {
  11018. /**
  11019. * Returns the current value
  11020. */
  11021. get: function () {
  11022. return this._current;
  11023. },
  11024. enumerable: true,
  11025. configurable: true
  11026. });
  11027. Object.defineProperty(PerfCounter.prototype, "total", {
  11028. /**
  11029. * Gets the accumulated total
  11030. */
  11031. get: function () {
  11032. return this._totalAccumulated;
  11033. },
  11034. enumerable: true,
  11035. configurable: true
  11036. });
  11037. Object.defineProperty(PerfCounter.prototype, "count", {
  11038. /**
  11039. * Gets the total value count
  11040. */
  11041. get: function () {
  11042. return this._totalValueCount;
  11043. },
  11044. enumerable: true,
  11045. configurable: true
  11046. });
  11047. /**
  11048. * Call this method to start monitoring a new frame.
  11049. * 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.
  11050. */
  11051. PerfCounter.prototype.fetchNewFrame = function () {
  11052. this._totalValueCount++;
  11053. this._current = 0;
  11054. this._lastSecValueCount++;
  11055. };
  11056. /**
  11057. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  11058. * @param newCount the count value to add to the monitored count
  11059. * @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.
  11060. */
  11061. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  11062. if (!PerfCounter.Enabled) {
  11063. return;
  11064. }
  11065. this._current += newCount;
  11066. if (fetchResult) {
  11067. this._fetchResult();
  11068. }
  11069. };
  11070. /**
  11071. * Start monitoring this performance counter
  11072. */
  11073. PerfCounter.prototype.beginMonitoring = function () {
  11074. if (!PerfCounter.Enabled) {
  11075. return;
  11076. }
  11077. this._startMonitoringTime = Tools.Now;
  11078. };
  11079. /**
  11080. * Compute the time lapsed since the previous beginMonitoring() call.
  11081. * @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
  11082. */
  11083. PerfCounter.prototype.endMonitoring = function (newFrame) {
  11084. if (newFrame === void 0) { newFrame = true; }
  11085. if (!PerfCounter.Enabled) {
  11086. return;
  11087. }
  11088. if (newFrame) {
  11089. this.fetchNewFrame();
  11090. }
  11091. var currentTime = Tools.Now;
  11092. this._current = currentTime - this._startMonitoringTime;
  11093. if (newFrame) {
  11094. this._fetchResult();
  11095. }
  11096. };
  11097. PerfCounter.prototype._fetchResult = function () {
  11098. this._totalAccumulated += this._current;
  11099. this._lastSecAccumulated += this._current;
  11100. // Min/Max update
  11101. this._min = Math.min(this._min, this._current);
  11102. this._max = Math.max(this._max, this._current);
  11103. this._average = this._totalAccumulated / this._totalValueCount;
  11104. // Reset last sec?
  11105. var now = Tools.Now;
  11106. if ((now - this._lastSecTime) > 1000) {
  11107. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  11108. this._lastSecTime = now;
  11109. this._lastSecAccumulated = 0;
  11110. this._lastSecValueCount = 0;
  11111. }
  11112. };
  11113. /**
  11114. * Gets or sets a global boolean to turn on and off all the counters
  11115. */
  11116. PerfCounter.Enabled = true;
  11117. return PerfCounter;
  11118. }());
  11119. BABYLON.PerfCounter = PerfCounter;
  11120. /**
  11121. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  11122. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  11123. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  11124. * @param name The name of the class, case should be preserved
  11125. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  11126. */
  11127. function className(name, module) {
  11128. return function (target) {
  11129. target["__bjsclassName__"] = name;
  11130. target["__bjsmoduleName__"] = (module != null) ? module : null;
  11131. };
  11132. }
  11133. BABYLON.className = className;
  11134. /**
  11135. * An implementation of a loop for asynchronous functions.
  11136. */
  11137. var AsyncLoop = /** @class */ (function () {
  11138. /**
  11139. * Constructor.
  11140. * @param iterations the number of iterations.
  11141. * @param func the function to run each iteration
  11142. * @param successCallback the callback that will be called upon succesful execution
  11143. * @param offset starting offset.
  11144. */
  11145. function AsyncLoop(
  11146. /**
  11147. * Defines the number of iterations for the loop
  11148. */
  11149. iterations, func, successCallback, offset) {
  11150. if (offset === void 0) { offset = 0; }
  11151. this.iterations = iterations;
  11152. this.index = offset - 1;
  11153. this._done = false;
  11154. this._fn = func;
  11155. this._successCallback = successCallback;
  11156. }
  11157. /**
  11158. * Execute the next iteration. Must be called after the last iteration was finished.
  11159. */
  11160. AsyncLoop.prototype.executeNext = function () {
  11161. if (!this._done) {
  11162. if (this.index + 1 < this.iterations) {
  11163. ++this.index;
  11164. this._fn(this);
  11165. }
  11166. else {
  11167. this.breakLoop();
  11168. }
  11169. }
  11170. };
  11171. /**
  11172. * Break the loop and run the success callback.
  11173. */
  11174. AsyncLoop.prototype.breakLoop = function () {
  11175. this._done = true;
  11176. this._successCallback();
  11177. };
  11178. /**
  11179. * Create and run an async loop.
  11180. * @param iterations the number of iterations.
  11181. * @param fn the function to run each iteration
  11182. * @param successCallback the callback that will be called upon succesful execution
  11183. * @param offset starting offset.
  11184. * @returns the created async loop object
  11185. */
  11186. AsyncLoop.Run = function (iterations, fn, successCallback, offset) {
  11187. if (offset === void 0) { offset = 0; }
  11188. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  11189. loop.executeNext();
  11190. return loop;
  11191. };
  11192. /**
  11193. * A for-loop that will run a given number of iterations synchronous and the rest async.
  11194. * @param iterations total number of iterations
  11195. * @param syncedIterations number of synchronous iterations in each async iteration.
  11196. * @param fn the function to call each iteration.
  11197. * @param callback a success call back that will be called when iterating stops.
  11198. * @param breakFunction a break condition (optional)
  11199. * @param timeout timeout settings for the setTimeout function. default - 0.
  11200. * @returns the created async loop object
  11201. */
  11202. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  11203. if (timeout === void 0) { timeout = 0; }
  11204. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  11205. if (breakFunction && breakFunction()) {
  11206. loop.breakLoop();
  11207. }
  11208. else {
  11209. setTimeout(function () {
  11210. for (var i = 0; i < syncedIterations; ++i) {
  11211. var iteration = (loop.index * syncedIterations) + i;
  11212. if (iteration >= iterations) {
  11213. break;
  11214. }
  11215. fn(iteration);
  11216. if (breakFunction && breakFunction()) {
  11217. loop.breakLoop();
  11218. break;
  11219. }
  11220. }
  11221. loop.executeNext();
  11222. }, timeout);
  11223. }
  11224. }, callback);
  11225. };
  11226. return AsyncLoop;
  11227. }());
  11228. BABYLON.AsyncLoop = AsyncLoop;
  11229. })(BABYLON || (BABYLON = {}));
  11230. //# sourceMappingURL=babylon.tools.js.map
  11231. var BABYLON;
  11232. (function (BABYLON) {
  11233. var PromiseStates;
  11234. (function (PromiseStates) {
  11235. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  11236. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  11237. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  11238. })(PromiseStates || (PromiseStates = {}));
  11239. var FulFillmentAgregator = /** @class */ (function () {
  11240. function FulFillmentAgregator() {
  11241. this.count = 0;
  11242. this.target = 0;
  11243. this.results = [];
  11244. }
  11245. return FulFillmentAgregator;
  11246. }());
  11247. var InternalPromise = /** @class */ (function () {
  11248. function InternalPromise(resolver) {
  11249. var _this = this;
  11250. this._state = PromiseStates.Pending;
  11251. this._children = new Array();
  11252. this._rejectWasConsumed = false;
  11253. if (!resolver) {
  11254. return;
  11255. }
  11256. try {
  11257. resolver(function (value) {
  11258. _this._resolve(value);
  11259. }, function (reason) {
  11260. _this._reject(reason);
  11261. });
  11262. }
  11263. catch (e) {
  11264. this._reject(e);
  11265. }
  11266. }
  11267. Object.defineProperty(InternalPromise.prototype, "_result", {
  11268. get: function () {
  11269. return this._resultValue;
  11270. },
  11271. set: function (value) {
  11272. this._resultValue = value;
  11273. if (this._parent && this._parent._result === undefined) {
  11274. this._parent._result = value;
  11275. }
  11276. },
  11277. enumerable: true,
  11278. configurable: true
  11279. });
  11280. InternalPromise.prototype.catch = function (onRejected) {
  11281. return this.then(undefined, onRejected);
  11282. };
  11283. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  11284. var _this = this;
  11285. var newPromise = new InternalPromise();
  11286. newPromise._onFulfilled = onFulfilled;
  11287. newPromise._onRejected = onRejected;
  11288. // Composition
  11289. this._children.push(newPromise);
  11290. newPromise._parent = this;
  11291. if (this._state !== PromiseStates.Pending) {
  11292. BABYLON.Tools.SetImmediate(function () {
  11293. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  11294. var returnedValue = newPromise._resolve(_this._result);
  11295. if (returnedValue !== undefined && returnedValue !== null) {
  11296. if (returnedValue._state !== undefined) {
  11297. var returnedPromise = returnedValue;
  11298. newPromise._children.push(returnedPromise);
  11299. returnedPromise._parent = newPromise;
  11300. newPromise = returnedPromise;
  11301. }
  11302. else {
  11303. newPromise._result = returnedValue;
  11304. }
  11305. }
  11306. }
  11307. else {
  11308. newPromise._reject(_this._reason);
  11309. }
  11310. });
  11311. }
  11312. return newPromise;
  11313. };
  11314. InternalPromise.prototype._moveChildren = function (children) {
  11315. var _this = this;
  11316. var _a;
  11317. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  11318. this._children.forEach(function (child) {
  11319. child._parent = _this;
  11320. });
  11321. if (this._state === PromiseStates.Fulfilled) {
  11322. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  11323. var child = _b[_i];
  11324. child._resolve(this._result);
  11325. }
  11326. }
  11327. else if (this._state === PromiseStates.Rejected) {
  11328. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  11329. var child = _d[_c];
  11330. child._reject(this._reason);
  11331. }
  11332. }
  11333. };
  11334. InternalPromise.prototype._resolve = function (value) {
  11335. try {
  11336. this._state = PromiseStates.Fulfilled;
  11337. var returnedValue = null;
  11338. if (this._onFulfilled) {
  11339. returnedValue = this._onFulfilled(value);
  11340. }
  11341. if (returnedValue !== undefined && returnedValue !== null) {
  11342. if (returnedValue._state !== undefined) {
  11343. // Transmit children
  11344. var returnedPromise = returnedValue;
  11345. returnedPromise._parent = this;
  11346. returnedPromise._moveChildren(this._children);
  11347. value = returnedPromise._result;
  11348. }
  11349. else {
  11350. value = returnedValue;
  11351. }
  11352. }
  11353. this._result = value;
  11354. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11355. var child = _a[_i];
  11356. child._resolve(value);
  11357. }
  11358. this._children.length = 0;
  11359. delete this._onFulfilled;
  11360. delete this._onRejected;
  11361. }
  11362. catch (e) {
  11363. this._reject(e, true);
  11364. }
  11365. };
  11366. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  11367. if (onLocalThrow === void 0) { onLocalThrow = false; }
  11368. this._state = PromiseStates.Rejected;
  11369. this._reason = reason;
  11370. if (this._onRejected && !onLocalThrow) {
  11371. try {
  11372. this._onRejected(reason);
  11373. this._rejectWasConsumed = true;
  11374. }
  11375. catch (e) {
  11376. reason = e;
  11377. }
  11378. }
  11379. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11380. var child = _a[_i];
  11381. if (this._rejectWasConsumed) {
  11382. child._resolve(null);
  11383. }
  11384. else {
  11385. child._reject(reason);
  11386. }
  11387. }
  11388. this._children.length = 0;
  11389. delete this._onFulfilled;
  11390. delete this._onRejected;
  11391. };
  11392. InternalPromise.resolve = function (value) {
  11393. var newPromise = new InternalPromise();
  11394. newPromise._resolve(value);
  11395. return newPromise;
  11396. };
  11397. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  11398. promise.then(function (value) {
  11399. agregator.results[index] = value;
  11400. agregator.count++;
  11401. if (agregator.count === agregator.target) {
  11402. agregator.rootPromise._resolve(agregator.results);
  11403. }
  11404. return null;
  11405. }, function (reason) {
  11406. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  11407. agregator.rootPromise._reject(reason);
  11408. }
  11409. });
  11410. };
  11411. InternalPromise.all = function (promises) {
  11412. var newPromise = new InternalPromise();
  11413. var agregator = new FulFillmentAgregator();
  11414. agregator.target = promises.length;
  11415. agregator.rootPromise = newPromise;
  11416. if (promises.length) {
  11417. for (var index = 0; index < promises.length; index++) {
  11418. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  11419. }
  11420. }
  11421. else {
  11422. newPromise._resolve([]);
  11423. }
  11424. return newPromise;
  11425. };
  11426. InternalPromise.race = function (promises) {
  11427. var newPromise = new InternalPromise();
  11428. if (promises.length) {
  11429. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  11430. var promise = promises_1[_i];
  11431. promise.then(function (value) {
  11432. if (newPromise) {
  11433. newPromise._resolve(value);
  11434. newPromise = null;
  11435. }
  11436. return null;
  11437. }, function (reason) {
  11438. if (newPromise) {
  11439. newPromise._reject(reason);
  11440. newPromise = null;
  11441. }
  11442. });
  11443. }
  11444. }
  11445. return newPromise;
  11446. };
  11447. return InternalPromise;
  11448. }());
  11449. /**
  11450. * Helper class that provides a small promise polyfill
  11451. */
  11452. var PromisePolyfill = /** @class */ (function () {
  11453. function PromisePolyfill() {
  11454. }
  11455. /**
  11456. * Static function used to check if the polyfill is required
  11457. * If this is the case then the function will inject the polyfill to window.Promise
  11458. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  11459. */
  11460. PromisePolyfill.Apply = function (force) {
  11461. if (force === void 0) { force = false; }
  11462. if (force || typeof Promise === 'undefined') {
  11463. var root = window;
  11464. root.Promise = InternalPromise;
  11465. }
  11466. };
  11467. return PromisePolyfill;
  11468. }());
  11469. BABYLON.PromisePolyfill = PromisePolyfill;
  11470. })(BABYLON || (BABYLON = {}));
  11471. //# sourceMappingURL=babylon.promise.js.map
  11472. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  11473. var BABYLON;
  11474. (function (BABYLON) {
  11475. /**
  11476. * Helper class to push actions to a pool of workers.
  11477. */
  11478. var WorkerPool = /** @class */ (function () {
  11479. /**
  11480. * Constructor
  11481. * @param workers Array of workers to use for actions
  11482. */
  11483. function WorkerPool(workers) {
  11484. this._pendingActions = new Array();
  11485. this._workerInfos = workers.map(function (worker) { return ({
  11486. worker: worker,
  11487. active: false
  11488. }); });
  11489. }
  11490. /**
  11491. * Terminates all workers and clears any pending actions.
  11492. */
  11493. WorkerPool.prototype.dispose = function () {
  11494. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11495. var workerInfo = _a[_i];
  11496. workerInfo.worker.terminate();
  11497. }
  11498. delete this._workerInfos;
  11499. delete this._pendingActions;
  11500. };
  11501. /**
  11502. * Pushes an action to the worker pool. If all the workers are active, the action will be
  11503. * pended until a worker has completed its action.
  11504. * @param action The action to perform. Call onComplete when the action is complete.
  11505. */
  11506. WorkerPool.prototype.push = function (action) {
  11507. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11508. var workerInfo = _a[_i];
  11509. if (!workerInfo.active) {
  11510. this._execute(workerInfo, action);
  11511. return;
  11512. }
  11513. }
  11514. this._pendingActions.push(action);
  11515. };
  11516. WorkerPool.prototype._execute = function (workerInfo, action) {
  11517. var _this = this;
  11518. workerInfo.active = true;
  11519. action(workerInfo.worker, function () {
  11520. workerInfo.active = false;
  11521. var nextAction = _this._pendingActions.shift();
  11522. if (nextAction) {
  11523. _this._execute(workerInfo, nextAction);
  11524. }
  11525. });
  11526. };
  11527. return WorkerPool;
  11528. }());
  11529. BABYLON.WorkerPool = WorkerPool;
  11530. })(BABYLON || (BABYLON = {}));
  11531. //# sourceMappingURL=babylon.workerPool.js.map
  11532. var BABYLON;
  11533. (function (BABYLON) {
  11534. /**
  11535. * @hidden
  11536. **/
  11537. var _AlphaState = /** @class */ (function () {
  11538. /**
  11539. * Initializes the state.
  11540. */
  11541. function _AlphaState() {
  11542. this._isAlphaBlendDirty = false;
  11543. this._isBlendFunctionParametersDirty = false;
  11544. this._isBlendEquationParametersDirty = false;
  11545. this._isBlendConstantsDirty = false;
  11546. this._alphaBlend = false;
  11547. this._blendFunctionParameters = new Array(4);
  11548. this._blendEquationParameters = new Array(2);
  11549. this._blendConstants = new Array(4);
  11550. this.reset();
  11551. }
  11552. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  11553. get: function () {
  11554. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  11555. },
  11556. enumerable: true,
  11557. configurable: true
  11558. });
  11559. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  11560. get: function () {
  11561. return this._alphaBlend;
  11562. },
  11563. set: function (value) {
  11564. if (this._alphaBlend === value) {
  11565. return;
  11566. }
  11567. this._alphaBlend = value;
  11568. this._isAlphaBlendDirty = true;
  11569. },
  11570. enumerable: true,
  11571. configurable: true
  11572. });
  11573. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  11574. if (this._blendConstants[0] === r &&
  11575. this._blendConstants[1] === g &&
  11576. this._blendConstants[2] === b &&
  11577. this._blendConstants[3] === a) {
  11578. return;
  11579. }
  11580. this._blendConstants[0] = r;
  11581. this._blendConstants[1] = g;
  11582. this._blendConstants[2] = b;
  11583. this._blendConstants[3] = a;
  11584. this._isBlendConstantsDirty = true;
  11585. };
  11586. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  11587. if (this._blendFunctionParameters[0] === value0 &&
  11588. this._blendFunctionParameters[1] === value1 &&
  11589. this._blendFunctionParameters[2] === value2 &&
  11590. this._blendFunctionParameters[3] === value3) {
  11591. return;
  11592. }
  11593. this._blendFunctionParameters[0] = value0;
  11594. this._blendFunctionParameters[1] = value1;
  11595. this._blendFunctionParameters[2] = value2;
  11596. this._blendFunctionParameters[3] = value3;
  11597. this._isBlendFunctionParametersDirty = true;
  11598. };
  11599. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  11600. if (this._blendEquationParameters[0] === rgb &&
  11601. this._blendEquationParameters[1] === alpha) {
  11602. return;
  11603. }
  11604. this._blendEquationParameters[0] = rgb;
  11605. this._blendEquationParameters[1] = alpha;
  11606. this._isBlendEquationParametersDirty = true;
  11607. };
  11608. _AlphaState.prototype.reset = function () {
  11609. this._alphaBlend = false;
  11610. this._blendFunctionParameters[0] = null;
  11611. this._blendFunctionParameters[1] = null;
  11612. this._blendFunctionParameters[2] = null;
  11613. this._blendFunctionParameters[3] = null;
  11614. this._blendEquationParameters[0] = null;
  11615. this._blendEquationParameters[1] = null;
  11616. this._blendConstants[0] = null;
  11617. this._blendConstants[1] = null;
  11618. this._blendConstants[2] = null;
  11619. this._blendConstants[3] = null;
  11620. this._isAlphaBlendDirty = true;
  11621. this._isBlendFunctionParametersDirty = false;
  11622. this._isBlendEquationParametersDirty = false;
  11623. this._isBlendConstantsDirty = false;
  11624. };
  11625. _AlphaState.prototype.apply = function (gl) {
  11626. if (!this.isDirty) {
  11627. return;
  11628. }
  11629. // Alpha blend
  11630. if (this._isAlphaBlendDirty) {
  11631. if (this._alphaBlend) {
  11632. gl.enable(gl.BLEND);
  11633. }
  11634. else {
  11635. gl.disable(gl.BLEND);
  11636. }
  11637. this._isAlphaBlendDirty = false;
  11638. }
  11639. // Alpha function
  11640. if (this._isBlendFunctionParametersDirty) {
  11641. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  11642. this._isBlendFunctionParametersDirty = false;
  11643. }
  11644. // Alpha equation
  11645. if (this._isBlendEquationParametersDirty) {
  11646. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  11647. this._isBlendEquationParametersDirty = false;
  11648. }
  11649. // Constants
  11650. if (this._isBlendConstantsDirty) {
  11651. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  11652. this._isBlendConstantsDirty = false;
  11653. }
  11654. };
  11655. return _AlphaState;
  11656. }());
  11657. BABYLON._AlphaState = _AlphaState;
  11658. })(BABYLON || (BABYLON = {}));
  11659. //# sourceMappingURL=babylon.alphaCullingState.js.map
  11660. var BABYLON;
  11661. (function (BABYLON) {
  11662. /**
  11663. * @hidden
  11664. **/
  11665. var _DepthCullingState = /** @class */ (function () {
  11666. /**
  11667. * Initializes the state.
  11668. */
  11669. function _DepthCullingState() {
  11670. this._isDepthTestDirty = false;
  11671. this._isDepthMaskDirty = false;
  11672. this._isDepthFuncDirty = false;
  11673. this._isCullFaceDirty = false;
  11674. this._isCullDirty = false;
  11675. this._isZOffsetDirty = false;
  11676. this._isFrontFaceDirty = false;
  11677. this.reset();
  11678. }
  11679. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  11680. get: function () {
  11681. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  11682. },
  11683. enumerable: true,
  11684. configurable: true
  11685. });
  11686. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  11687. get: function () {
  11688. return this._zOffset;
  11689. },
  11690. set: function (value) {
  11691. if (this._zOffset === value) {
  11692. return;
  11693. }
  11694. this._zOffset = value;
  11695. this._isZOffsetDirty = true;
  11696. },
  11697. enumerable: true,
  11698. configurable: true
  11699. });
  11700. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  11701. get: function () {
  11702. return this._cullFace;
  11703. },
  11704. set: function (value) {
  11705. if (this._cullFace === value) {
  11706. return;
  11707. }
  11708. this._cullFace = value;
  11709. this._isCullFaceDirty = true;
  11710. },
  11711. enumerable: true,
  11712. configurable: true
  11713. });
  11714. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11715. get: function () {
  11716. return this._cull;
  11717. },
  11718. set: function (value) {
  11719. if (this._cull === value) {
  11720. return;
  11721. }
  11722. this._cull = value;
  11723. this._isCullDirty = true;
  11724. },
  11725. enumerable: true,
  11726. configurable: true
  11727. });
  11728. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11729. get: function () {
  11730. return this._depthFunc;
  11731. },
  11732. set: function (value) {
  11733. if (this._depthFunc === value) {
  11734. return;
  11735. }
  11736. this._depthFunc = value;
  11737. this._isDepthFuncDirty = true;
  11738. },
  11739. enumerable: true,
  11740. configurable: true
  11741. });
  11742. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11743. get: function () {
  11744. return this._depthMask;
  11745. },
  11746. set: function (value) {
  11747. if (this._depthMask === value) {
  11748. return;
  11749. }
  11750. this._depthMask = value;
  11751. this._isDepthMaskDirty = true;
  11752. },
  11753. enumerable: true,
  11754. configurable: true
  11755. });
  11756. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11757. get: function () {
  11758. return this._depthTest;
  11759. },
  11760. set: function (value) {
  11761. if (this._depthTest === value) {
  11762. return;
  11763. }
  11764. this._depthTest = value;
  11765. this._isDepthTestDirty = true;
  11766. },
  11767. enumerable: true,
  11768. configurable: true
  11769. });
  11770. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11771. get: function () {
  11772. return this._frontFace;
  11773. },
  11774. set: function (value) {
  11775. if (this._frontFace === value) {
  11776. return;
  11777. }
  11778. this._frontFace = value;
  11779. this._isFrontFaceDirty = true;
  11780. },
  11781. enumerable: true,
  11782. configurable: true
  11783. });
  11784. _DepthCullingState.prototype.reset = function () {
  11785. this._depthMask = true;
  11786. this._depthTest = true;
  11787. this._depthFunc = null;
  11788. this._cullFace = null;
  11789. this._cull = null;
  11790. this._zOffset = 0;
  11791. this._frontFace = null;
  11792. this._isDepthTestDirty = true;
  11793. this._isDepthMaskDirty = true;
  11794. this._isDepthFuncDirty = false;
  11795. this._isCullFaceDirty = false;
  11796. this._isCullDirty = false;
  11797. this._isZOffsetDirty = false;
  11798. this._isFrontFaceDirty = false;
  11799. };
  11800. _DepthCullingState.prototype.apply = function (gl) {
  11801. if (!this.isDirty) {
  11802. return;
  11803. }
  11804. // Cull
  11805. if (this._isCullDirty) {
  11806. if (this.cull) {
  11807. gl.enable(gl.CULL_FACE);
  11808. }
  11809. else {
  11810. gl.disable(gl.CULL_FACE);
  11811. }
  11812. this._isCullDirty = false;
  11813. }
  11814. // Cull face
  11815. if (this._isCullFaceDirty) {
  11816. gl.cullFace(this.cullFace);
  11817. this._isCullFaceDirty = false;
  11818. }
  11819. // Depth mask
  11820. if (this._isDepthMaskDirty) {
  11821. gl.depthMask(this.depthMask);
  11822. this._isDepthMaskDirty = false;
  11823. }
  11824. // Depth test
  11825. if (this._isDepthTestDirty) {
  11826. if (this.depthTest) {
  11827. gl.enable(gl.DEPTH_TEST);
  11828. }
  11829. else {
  11830. gl.disable(gl.DEPTH_TEST);
  11831. }
  11832. this._isDepthTestDirty = false;
  11833. }
  11834. // Depth func
  11835. if (this._isDepthFuncDirty) {
  11836. gl.depthFunc(this.depthFunc);
  11837. this._isDepthFuncDirty = false;
  11838. }
  11839. // zOffset
  11840. if (this._isZOffsetDirty) {
  11841. if (this.zOffset) {
  11842. gl.enable(gl.POLYGON_OFFSET_FILL);
  11843. gl.polygonOffset(this.zOffset, 0);
  11844. }
  11845. else {
  11846. gl.disable(gl.POLYGON_OFFSET_FILL);
  11847. }
  11848. this._isZOffsetDirty = false;
  11849. }
  11850. // Front face
  11851. if (this._isFrontFaceDirty) {
  11852. gl.frontFace(this.frontFace);
  11853. this._isFrontFaceDirty = false;
  11854. }
  11855. };
  11856. return _DepthCullingState;
  11857. }());
  11858. BABYLON._DepthCullingState = _DepthCullingState;
  11859. })(BABYLON || (BABYLON = {}));
  11860. //# sourceMappingURL=babylon.depthCullingState.js.map
  11861. var BABYLON;
  11862. (function (BABYLON) {
  11863. /**
  11864. * @hidden
  11865. **/
  11866. var _StencilState = /** @class */ (function () {
  11867. function _StencilState() {
  11868. this._isStencilTestDirty = false;
  11869. this._isStencilMaskDirty = false;
  11870. this._isStencilFuncDirty = false;
  11871. this._isStencilOpDirty = false;
  11872. this.reset();
  11873. }
  11874. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11875. get: function () {
  11876. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11877. },
  11878. enumerable: true,
  11879. configurable: true
  11880. });
  11881. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11882. get: function () {
  11883. return this._stencilFunc;
  11884. },
  11885. set: function (value) {
  11886. if (this._stencilFunc === value) {
  11887. return;
  11888. }
  11889. this._stencilFunc = value;
  11890. this._isStencilFuncDirty = true;
  11891. },
  11892. enumerable: true,
  11893. configurable: true
  11894. });
  11895. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11896. get: function () {
  11897. return this._stencilFuncRef;
  11898. },
  11899. set: function (value) {
  11900. if (this._stencilFuncRef === value) {
  11901. return;
  11902. }
  11903. this._stencilFuncRef = value;
  11904. this._isStencilFuncDirty = true;
  11905. },
  11906. enumerable: true,
  11907. configurable: true
  11908. });
  11909. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11910. get: function () {
  11911. return this._stencilFuncMask;
  11912. },
  11913. set: function (value) {
  11914. if (this._stencilFuncMask === value) {
  11915. return;
  11916. }
  11917. this._stencilFuncMask = value;
  11918. this._isStencilFuncDirty = true;
  11919. },
  11920. enumerable: true,
  11921. configurable: true
  11922. });
  11923. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11924. get: function () {
  11925. return this._stencilOpStencilFail;
  11926. },
  11927. set: function (value) {
  11928. if (this._stencilOpStencilFail === value) {
  11929. return;
  11930. }
  11931. this._stencilOpStencilFail = value;
  11932. this._isStencilOpDirty = true;
  11933. },
  11934. enumerable: true,
  11935. configurable: true
  11936. });
  11937. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11938. get: function () {
  11939. return this._stencilOpDepthFail;
  11940. },
  11941. set: function (value) {
  11942. if (this._stencilOpDepthFail === value) {
  11943. return;
  11944. }
  11945. this._stencilOpDepthFail = value;
  11946. this._isStencilOpDirty = true;
  11947. },
  11948. enumerable: true,
  11949. configurable: true
  11950. });
  11951. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11952. get: function () {
  11953. return this._stencilOpStencilDepthPass;
  11954. },
  11955. set: function (value) {
  11956. if (this._stencilOpStencilDepthPass === value) {
  11957. return;
  11958. }
  11959. this._stencilOpStencilDepthPass = value;
  11960. this._isStencilOpDirty = true;
  11961. },
  11962. enumerable: true,
  11963. configurable: true
  11964. });
  11965. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11966. get: function () {
  11967. return this._stencilMask;
  11968. },
  11969. set: function (value) {
  11970. if (this._stencilMask === value) {
  11971. return;
  11972. }
  11973. this._stencilMask = value;
  11974. this._isStencilMaskDirty = true;
  11975. },
  11976. enumerable: true,
  11977. configurable: true
  11978. });
  11979. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11980. get: function () {
  11981. return this._stencilTest;
  11982. },
  11983. set: function (value) {
  11984. if (this._stencilTest === value) {
  11985. return;
  11986. }
  11987. this._stencilTest = value;
  11988. this._isStencilTestDirty = true;
  11989. },
  11990. enumerable: true,
  11991. configurable: true
  11992. });
  11993. _StencilState.prototype.reset = function () {
  11994. this._stencilTest = false;
  11995. this._stencilMask = 0xFF;
  11996. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11997. this._stencilFuncRef = 1;
  11998. this._stencilFuncMask = 0xFF;
  11999. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  12000. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  12001. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  12002. this._isStencilTestDirty = true;
  12003. this._isStencilMaskDirty = true;
  12004. this._isStencilFuncDirty = true;
  12005. this._isStencilOpDirty = true;
  12006. };
  12007. _StencilState.prototype.apply = function (gl) {
  12008. if (!this.isDirty) {
  12009. return;
  12010. }
  12011. // Stencil test
  12012. if (this._isStencilTestDirty) {
  12013. if (this.stencilTest) {
  12014. gl.enable(gl.STENCIL_TEST);
  12015. }
  12016. else {
  12017. gl.disable(gl.STENCIL_TEST);
  12018. }
  12019. this._isStencilTestDirty = false;
  12020. }
  12021. // Stencil mask
  12022. if (this._isStencilMaskDirty) {
  12023. gl.stencilMask(this.stencilMask);
  12024. this._isStencilMaskDirty = false;
  12025. }
  12026. // Stencil func
  12027. if (this._isStencilFuncDirty) {
  12028. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  12029. this._isStencilFuncDirty = false;
  12030. }
  12031. // Stencil op
  12032. if (this._isStencilOpDirty) {
  12033. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  12034. this._isStencilOpDirty = false;
  12035. }
  12036. };
  12037. return _StencilState;
  12038. }());
  12039. BABYLON._StencilState = _StencilState;
  12040. })(BABYLON || (BABYLON = {}));
  12041. //# sourceMappingURL=babylon.stencilState.js.map
  12042. var __assign = (this && this.__assign) || function () {
  12043. __assign = Object.assign || function(t) {
  12044. for (var s, i = 1, n = arguments.length; i < n; i++) {
  12045. s = arguments[i];
  12046. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  12047. t[p] = s[p];
  12048. }
  12049. return t;
  12050. };
  12051. return __assign.apply(this, arguments);
  12052. };
  12053. var BABYLON;
  12054. (function (BABYLON) {
  12055. /**
  12056. * Keeps track of all the buffer info used in engine.
  12057. */
  12058. var BufferPointer = /** @class */ (function () {
  12059. function BufferPointer() {
  12060. }
  12061. return BufferPointer;
  12062. }());
  12063. /**
  12064. * Interface for attribute information associated with buffer instanciation
  12065. */
  12066. var InstancingAttributeInfo = /** @class */ (function () {
  12067. function InstancingAttributeInfo() {
  12068. }
  12069. return InstancingAttributeInfo;
  12070. }());
  12071. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  12072. /**
  12073. * Define options used to create a render target texture
  12074. */
  12075. var RenderTargetCreationOptions = /** @class */ (function () {
  12076. function RenderTargetCreationOptions() {
  12077. }
  12078. return RenderTargetCreationOptions;
  12079. }());
  12080. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  12081. /**
  12082. * Define options used to create a depth texture
  12083. */
  12084. var DepthTextureCreationOptions = /** @class */ (function () {
  12085. function DepthTextureCreationOptions() {
  12086. }
  12087. return DepthTextureCreationOptions;
  12088. }());
  12089. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  12090. /**
  12091. * Class used to describe the capabilities of the engine relatively to the current browser
  12092. */
  12093. var EngineCapabilities = /** @class */ (function () {
  12094. function EngineCapabilities() {
  12095. }
  12096. return EngineCapabilities;
  12097. }());
  12098. BABYLON.EngineCapabilities = EngineCapabilities;
  12099. /**
  12100. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  12101. */
  12102. var Engine = /** @class */ (function () {
  12103. /**
  12104. * Creates a new engine
  12105. * @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
  12106. * @param antialias defines enable antialiasing (default: false)
  12107. * @param options defines further options to be sent to the getContext() function
  12108. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  12109. */
  12110. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  12111. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  12112. var _this = this;
  12113. // Public members
  12114. /**
  12115. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  12116. */
  12117. this.forcePOTTextures = false;
  12118. /**
  12119. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  12120. */
  12121. this.isFullscreen = false;
  12122. /**
  12123. * Gets a boolean indicating if the pointer is currently locked
  12124. */
  12125. this.isPointerLock = false;
  12126. /**
  12127. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  12128. */
  12129. this.cullBackFaces = true;
  12130. /**
  12131. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  12132. */
  12133. this.renderEvenInBackground = true;
  12134. /**
  12135. * Gets or sets a boolean indicating that cache can be kept between frames
  12136. */
  12137. this.preventCacheWipeBetweenFrames = false;
  12138. /**
  12139. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  12140. **/
  12141. this.enableOfflineSupport = false;
  12142. /**
  12143. * 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)
  12144. **/
  12145. this.disableManifestCheck = false;
  12146. /**
  12147. * Gets the list of created scenes
  12148. */
  12149. this.scenes = new Array();
  12150. /**
  12151. * Gets the list of created postprocesses
  12152. */
  12153. this.postProcesses = new Array();
  12154. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  12155. this.validateShaderPrograms = false;
  12156. // Observables
  12157. /**
  12158. * Observable event triggered each time the rendering canvas is resized
  12159. */
  12160. this.onResizeObservable = new BABYLON.Observable();
  12161. /**
  12162. * Observable event triggered each time the canvas loses focus
  12163. */
  12164. this.onCanvasBlurObservable = new BABYLON.Observable();
  12165. /**
  12166. * Observable event triggered each time the canvas gains focus
  12167. */
  12168. this.onCanvasFocusObservable = new BABYLON.Observable();
  12169. /**
  12170. * Observable event triggered each time the canvas receives pointerout event
  12171. */
  12172. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  12173. /**
  12174. * Observable event triggered before each texture is initialized
  12175. */
  12176. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  12177. //WebVR
  12178. this._vrDisplay = undefined;
  12179. this._vrSupported = false;
  12180. this._vrExclusivePointerMode = false;
  12181. // Uniform buffers list
  12182. /**
  12183. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  12184. */
  12185. this.disableUniformBuffers = false;
  12186. /** @hidden */
  12187. this._uniformBuffers = new Array();
  12188. // Observables
  12189. /**
  12190. * Observable raised when the engine begins a new frame
  12191. */
  12192. this.onBeginFrameObservable = new BABYLON.Observable();
  12193. /**
  12194. * Observable raised when the engine ends the current frame
  12195. */
  12196. this.onEndFrameObservable = new BABYLON.Observable();
  12197. /**
  12198. * Observable raised when the engine is about to compile a shader
  12199. */
  12200. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  12201. /**
  12202. * Observable raised when the engine has jsut compiled a shader
  12203. */
  12204. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  12205. this._windowIsBackground = false;
  12206. this._webGLVersion = 1.0;
  12207. /** @hidden */
  12208. this._badOS = false;
  12209. /** @hidden */
  12210. this._badDesktopOS = false;
  12211. /**
  12212. * Gets or sets a value indicating if we want to disable texture binding optmization.
  12213. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  12214. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  12215. */
  12216. this.disableTextureBindingOptimization = false;
  12217. /**
  12218. * Observable signaled when VR display mode changes
  12219. */
  12220. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  12221. /**
  12222. * Observable signaled when VR request present is complete
  12223. */
  12224. this.onVRRequestPresentComplete = new BABYLON.Observable();
  12225. /**
  12226. * Observable signaled when VR request present starts
  12227. */
  12228. this.onVRRequestPresentStart = new BABYLON.Observable();
  12229. this._colorWrite = true;
  12230. /** @hidden */
  12231. this._drawCalls = new BABYLON.PerfCounter();
  12232. /** @hidden */
  12233. this._textureCollisions = new BABYLON.PerfCounter();
  12234. this._renderingQueueLaunched = false;
  12235. this._activeRenderLoops = new Array();
  12236. // Deterministic lockstepMaxSteps
  12237. this._deterministicLockstep = false;
  12238. this._lockstepMaxSteps = 4;
  12239. // Lost context
  12240. /**
  12241. * Observable signaled when a context lost event is raised
  12242. */
  12243. this.onContextLostObservable = new BABYLON.Observable();
  12244. /**
  12245. * Observable signaled when a context restored event is raised
  12246. */
  12247. this.onContextRestoredObservable = new BABYLON.Observable();
  12248. this._contextWasLost = false;
  12249. this._doNotHandleContextLost = false;
  12250. // FPS
  12251. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  12252. this._fps = 60;
  12253. this._deltaTime = 0;
  12254. /**
  12255. * Turn this value on if you want to pause FPS computation when in background
  12256. */
  12257. this.disablePerformanceMonitorInBackground = false;
  12258. // States
  12259. /** @hidden */
  12260. this._depthCullingState = new BABYLON._DepthCullingState();
  12261. /** @hidden */
  12262. this._stencilState = new BABYLON._StencilState();
  12263. /** @hidden */
  12264. this._alphaState = new BABYLON._AlphaState();
  12265. /** @hidden */
  12266. this._alphaMode = Engine.ALPHA_DISABLE;
  12267. // Cache
  12268. this._internalTexturesCache = new Array();
  12269. /** @hidden */
  12270. this._activeChannel = 0;
  12271. this._currentTextureChannel = -1;
  12272. /** @hidden */
  12273. this._boundTexturesCache = {};
  12274. this._compiledEffects = {};
  12275. this._vertexAttribArraysEnabled = [];
  12276. this._uintIndicesCurrentlySet = false;
  12277. this._currentBoundBuffer = new Array();
  12278. /** @hidden */
  12279. this._currentFramebuffer = null;
  12280. this._currentBufferPointers = new Array();
  12281. this._currentInstanceLocations = new Array();
  12282. this._currentInstanceBuffers = new Array();
  12283. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12284. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12285. this._vaoRecordInProgress = false;
  12286. this._mustWipeVertexAttributes = false;
  12287. this._nextFreeTextureSlots = new Array();
  12288. this._maxSimultaneousTextures = 0;
  12289. this._activeRequests = new Array();
  12290. // Hardware supported Compressed Textures
  12291. this._texturesSupported = new Array();
  12292. /**
  12293. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  12294. */
  12295. this.premultipliedAlpha = true;
  12296. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  12297. this._onVRFullScreenTriggered = function () {
  12298. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  12299. //get the old size before we change
  12300. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  12301. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  12302. //get the width and height, change the render size
  12303. var leftEye = _this._vrDisplay.getEyeParameters('left');
  12304. _this.setHardwareScalingLevel(1);
  12305. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  12306. }
  12307. else {
  12308. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  12309. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  12310. }
  12311. };
  12312. this._unpackFlipYCached = null;
  12313. /**
  12314. * In case you are sharing the context with other applications, it might
  12315. * be interested to not cache the unpack flip y state to ensure a consistent
  12316. * value would be set.
  12317. */
  12318. this.enableUnpackFlipYCached = true;
  12319. this._boundUniforms = {};
  12320. // Register promises
  12321. BABYLON.PromisePolyfill.Apply();
  12322. var canvas = null;
  12323. Engine.Instances.push(this);
  12324. if (!canvasOrContext) {
  12325. return;
  12326. }
  12327. options = options || {};
  12328. if (canvasOrContext.getContext) {
  12329. canvas = canvasOrContext;
  12330. this._renderingCanvas = canvas;
  12331. if (antialias != null) {
  12332. options.antialias = antialias;
  12333. }
  12334. if (options.deterministicLockstep === undefined) {
  12335. options.deterministicLockstep = false;
  12336. }
  12337. if (options.lockstepMaxSteps === undefined) {
  12338. options.lockstepMaxSteps = 4;
  12339. }
  12340. if (options.preserveDrawingBuffer === undefined) {
  12341. options.preserveDrawingBuffer = false;
  12342. }
  12343. if (options.audioEngine === undefined) {
  12344. options.audioEngine = true;
  12345. }
  12346. if (options.stencil === undefined) {
  12347. options.stencil = true;
  12348. }
  12349. if (options.premultipliedAlpha === false) {
  12350. this.premultipliedAlpha = false;
  12351. }
  12352. this._deterministicLockstep = options.deterministicLockstep;
  12353. this._lockstepMaxSteps = options.lockstepMaxSteps;
  12354. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  12355. // Exceptions
  12356. if (navigator && navigator.userAgent) {
  12357. var ua = navigator.userAgent;
  12358. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  12359. var exception = _a[_i];
  12360. var key = exception.key;
  12361. var targets = exception.targets;
  12362. if (ua.indexOf(key) > -1) {
  12363. if (exception.capture && exception.captureConstraint) {
  12364. var capture = exception.capture;
  12365. var constraint = exception.captureConstraint;
  12366. var regex = new RegExp(capture);
  12367. var matches = regex.exec(ua);
  12368. if (matches && matches.length > 0) {
  12369. var capturedValue = parseInt(matches[matches.length - 1]);
  12370. if (capturedValue >= constraint) {
  12371. continue;
  12372. }
  12373. }
  12374. }
  12375. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  12376. var target = targets_1[_b];
  12377. switch (target) {
  12378. case "uniformBuffer":
  12379. this.disableUniformBuffers = true;
  12380. break;
  12381. case "textureBindingOptimization":
  12382. this.disableTextureBindingOptimization = true;
  12383. break;
  12384. }
  12385. }
  12386. }
  12387. }
  12388. }
  12389. // GL
  12390. if (!options.disableWebGL2Support) {
  12391. try {
  12392. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  12393. if (this._gl) {
  12394. this._webGLVersion = 2.0;
  12395. // Prevent weird browsers to lie :-)
  12396. if (!this._gl.deleteQuery) {
  12397. this._webGLVersion = 1.0;
  12398. }
  12399. }
  12400. }
  12401. catch (e) {
  12402. // Do nothing
  12403. }
  12404. }
  12405. if (!this._gl) {
  12406. if (!canvas) {
  12407. throw new Error("The provided canvas is null or undefined.");
  12408. }
  12409. try {
  12410. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  12411. }
  12412. catch (e) {
  12413. throw new Error("WebGL not supported");
  12414. }
  12415. }
  12416. if (!this._gl) {
  12417. throw new Error("WebGL not supported");
  12418. }
  12419. this._onCanvasFocus = function () {
  12420. _this.onCanvasFocusObservable.notifyObservers(_this);
  12421. };
  12422. this._onCanvasBlur = function () {
  12423. _this.onCanvasBlurObservable.notifyObservers(_this);
  12424. };
  12425. canvas.addEventListener("focus", this._onCanvasFocus);
  12426. canvas.addEventListener("blur", this._onCanvasBlur);
  12427. this._onBlur = function () {
  12428. if (_this.disablePerformanceMonitorInBackground) {
  12429. _this._performanceMonitor.disable();
  12430. }
  12431. _this._windowIsBackground = true;
  12432. };
  12433. this._onFocus = function () {
  12434. if (_this.disablePerformanceMonitorInBackground) {
  12435. _this._performanceMonitor.enable();
  12436. }
  12437. _this._windowIsBackground = false;
  12438. };
  12439. this._onCanvasPointerOut = function (ev) {
  12440. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  12441. };
  12442. window.addEventListener("blur", this._onBlur);
  12443. window.addEventListener("focus", this._onFocus);
  12444. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  12445. // Context lost
  12446. if (!this._doNotHandleContextLost) {
  12447. this._onContextLost = function (evt) {
  12448. evt.preventDefault();
  12449. _this._contextWasLost = true;
  12450. BABYLON.Tools.Warn("WebGL context lost.");
  12451. _this.onContextLostObservable.notifyObservers(_this);
  12452. };
  12453. this._onContextRestored = function (evt) {
  12454. // Adding a timeout to avoid race condition at browser level
  12455. setTimeout(function () {
  12456. // Rebuild gl context
  12457. _this._initGLContext();
  12458. // Rebuild effects
  12459. _this._rebuildEffects();
  12460. // Rebuild textures
  12461. _this._rebuildInternalTextures();
  12462. // Rebuild buffers
  12463. _this._rebuildBuffers();
  12464. // Cache
  12465. _this.wipeCaches(true);
  12466. BABYLON.Tools.Warn("WebGL context successfully restored.");
  12467. _this.onContextRestoredObservable.notifyObservers(_this);
  12468. _this._contextWasLost = false;
  12469. }, 0);
  12470. };
  12471. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  12472. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  12473. }
  12474. }
  12475. else {
  12476. this._gl = canvasOrContext;
  12477. this._renderingCanvas = this._gl.canvas;
  12478. if (this._gl.renderbufferStorageMultisample) {
  12479. this._webGLVersion = 2.0;
  12480. }
  12481. var attributes = this._gl.getContextAttributes();
  12482. if (attributes) {
  12483. options.stencil = attributes.stencil;
  12484. }
  12485. }
  12486. // Viewport
  12487. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  12488. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  12489. this.resize();
  12490. this._isStencilEnable = options.stencil ? true : false;
  12491. this._initGLContext();
  12492. if (canvas) {
  12493. // Fullscreen
  12494. this._onFullscreenChange = function () {
  12495. if (document.fullscreen !== undefined) {
  12496. _this.isFullscreen = document.fullscreen;
  12497. }
  12498. else if (document.mozFullScreen !== undefined) {
  12499. _this.isFullscreen = document.mozFullScreen;
  12500. }
  12501. else if (document.webkitIsFullScreen !== undefined) {
  12502. _this.isFullscreen = document.webkitIsFullScreen;
  12503. }
  12504. else if (document.msIsFullScreen !== undefined) {
  12505. _this.isFullscreen = document.msIsFullScreen;
  12506. }
  12507. // Pointer lock
  12508. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  12509. canvas.requestPointerLock = canvas.requestPointerLock ||
  12510. canvas.msRequestPointerLock ||
  12511. canvas.mozRequestPointerLock ||
  12512. canvas.webkitRequestPointerLock;
  12513. if (canvas.requestPointerLock) {
  12514. canvas.requestPointerLock();
  12515. }
  12516. }
  12517. };
  12518. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  12519. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  12520. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  12521. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  12522. // Pointer lock
  12523. this._onPointerLockChange = function () {
  12524. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  12525. document.webkitPointerLockElement === canvas ||
  12526. document.msPointerLockElement === canvas ||
  12527. document.pointerLockElement === canvas);
  12528. };
  12529. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  12530. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  12531. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  12532. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  12533. this._onVRDisplayPointerRestricted = function () {
  12534. if (canvas) {
  12535. canvas.requestPointerLock();
  12536. }
  12537. };
  12538. this._onVRDisplayPointerUnrestricted = function () {
  12539. document.exitPointerLock();
  12540. };
  12541. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  12542. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  12543. }
  12544. // Create Audio Engine if needed.
  12545. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  12546. Engine.audioEngine = Engine.AudioEngineFactory(this.getRenderingCanvas());
  12547. }
  12548. // Prepare buffer pointers
  12549. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12550. this._currentBufferPointers[i] = new BufferPointer();
  12551. }
  12552. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  12553. // Load WebVR Devices
  12554. if (options.autoEnableWebVR) {
  12555. this.initWebVR();
  12556. }
  12557. // Detect if we are running on a faulty buggy OS.
  12558. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  12559. // Detect if we are running on a faulty buggy desktop OS.
  12560. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  12561. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  12562. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  12563. }
  12564. Object.defineProperty(Engine, "LastCreatedEngine", {
  12565. /**
  12566. * Gets the latest created engine
  12567. */
  12568. get: function () {
  12569. if (Engine.Instances.length === 0) {
  12570. return null;
  12571. }
  12572. return Engine.Instances[Engine.Instances.length - 1];
  12573. },
  12574. enumerable: true,
  12575. configurable: true
  12576. });
  12577. Object.defineProperty(Engine, "LastCreatedScene", {
  12578. /**
  12579. * Gets the latest created scene
  12580. */
  12581. get: function () {
  12582. var lastCreatedEngine = Engine.LastCreatedEngine;
  12583. if (!lastCreatedEngine) {
  12584. return null;
  12585. }
  12586. if (lastCreatedEngine.scenes.length === 0) {
  12587. return null;
  12588. }
  12589. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  12590. },
  12591. enumerable: true,
  12592. configurable: true
  12593. });
  12594. /**
  12595. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  12596. * @param flag defines which part of the materials must be marked as dirty
  12597. * @param predicate defines a predicate used to filter which materials should be affected
  12598. */
  12599. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  12600. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  12601. var engine = Engine.Instances[engineIndex];
  12602. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  12603. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  12604. }
  12605. }
  12606. };
  12607. Object.defineProperty(Engine, "Version", {
  12608. /**
  12609. * Returns the current version of the framework
  12610. */
  12611. get: function () {
  12612. return "3.3.0-rc.4";
  12613. },
  12614. enumerable: true,
  12615. configurable: true
  12616. });
  12617. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12618. /**
  12619. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12620. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12621. */
  12622. get: function () {
  12623. return this._vrExclusivePointerMode;
  12624. },
  12625. enumerable: true,
  12626. configurable: true
  12627. });
  12628. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12629. /**
  12630. * Gets a boolean indicating that the engine supports uniform buffers
  12631. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12632. */
  12633. get: function () {
  12634. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12635. },
  12636. enumerable: true,
  12637. configurable: true
  12638. });
  12639. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12640. /**
  12641. * Gets a boolean indicating that only power of 2 textures are supported
  12642. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12643. */
  12644. get: function () {
  12645. return this._webGLVersion < 2 || this.forcePOTTextures;
  12646. },
  12647. enumerable: true,
  12648. configurable: true
  12649. });
  12650. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12651. /**
  12652. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12653. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12654. */
  12655. get: function () {
  12656. return this._doNotHandleContextLost;
  12657. },
  12658. set: function (value) {
  12659. this._doNotHandleContextLost = value;
  12660. },
  12661. enumerable: true,
  12662. configurable: true
  12663. });
  12664. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12665. /**
  12666. * Gets the performance monitor attached to this engine
  12667. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12668. */
  12669. get: function () {
  12670. return this._performanceMonitor;
  12671. },
  12672. enumerable: true,
  12673. configurable: true
  12674. });
  12675. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12676. /**
  12677. * Gets the list of texture formats supported
  12678. */
  12679. get: function () {
  12680. return this._texturesSupported;
  12681. },
  12682. enumerable: true,
  12683. configurable: true
  12684. });
  12685. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12686. /**
  12687. * Gets the list of texture formats in use
  12688. */
  12689. get: function () {
  12690. return this._textureFormatInUse;
  12691. },
  12692. enumerable: true,
  12693. configurable: true
  12694. });
  12695. Object.defineProperty(Engine.prototype, "currentViewport", {
  12696. /**
  12697. * Gets the current viewport
  12698. */
  12699. get: function () {
  12700. return this._cachedViewport;
  12701. },
  12702. enumerable: true,
  12703. configurable: true
  12704. });
  12705. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12706. /**
  12707. * Gets the default empty texture
  12708. */
  12709. get: function () {
  12710. if (!this._emptyTexture) {
  12711. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12712. }
  12713. return this._emptyTexture;
  12714. },
  12715. enumerable: true,
  12716. configurable: true
  12717. });
  12718. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12719. /**
  12720. * Gets the default empty 3D texture
  12721. */
  12722. get: function () {
  12723. if (!this._emptyTexture3D) {
  12724. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12725. }
  12726. return this._emptyTexture3D;
  12727. },
  12728. enumerable: true,
  12729. configurable: true
  12730. });
  12731. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12732. /**
  12733. * Gets the default empty cube texture
  12734. */
  12735. get: function () {
  12736. if (!this._emptyCubeTexture) {
  12737. var faceData = new Uint8Array(4);
  12738. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12739. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12740. }
  12741. return this._emptyCubeTexture;
  12742. },
  12743. enumerable: true,
  12744. configurable: true
  12745. });
  12746. Engine.prototype._rebuildInternalTextures = function () {
  12747. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12748. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12749. var internalTexture = currentState_1[_i];
  12750. internalTexture._rebuild();
  12751. }
  12752. };
  12753. Engine.prototype._rebuildEffects = function () {
  12754. for (var key in this._compiledEffects) {
  12755. var effect = this._compiledEffects[key];
  12756. effect._prepareEffect();
  12757. }
  12758. BABYLON.Effect.ResetCache();
  12759. };
  12760. Engine.prototype._rebuildBuffers = function () {
  12761. // Index / Vertex
  12762. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12763. var scene = _a[_i];
  12764. scene.resetCachedMaterial();
  12765. scene._rebuildGeometries();
  12766. scene._rebuildTextures();
  12767. }
  12768. // Uniforms
  12769. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12770. var uniformBuffer = _c[_b];
  12771. uniformBuffer._rebuild();
  12772. }
  12773. };
  12774. Engine.prototype._initGLContext = function () {
  12775. // Caps
  12776. this._caps = new EngineCapabilities();
  12777. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12778. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12779. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12780. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12781. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12782. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12783. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12784. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12785. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12786. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12787. // Infos
  12788. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12789. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12790. if (rendererInfo != null) {
  12791. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12792. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12793. }
  12794. if (!this._glVendor) {
  12795. this._glVendor = "Unknown vendor";
  12796. }
  12797. if (!this._glRenderer) {
  12798. this._glRenderer = "Unknown renderer";
  12799. }
  12800. // Constants
  12801. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12802. if (this._gl.RGBA16F !== 0x881A) {
  12803. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12804. }
  12805. if (this._gl.RGBA32F !== 0x8814) {
  12806. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12807. }
  12808. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12809. this._gl.DEPTH24_STENCIL8 = 35056;
  12810. }
  12811. // Extensions
  12812. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12813. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12814. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12815. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12816. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12817. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12818. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12819. 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');
  12820. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12821. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12822. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12823. this._caps.highPrecisionShaderSupported = true;
  12824. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12825. if (this._caps.timerQuery) {
  12826. if (this._webGLVersion === 1) {
  12827. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12828. }
  12829. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12830. }
  12831. // Checks if some of the format renders first to allow the use of webgl inspector.
  12832. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12833. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12834. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12835. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12836. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12837. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12838. if (this._webGLVersion > 1) {
  12839. this._gl.HALF_FLOAT_OES = 0x140B;
  12840. }
  12841. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12842. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12843. // Draw buffers
  12844. if (this._webGLVersion > 1) {
  12845. this._caps.drawBuffersExtension = true;
  12846. }
  12847. else {
  12848. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12849. if (drawBuffersExtension !== null) {
  12850. this._caps.drawBuffersExtension = true;
  12851. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12852. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12853. for (var i = 0; i < 16; i++) {
  12854. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12855. }
  12856. }
  12857. else {
  12858. this._caps.drawBuffersExtension = false;
  12859. }
  12860. }
  12861. // Depth Texture
  12862. if (this._webGLVersion > 1) {
  12863. this._caps.depthTextureExtension = true;
  12864. }
  12865. else {
  12866. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12867. if (depthTextureExtension != null) {
  12868. this._caps.depthTextureExtension = true;
  12869. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12870. }
  12871. }
  12872. // Vertex array object
  12873. if (this._webGLVersion > 1) {
  12874. this._caps.vertexArrayObject = true;
  12875. }
  12876. else {
  12877. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12878. if (vertexArrayObjectExtension != null) {
  12879. this._caps.vertexArrayObject = true;
  12880. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12881. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12882. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12883. }
  12884. else {
  12885. this._caps.vertexArrayObject = false;
  12886. }
  12887. }
  12888. // Instances count
  12889. if (this._webGLVersion > 1) {
  12890. this._caps.instancedArrays = true;
  12891. }
  12892. else {
  12893. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12894. if (instanceExtension != null) {
  12895. this._caps.instancedArrays = true;
  12896. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12897. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12898. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12899. }
  12900. else {
  12901. this._caps.instancedArrays = false;
  12902. }
  12903. }
  12904. // Intelligently add supported compressed formats in order to check for.
  12905. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12906. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12907. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12908. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12909. if (this._caps.astc) {
  12910. this.texturesSupported.push('-astc.ktx');
  12911. }
  12912. if (this._caps.s3tc) {
  12913. this.texturesSupported.push('-dxt.ktx');
  12914. }
  12915. if (this._caps.pvrtc) {
  12916. this.texturesSupported.push('-pvrtc.ktx');
  12917. }
  12918. if (this._caps.etc2) {
  12919. this.texturesSupported.push('-etc2.ktx');
  12920. }
  12921. if (this._caps.etc1) {
  12922. this.texturesSupported.push('-etc1.ktx');
  12923. }
  12924. if (this._gl.getShaderPrecisionFormat) {
  12925. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12926. if (highp) {
  12927. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12928. }
  12929. }
  12930. // Depth buffer
  12931. this.setDepthBuffer(true);
  12932. this.setDepthFunctionToLessOrEqual();
  12933. this.setDepthWrite(true);
  12934. // Texture maps
  12935. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12936. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12937. this._nextFreeTextureSlots.push(slot);
  12938. }
  12939. };
  12940. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12941. /**
  12942. * Gets version of the current webGL context
  12943. */
  12944. get: function () {
  12945. return this._webGLVersion;
  12946. },
  12947. enumerable: true,
  12948. configurable: true
  12949. });
  12950. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12951. /**
  12952. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12953. */
  12954. get: function () {
  12955. return this._isStencilEnable;
  12956. },
  12957. enumerable: true,
  12958. configurable: true
  12959. });
  12960. Engine.prototype._prepareWorkingCanvas = function () {
  12961. if (this._workingCanvas) {
  12962. return;
  12963. }
  12964. this._workingCanvas = document.createElement("canvas");
  12965. var context = this._workingCanvas.getContext("2d");
  12966. if (context) {
  12967. this._workingContext = context;
  12968. }
  12969. };
  12970. /**
  12971. * Reset the texture cache to empty state
  12972. */
  12973. Engine.prototype.resetTextureCache = function () {
  12974. for (var key in this._boundTexturesCache) {
  12975. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12976. continue;
  12977. }
  12978. var boundTexture = this._boundTexturesCache[key];
  12979. if (boundTexture) {
  12980. this._removeDesignatedSlot(boundTexture);
  12981. }
  12982. this._boundTexturesCache[key] = null;
  12983. }
  12984. if (!this.disableTextureBindingOptimization) {
  12985. this._nextFreeTextureSlots = [];
  12986. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12987. this._nextFreeTextureSlots.push(slot);
  12988. }
  12989. }
  12990. this._currentTextureChannel = -1;
  12991. };
  12992. /**
  12993. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12994. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12995. * @returns true if engine is in deterministic lock step mode
  12996. */
  12997. Engine.prototype.isDeterministicLockStep = function () {
  12998. return this._deterministicLockstep;
  12999. };
  13000. /**
  13001. * Gets the max steps when engine is running in deterministic lock step
  13002. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  13003. * @returns the max steps
  13004. */
  13005. Engine.prototype.getLockstepMaxSteps = function () {
  13006. return this._lockstepMaxSteps;
  13007. };
  13008. /**
  13009. * Gets an object containing information about the current webGL context
  13010. * @returns an object containing the vender, the renderer and the version of the current webGL context
  13011. */
  13012. Engine.prototype.getGlInfo = function () {
  13013. return {
  13014. vendor: this._glVendor,
  13015. renderer: this._glRenderer,
  13016. version: this._glVersion
  13017. };
  13018. };
  13019. /**
  13020. * Gets current aspect ratio
  13021. * @param camera defines the camera to use to get the aspect ratio
  13022. * @param useScreen defines if screen size must be used (or the current render target if any)
  13023. * @returns a number defining the aspect ratio
  13024. */
  13025. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  13026. if (useScreen === void 0) { useScreen = false; }
  13027. var viewport = camera.viewport;
  13028. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  13029. };
  13030. /**
  13031. * Gets current screen aspect ratio
  13032. * @returns a number defining the aspect ratio
  13033. */
  13034. Engine.prototype.getScreenAspectRatio = function () {
  13035. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  13036. };
  13037. /**
  13038. * Gets the current render width
  13039. * @param useScreen defines if screen size must be used (or the current render target if any)
  13040. * @returns a number defining the current render width
  13041. */
  13042. Engine.prototype.getRenderWidth = function (useScreen) {
  13043. if (useScreen === void 0) { useScreen = false; }
  13044. if (!useScreen && this._currentRenderTarget) {
  13045. return this._currentRenderTarget.width;
  13046. }
  13047. return this._gl.drawingBufferWidth;
  13048. };
  13049. /**
  13050. * Gets the current render height
  13051. * @param useScreen defines if screen size must be used (or the current render target if any)
  13052. * @returns a number defining the current render height
  13053. */
  13054. Engine.prototype.getRenderHeight = function (useScreen) {
  13055. if (useScreen === void 0) { useScreen = false; }
  13056. if (!useScreen && this._currentRenderTarget) {
  13057. return this._currentRenderTarget.height;
  13058. }
  13059. return this._gl.drawingBufferHeight;
  13060. };
  13061. /**
  13062. * Gets the HTML canvas attached with the current webGL context
  13063. * @returns a HTML canvas
  13064. */
  13065. Engine.prototype.getRenderingCanvas = function () {
  13066. return this._renderingCanvas;
  13067. };
  13068. /**
  13069. * Gets the client rect of the HTML canvas attached with the current webGL context
  13070. * @returns a client rectanglee
  13071. */
  13072. Engine.prototype.getRenderingCanvasClientRect = function () {
  13073. if (!this._renderingCanvas) {
  13074. return null;
  13075. }
  13076. return this._renderingCanvas.getBoundingClientRect();
  13077. };
  13078. /**
  13079. * Defines the hardware scaling level.
  13080. * By default the hardware scaling level is computed from the window device ratio.
  13081. * 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.
  13082. * @param level defines the level to use
  13083. */
  13084. Engine.prototype.setHardwareScalingLevel = function (level) {
  13085. this._hardwareScalingLevel = level;
  13086. this.resize();
  13087. };
  13088. /**
  13089. * Gets the current hardware scaling level.
  13090. * By default the hardware scaling level is computed from the window device ratio.
  13091. * 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.
  13092. * @returns a number indicating the current hardware scaling level
  13093. */
  13094. Engine.prototype.getHardwareScalingLevel = function () {
  13095. return this._hardwareScalingLevel;
  13096. };
  13097. /**
  13098. * Gets the list of loaded textures
  13099. * @returns an array containing all loaded textures
  13100. */
  13101. Engine.prototype.getLoadedTexturesCache = function () {
  13102. return this._internalTexturesCache;
  13103. };
  13104. /**
  13105. * Gets the object containing all engine capabilities
  13106. * @returns the EngineCapabilities object
  13107. */
  13108. Engine.prototype.getCaps = function () {
  13109. return this._caps;
  13110. };
  13111. Object.defineProperty(Engine.prototype, "drawCalls", {
  13112. /** @hidden */
  13113. get: function () {
  13114. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  13115. return 0;
  13116. },
  13117. enumerable: true,
  13118. configurable: true
  13119. });
  13120. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  13121. /** @hidden */
  13122. get: function () {
  13123. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  13124. return null;
  13125. },
  13126. enumerable: true,
  13127. configurable: true
  13128. });
  13129. /**
  13130. * Gets the current depth function
  13131. * @returns a number defining the depth function
  13132. */
  13133. Engine.prototype.getDepthFunction = function () {
  13134. return this._depthCullingState.depthFunc;
  13135. };
  13136. /**
  13137. * Sets the current depth function
  13138. * @param depthFunc defines the function to use
  13139. */
  13140. Engine.prototype.setDepthFunction = function (depthFunc) {
  13141. this._depthCullingState.depthFunc = depthFunc;
  13142. };
  13143. /**
  13144. * Sets the current depth function to GREATER
  13145. */
  13146. Engine.prototype.setDepthFunctionToGreater = function () {
  13147. this._depthCullingState.depthFunc = this._gl.GREATER;
  13148. };
  13149. /**
  13150. * Sets the current depth function to GEQUAL
  13151. */
  13152. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  13153. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  13154. };
  13155. /**
  13156. * Sets the current depth function to LESS
  13157. */
  13158. Engine.prototype.setDepthFunctionToLess = function () {
  13159. this._depthCullingState.depthFunc = this._gl.LESS;
  13160. };
  13161. /**
  13162. * Sets the current depth function to LEQUAL
  13163. */
  13164. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  13165. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  13166. };
  13167. /**
  13168. * Gets a boolean indicating if stencil buffer is enabled
  13169. * @returns the current stencil buffer state
  13170. */
  13171. Engine.prototype.getStencilBuffer = function () {
  13172. return this._stencilState.stencilTest;
  13173. };
  13174. /**
  13175. * Enable or disable the stencil buffer
  13176. * @param enable defines if the stencil buffer must be enabled or disabled
  13177. */
  13178. Engine.prototype.setStencilBuffer = function (enable) {
  13179. this._stencilState.stencilTest = enable;
  13180. };
  13181. /**
  13182. * Gets the current stencil mask
  13183. * @returns a number defining the new stencil mask to use
  13184. */
  13185. Engine.prototype.getStencilMask = function () {
  13186. return this._stencilState.stencilMask;
  13187. };
  13188. /**
  13189. * Sets the current stencil mask
  13190. * @param mask defines the new stencil mask to use
  13191. */
  13192. Engine.prototype.setStencilMask = function (mask) {
  13193. this._stencilState.stencilMask = mask;
  13194. };
  13195. /**
  13196. * Gets the current stencil function
  13197. * @returns a number defining the stencil function to use
  13198. */
  13199. Engine.prototype.getStencilFunction = function () {
  13200. return this._stencilState.stencilFunc;
  13201. };
  13202. /**
  13203. * Gets the current stencil reference value
  13204. * @returns a number defining the stencil reference value to use
  13205. */
  13206. Engine.prototype.getStencilFunctionReference = function () {
  13207. return this._stencilState.stencilFuncRef;
  13208. };
  13209. /**
  13210. * Gets the current stencil mask
  13211. * @returns a number defining the stencil mask to use
  13212. */
  13213. Engine.prototype.getStencilFunctionMask = function () {
  13214. return this._stencilState.stencilFuncMask;
  13215. };
  13216. /**
  13217. * Sets the current stencil function
  13218. * @param stencilFunc defines the new stencil function to use
  13219. */
  13220. Engine.prototype.setStencilFunction = function (stencilFunc) {
  13221. this._stencilState.stencilFunc = stencilFunc;
  13222. };
  13223. /**
  13224. * Sets the current stencil reference
  13225. * @param reference defines the new stencil reference to use
  13226. */
  13227. Engine.prototype.setStencilFunctionReference = function (reference) {
  13228. this._stencilState.stencilFuncRef = reference;
  13229. };
  13230. /**
  13231. * Sets the current stencil mask
  13232. * @param mask defines the new stencil mask to use
  13233. */
  13234. Engine.prototype.setStencilFunctionMask = function (mask) {
  13235. this._stencilState.stencilFuncMask = mask;
  13236. };
  13237. /**
  13238. * Gets the current stencil operation when stencil fails
  13239. * @returns a number defining stencil operation to use when stencil fails
  13240. */
  13241. Engine.prototype.getStencilOperationFail = function () {
  13242. return this._stencilState.stencilOpStencilFail;
  13243. };
  13244. /**
  13245. * Gets the current stencil operation when depth fails
  13246. * @returns a number defining stencil operation to use when depth fails
  13247. */
  13248. Engine.prototype.getStencilOperationDepthFail = function () {
  13249. return this._stencilState.stencilOpDepthFail;
  13250. };
  13251. /**
  13252. * Gets the current stencil operation when stencil passes
  13253. * @returns a number defining stencil operation to use when stencil passes
  13254. */
  13255. Engine.prototype.getStencilOperationPass = function () {
  13256. return this._stencilState.stencilOpStencilDepthPass;
  13257. };
  13258. /**
  13259. * Sets the stencil operation to use when stencil fails
  13260. * @param operation defines the stencil operation to use when stencil fails
  13261. */
  13262. Engine.prototype.setStencilOperationFail = function (operation) {
  13263. this._stencilState.stencilOpStencilFail = operation;
  13264. };
  13265. /**
  13266. * Sets the stencil operation to use when depth fails
  13267. * @param operation defines the stencil operation to use when depth fails
  13268. */
  13269. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  13270. this._stencilState.stencilOpDepthFail = operation;
  13271. };
  13272. /**
  13273. * Sets the stencil operation to use when stencil passes
  13274. * @param operation defines the stencil operation to use when stencil passes
  13275. */
  13276. Engine.prototype.setStencilOperationPass = function (operation) {
  13277. this._stencilState.stencilOpStencilDepthPass = operation;
  13278. };
  13279. /**
  13280. * Sets a boolean indicating if the dithering state is enabled or disabled
  13281. * @param value defines the dithering state
  13282. */
  13283. Engine.prototype.setDitheringState = function (value) {
  13284. if (value) {
  13285. this._gl.enable(this._gl.DITHER);
  13286. }
  13287. else {
  13288. this._gl.disable(this._gl.DITHER);
  13289. }
  13290. };
  13291. /**
  13292. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  13293. * @param value defines the rasterizer state
  13294. */
  13295. Engine.prototype.setRasterizerState = function (value) {
  13296. if (value) {
  13297. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  13298. }
  13299. else {
  13300. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  13301. }
  13302. };
  13303. /**
  13304. * stop executing a render loop function and remove it from the execution array
  13305. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  13306. */
  13307. Engine.prototype.stopRenderLoop = function (renderFunction) {
  13308. if (!renderFunction) {
  13309. this._activeRenderLoops = [];
  13310. return;
  13311. }
  13312. var index = this._activeRenderLoops.indexOf(renderFunction);
  13313. if (index >= 0) {
  13314. this._activeRenderLoops.splice(index, 1);
  13315. }
  13316. };
  13317. /** @hidden */
  13318. Engine.prototype._renderLoop = function () {
  13319. if (!this._contextWasLost) {
  13320. var shouldRender = true;
  13321. if (!this.renderEvenInBackground && this._windowIsBackground) {
  13322. shouldRender = false;
  13323. }
  13324. if (shouldRender) {
  13325. // Start new frame
  13326. this.beginFrame();
  13327. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  13328. var renderFunction = this._activeRenderLoops[index];
  13329. renderFunction();
  13330. }
  13331. // Present
  13332. this.endFrame();
  13333. }
  13334. }
  13335. if (this._activeRenderLoops.length > 0) {
  13336. // Register new frame
  13337. var requester = null;
  13338. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13339. requester = this._vrDisplay;
  13340. }
  13341. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  13342. }
  13343. else {
  13344. this._renderingQueueLaunched = false;
  13345. }
  13346. };
  13347. /**
  13348. * Register and execute a render loop. The engine can have more than one render function
  13349. * @param renderFunction defines the function to continuously execute
  13350. */
  13351. Engine.prototype.runRenderLoop = function (renderFunction) {
  13352. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  13353. return;
  13354. }
  13355. this._activeRenderLoops.push(renderFunction);
  13356. if (!this._renderingQueueLaunched) {
  13357. this._renderingQueueLaunched = true;
  13358. this._bindedRenderFunction = this._renderLoop.bind(this);
  13359. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13360. }
  13361. };
  13362. /**
  13363. * Toggle full screen mode
  13364. * @param requestPointerLock defines if a pointer lock should be requested from the user
  13365. */
  13366. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  13367. if (this.isFullscreen) {
  13368. BABYLON.Tools.ExitFullscreen();
  13369. }
  13370. else {
  13371. this._pointerLockRequested = requestPointerLock;
  13372. if (this._renderingCanvas) {
  13373. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  13374. }
  13375. }
  13376. };
  13377. /**
  13378. * Clear the current render buffer or the current render target (if any is set up)
  13379. * @param color defines the color to use
  13380. * @param backBuffer defines if the back buffer must be cleared
  13381. * @param depth defines if the depth buffer must be cleared
  13382. * @param stencil defines if the stencil buffer must be cleared
  13383. */
  13384. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  13385. if (stencil === void 0) { stencil = false; }
  13386. this.applyStates();
  13387. var mode = 0;
  13388. if (backBuffer && color) {
  13389. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  13390. mode |= this._gl.COLOR_BUFFER_BIT;
  13391. }
  13392. if (depth) {
  13393. this._gl.clearDepth(1.0);
  13394. mode |= this._gl.DEPTH_BUFFER_BIT;
  13395. }
  13396. if (stencil) {
  13397. this._gl.clearStencil(0);
  13398. mode |= this._gl.STENCIL_BUFFER_BIT;
  13399. }
  13400. this._gl.clear(mode);
  13401. };
  13402. /**
  13403. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  13404. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  13405. * @param y defines the y-coordinate of the corner of the clear rectangle
  13406. * @param width defines the width of the clear rectangle
  13407. * @param height defines the height of the clear rectangle
  13408. * @param clearColor defines the clear color
  13409. */
  13410. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  13411. var gl = this._gl;
  13412. // Save state
  13413. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  13414. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  13415. // Change state
  13416. gl.enable(gl.SCISSOR_TEST);
  13417. gl.scissor(x, y, width, height);
  13418. // Clear
  13419. this.clear(clearColor, true, true, true);
  13420. // Restore state
  13421. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  13422. if (curScissor === true) {
  13423. gl.enable(gl.SCISSOR_TEST);
  13424. }
  13425. else {
  13426. gl.disable(gl.SCISSOR_TEST);
  13427. }
  13428. };
  13429. /** @hidden */
  13430. Engine.prototype._viewport = function (x, y, width, height) {
  13431. if (x !== this._viewportCached.x ||
  13432. y !== this._viewportCached.y ||
  13433. width !== this._viewportCached.z ||
  13434. height !== this._viewportCached.w) {
  13435. this._viewportCached.x = x;
  13436. this._viewportCached.y = y;
  13437. this._viewportCached.z = width;
  13438. this._viewportCached.w = height;
  13439. this._gl.viewport(x, y, width, height);
  13440. }
  13441. };
  13442. /**
  13443. * Set the WebGL's viewport
  13444. * @param viewport defines the viewport element to be used
  13445. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  13446. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  13447. */
  13448. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  13449. var width = requiredWidth || this.getRenderWidth();
  13450. var height = requiredHeight || this.getRenderHeight();
  13451. var x = viewport.x || 0;
  13452. var y = viewport.y || 0;
  13453. this._cachedViewport = viewport;
  13454. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  13455. };
  13456. /**
  13457. * Directly set the WebGL Viewport
  13458. * @param x defines the x coordinate of the viewport (in screen space)
  13459. * @param y defines the y coordinate of the viewport (in screen space)
  13460. * @param width defines the width of the viewport (in screen space)
  13461. * @param height defines the height of the viewport (in screen space)
  13462. * @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
  13463. */
  13464. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  13465. var currentViewport = this._cachedViewport;
  13466. this._cachedViewport = null;
  13467. this._viewport(x, y, width, height);
  13468. return currentViewport;
  13469. };
  13470. /**
  13471. * Begin a new frame
  13472. */
  13473. Engine.prototype.beginFrame = function () {
  13474. this.onBeginFrameObservable.notifyObservers(this);
  13475. this._measureFps();
  13476. };
  13477. /**
  13478. * Enf the current frame
  13479. */
  13480. Engine.prototype.endFrame = function () {
  13481. // Force a flush in case we are using a bad OS.
  13482. if (this._badOS) {
  13483. this.flushFramebuffer();
  13484. }
  13485. // Submit frame to the vr device, if enabled
  13486. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13487. // TODO: We should only submit the frame if we read frameData successfully.
  13488. this._vrDisplay.submitFrame();
  13489. }
  13490. this.onEndFrameObservable.notifyObservers(this);
  13491. };
  13492. /**
  13493. * Resize the view according to the canvas' size
  13494. */
  13495. Engine.prototype.resize = function () {
  13496. // We're not resizing the size of the canvas while in VR mode & presenting
  13497. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13498. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13499. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13500. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13501. }
  13502. };
  13503. /**
  13504. * Force a specific size of the canvas
  13505. * @param width defines the new canvas' width
  13506. * @param height defines the new canvas' height
  13507. */
  13508. Engine.prototype.setSize = function (width, height) {
  13509. if (!this._renderingCanvas) {
  13510. return;
  13511. }
  13512. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13513. return;
  13514. }
  13515. this._renderingCanvas.width = width;
  13516. this._renderingCanvas.height = height;
  13517. for (var index = 0; index < this.scenes.length; index++) {
  13518. var scene = this.scenes[index];
  13519. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13520. var cam = scene.cameras[camIndex];
  13521. cam._currentRenderId = 0;
  13522. }
  13523. }
  13524. if (this.onResizeObservable.hasObservers) {
  13525. this.onResizeObservable.notifyObservers(this);
  13526. }
  13527. };
  13528. // WebVR functions
  13529. /**
  13530. * Gets a boolean indicating if a webVR device was detected
  13531. * @returns true if a webVR device was detected
  13532. */
  13533. Engine.prototype.isVRDevicePresent = function () {
  13534. return !!this._vrDisplay;
  13535. };
  13536. /**
  13537. * Gets the current webVR device
  13538. * @returns the current webVR device (or null)
  13539. */
  13540. Engine.prototype.getVRDevice = function () {
  13541. return this._vrDisplay;
  13542. };
  13543. /**
  13544. * Initializes a webVR display and starts listening to display change events
  13545. * The onVRDisplayChangedObservable will be notified upon these changes
  13546. * @returns The onVRDisplayChangedObservable
  13547. */
  13548. Engine.prototype.initWebVR = function () {
  13549. this.initWebVRAsync();
  13550. return this.onVRDisplayChangedObservable;
  13551. };
  13552. /**
  13553. * Initializes a webVR display and starts listening to display change events
  13554. * The onVRDisplayChangedObservable will be notified upon these changes
  13555. * @returns A promise containing a VRDisplay and if vr is supported
  13556. */
  13557. Engine.prototype.initWebVRAsync = function () {
  13558. var _this = this;
  13559. var notifyObservers = function () {
  13560. var eventArgs = {
  13561. vrDisplay: _this._vrDisplay,
  13562. vrSupported: _this._vrSupported
  13563. };
  13564. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13565. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13566. };
  13567. if (!this._onVrDisplayConnect) {
  13568. this._onVrDisplayConnect = function (event) {
  13569. _this._vrDisplay = event.display;
  13570. notifyObservers();
  13571. };
  13572. this._onVrDisplayDisconnect = function () {
  13573. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13574. _this._vrDisplay = undefined;
  13575. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13576. notifyObservers();
  13577. };
  13578. this._onVrDisplayPresentChange = function () {
  13579. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13580. };
  13581. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13582. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13583. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13584. }
  13585. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13586. this._webVRInitPromise.then(notifyObservers);
  13587. return this._webVRInitPromise;
  13588. };
  13589. /**
  13590. * Call this function to switch to webVR mode
  13591. * Will do nothing if webVR is not supported or if there is no webVR device
  13592. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13593. */
  13594. Engine.prototype.enableVR = function () {
  13595. var _this = this;
  13596. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13597. var onResolved = function () {
  13598. _this.onVRRequestPresentComplete.notifyObservers(true);
  13599. _this._onVRFullScreenTriggered();
  13600. };
  13601. var onRejected = function () {
  13602. _this.onVRRequestPresentComplete.notifyObservers(false);
  13603. };
  13604. this.onVRRequestPresentStart.notifyObservers(this);
  13605. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13606. }
  13607. };
  13608. /**
  13609. * Call this function to leave webVR mode
  13610. * Will do nothing if webVR is not supported or if there is no webVR device
  13611. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13612. */
  13613. Engine.prototype.disableVR = function () {
  13614. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13615. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13616. }
  13617. };
  13618. Engine.prototype._getVRDisplaysAsync = function () {
  13619. var _this = this;
  13620. return new Promise(function (res, rej) {
  13621. if (navigator.getVRDisplays) {
  13622. navigator.getVRDisplays().then(function (devices) {
  13623. _this._vrSupported = true;
  13624. // note that devices may actually be an empty array. This is fine;
  13625. // we expect this._vrDisplay to be undefined in this case.
  13626. _this._vrDisplay = devices[0];
  13627. res({
  13628. vrDisplay: _this._vrDisplay,
  13629. vrSupported: _this._vrSupported
  13630. });
  13631. });
  13632. }
  13633. else {
  13634. _this._vrDisplay = undefined;
  13635. _this._vrSupported = false;
  13636. res({
  13637. vrDisplay: _this._vrDisplay,
  13638. vrSupported: _this._vrSupported
  13639. });
  13640. }
  13641. });
  13642. };
  13643. /**
  13644. * Binds the frame buffer to the specified texture.
  13645. * @param texture The texture to render to or null for the default canvas
  13646. * @param faceIndex The face of the texture to render to in case of cube texture
  13647. * @param requiredWidth The width of the target to render to
  13648. * @param requiredHeight The height of the target to render to
  13649. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13650. * @param depthStencilTexture The depth stencil texture to use to render
  13651. * @param lodLevel defines le lod level to bind to the frame buffer
  13652. */
  13653. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13654. if (lodLevel === void 0) { lodLevel = 0; }
  13655. if (this._currentRenderTarget) {
  13656. this.unBindFramebuffer(this._currentRenderTarget);
  13657. }
  13658. this._currentRenderTarget = texture;
  13659. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13660. var gl = this._gl;
  13661. if (texture.isCube) {
  13662. if (faceIndex === undefined) {
  13663. faceIndex = 0;
  13664. }
  13665. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13666. if (depthStencilTexture) {
  13667. if (depthStencilTexture._generateStencilBuffer) {
  13668. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13669. }
  13670. else {
  13671. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13672. }
  13673. }
  13674. }
  13675. if (this._cachedViewport && !forceFullscreenViewport) {
  13676. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13677. }
  13678. else {
  13679. if (!requiredWidth) {
  13680. requiredWidth = texture.width;
  13681. if (lodLevel) {
  13682. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13683. }
  13684. }
  13685. if (!requiredHeight) {
  13686. requiredHeight = texture.height;
  13687. if (lodLevel) {
  13688. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13689. }
  13690. }
  13691. this._viewport(0, 0, requiredWidth, requiredHeight);
  13692. }
  13693. this.wipeCaches();
  13694. };
  13695. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13696. if (this._currentFramebuffer !== framebuffer) {
  13697. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13698. this._currentFramebuffer = framebuffer;
  13699. }
  13700. };
  13701. /**
  13702. * Unbind the current render target texture from the webGL context
  13703. * @param texture defines the render target texture to unbind
  13704. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13705. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13706. */
  13707. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13708. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13709. this._currentRenderTarget = null;
  13710. // If MSAA, we need to bitblt back to main texture
  13711. var gl = this._gl;
  13712. if (texture._MSAAFramebuffer) {
  13713. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13714. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13715. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13716. }
  13717. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13718. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13719. gl.generateMipmap(gl.TEXTURE_2D);
  13720. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13721. }
  13722. if (onBeforeUnbind) {
  13723. if (texture._MSAAFramebuffer) {
  13724. // Bind the correct framebuffer
  13725. this.bindUnboundFramebuffer(texture._framebuffer);
  13726. }
  13727. onBeforeUnbind();
  13728. }
  13729. this.bindUnboundFramebuffer(null);
  13730. };
  13731. /**
  13732. * Unbind a list of render target textures from the webGL context
  13733. * This is used only when drawBuffer extension or webGL2 are active
  13734. * @param textures defines the render target textures to unbind
  13735. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13736. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13737. */
  13738. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13739. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13740. this._currentRenderTarget = null;
  13741. // If MSAA, we need to bitblt back to main texture
  13742. var gl = this._gl;
  13743. if (textures[0]._MSAAFramebuffer) {
  13744. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13745. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13746. var attachments = textures[0]._attachments;
  13747. if (!attachments) {
  13748. attachments = new Array(textures.length);
  13749. textures[0]._attachments = attachments;
  13750. }
  13751. for (var i = 0; i < textures.length; i++) {
  13752. var texture = textures[i];
  13753. for (var j = 0; j < attachments.length; j++) {
  13754. attachments[j] = gl.NONE;
  13755. }
  13756. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13757. gl.readBuffer(attachments[i]);
  13758. gl.drawBuffers(attachments);
  13759. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13760. }
  13761. for (var i = 0; i < attachments.length; i++) {
  13762. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13763. }
  13764. gl.drawBuffers(attachments);
  13765. }
  13766. for (var i = 0; i < textures.length; i++) {
  13767. var texture = textures[i];
  13768. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13769. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13770. gl.generateMipmap(gl.TEXTURE_2D);
  13771. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13772. }
  13773. }
  13774. if (onBeforeUnbind) {
  13775. if (textures[0]._MSAAFramebuffer) {
  13776. // Bind the correct framebuffer
  13777. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13778. }
  13779. onBeforeUnbind();
  13780. }
  13781. this.bindUnboundFramebuffer(null);
  13782. };
  13783. /**
  13784. * Force the mipmap generation for the given render target texture
  13785. * @param texture defines the render target texture to use
  13786. */
  13787. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13788. if (texture.generateMipMaps) {
  13789. var gl = this._gl;
  13790. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13791. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13792. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13793. }
  13794. };
  13795. /**
  13796. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13797. */
  13798. Engine.prototype.flushFramebuffer = function () {
  13799. this._gl.flush();
  13800. };
  13801. /**
  13802. * Unbind the current render target and bind the default framebuffer
  13803. */
  13804. Engine.prototype.restoreDefaultFramebuffer = function () {
  13805. if (this._currentRenderTarget) {
  13806. this.unBindFramebuffer(this._currentRenderTarget);
  13807. }
  13808. else {
  13809. this.bindUnboundFramebuffer(null);
  13810. }
  13811. if (this._cachedViewport) {
  13812. this.setViewport(this._cachedViewport);
  13813. }
  13814. this.wipeCaches();
  13815. };
  13816. // UBOs
  13817. /**
  13818. * Create an uniform buffer
  13819. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13820. * @param elements defines the content of the uniform buffer
  13821. * @returns the webGL uniform buffer
  13822. */
  13823. Engine.prototype.createUniformBuffer = function (elements) {
  13824. var ubo = this._gl.createBuffer();
  13825. if (!ubo) {
  13826. throw new Error("Unable to create uniform buffer");
  13827. }
  13828. this.bindUniformBuffer(ubo);
  13829. if (elements instanceof Float32Array) {
  13830. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13831. }
  13832. else {
  13833. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13834. }
  13835. this.bindUniformBuffer(null);
  13836. ubo.references = 1;
  13837. return ubo;
  13838. };
  13839. /**
  13840. * Create a dynamic uniform buffer
  13841. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13842. * @param elements defines the content of the uniform buffer
  13843. * @returns the webGL uniform buffer
  13844. */
  13845. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13846. var ubo = this._gl.createBuffer();
  13847. if (!ubo) {
  13848. throw new Error("Unable to create dynamic uniform buffer");
  13849. }
  13850. this.bindUniformBuffer(ubo);
  13851. if (elements instanceof Float32Array) {
  13852. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13853. }
  13854. else {
  13855. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13856. }
  13857. this.bindUniformBuffer(null);
  13858. ubo.references = 1;
  13859. return ubo;
  13860. };
  13861. /**
  13862. * Update an existing uniform buffer
  13863. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13864. * @param uniformBuffer defines the target uniform buffer
  13865. * @param elements defines the content to update
  13866. * @param offset defines the offset in the uniform buffer where update should start
  13867. * @param count defines the size of the data to update
  13868. */
  13869. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13870. this.bindUniformBuffer(uniformBuffer);
  13871. if (offset === undefined) {
  13872. offset = 0;
  13873. }
  13874. if (count === undefined) {
  13875. if (elements instanceof Float32Array) {
  13876. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13877. }
  13878. else {
  13879. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13880. }
  13881. }
  13882. else {
  13883. if (elements instanceof Float32Array) {
  13884. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13885. }
  13886. else {
  13887. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13888. }
  13889. }
  13890. this.bindUniformBuffer(null);
  13891. };
  13892. // VBOs
  13893. Engine.prototype._resetVertexBufferBinding = function () {
  13894. this.bindArrayBuffer(null);
  13895. this._cachedVertexBuffers = null;
  13896. };
  13897. /**
  13898. * Creates a vertex buffer
  13899. * @param data the data for the vertex buffer
  13900. * @returns the new WebGL static buffer
  13901. */
  13902. Engine.prototype.createVertexBuffer = function (data) {
  13903. var vbo = this._gl.createBuffer();
  13904. if (!vbo) {
  13905. throw new Error("Unable to create vertex buffer");
  13906. }
  13907. this.bindArrayBuffer(vbo);
  13908. if (data instanceof Array) {
  13909. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13910. }
  13911. else {
  13912. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13913. }
  13914. this._resetVertexBufferBinding();
  13915. vbo.references = 1;
  13916. return vbo;
  13917. };
  13918. /**
  13919. * Creates a dynamic vertex buffer
  13920. * @param data the data for the dynamic vertex buffer
  13921. * @returns the new WebGL dynamic buffer
  13922. */
  13923. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13924. var vbo = this._gl.createBuffer();
  13925. if (!vbo) {
  13926. throw new Error("Unable to create dynamic vertex buffer");
  13927. }
  13928. this.bindArrayBuffer(vbo);
  13929. if (data instanceof Array) {
  13930. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13931. }
  13932. else {
  13933. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13934. }
  13935. this._resetVertexBufferBinding();
  13936. vbo.references = 1;
  13937. return vbo;
  13938. };
  13939. /**
  13940. * Update a dynamic index buffer
  13941. * @param indexBuffer defines the target index buffer
  13942. * @param indices defines the data to update
  13943. * @param offset defines the offset in the target index buffer where update should start
  13944. */
  13945. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13946. if (offset === void 0) { offset = 0; }
  13947. // Force cache update
  13948. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13949. this.bindIndexBuffer(indexBuffer);
  13950. var arrayBuffer;
  13951. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13952. arrayBuffer = indices;
  13953. }
  13954. else {
  13955. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13956. }
  13957. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13958. this._resetIndexBufferBinding();
  13959. };
  13960. /**
  13961. * Updates a dynamic vertex buffer.
  13962. * @param vertexBuffer the vertex buffer to update
  13963. * @param data the data used to update the vertex buffer
  13964. * @param byteOffset the byte offset of the data
  13965. * @param byteLength the byte length of the data
  13966. */
  13967. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13968. this.bindArrayBuffer(vertexBuffer);
  13969. if (byteOffset === undefined) {
  13970. byteOffset = 0;
  13971. }
  13972. if (byteLength === undefined) {
  13973. if (data instanceof Array) {
  13974. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13975. }
  13976. else {
  13977. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13978. }
  13979. }
  13980. else {
  13981. if (data instanceof Array) {
  13982. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13983. }
  13984. else {
  13985. if (data instanceof ArrayBuffer) {
  13986. data = new Uint8Array(data, byteOffset, byteLength);
  13987. }
  13988. else {
  13989. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13990. }
  13991. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13992. }
  13993. }
  13994. this._resetVertexBufferBinding();
  13995. };
  13996. Engine.prototype._resetIndexBufferBinding = function () {
  13997. this.bindIndexBuffer(null);
  13998. this._cachedIndexBuffer = null;
  13999. };
  14000. /**
  14001. * Creates a new index buffer
  14002. * @param indices defines the content of the index buffer
  14003. * @param updatable defines if the index buffer must be updatable
  14004. * @returns a new webGL buffer
  14005. */
  14006. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  14007. var vbo = this._gl.createBuffer();
  14008. if (!vbo) {
  14009. throw new Error("Unable to create index buffer");
  14010. }
  14011. this.bindIndexBuffer(vbo);
  14012. // Check for 32 bits indices
  14013. var arrayBuffer;
  14014. var need32Bits = false;
  14015. if (indices instanceof Uint16Array) {
  14016. arrayBuffer = indices;
  14017. }
  14018. else {
  14019. //check 32 bit support
  14020. if (this._caps.uintIndices) {
  14021. if (indices instanceof Uint32Array) {
  14022. arrayBuffer = indices;
  14023. need32Bits = true;
  14024. }
  14025. else {
  14026. //number[] or Int32Array, check if 32 bit is necessary
  14027. for (var index = 0; index < indices.length; index++) {
  14028. if (indices[index] > 65535) {
  14029. need32Bits = true;
  14030. break;
  14031. }
  14032. }
  14033. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  14034. }
  14035. }
  14036. else {
  14037. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  14038. arrayBuffer = new Uint16Array(indices);
  14039. }
  14040. }
  14041. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  14042. this._resetIndexBufferBinding();
  14043. vbo.references = 1;
  14044. vbo.is32Bits = need32Bits;
  14045. return vbo;
  14046. };
  14047. /**
  14048. * Bind a webGL buffer to the webGL context
  14049. * @param buffer defines the buffer to bind
  14050. */
  14051. Engine.prototype.bindArrayBuffer = function (buffer) {
  14052. if (!this._vaoRecordInProgress) {
  14053. this._unbindVertexArrayObject();
  14054. }
  14055. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  14056. };
  14057. /**
  14058. * Bind an uniform buffer to the current webGL context
  14059. * @param buffer defines the buffer to bind
  14060. */
  14061. Engine.prototype.bindUniformBuffer = function (buffer) {
  14062. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  14063. };
  14064. /**
  14065. * Bind a buffer to the current webGL context at a given location
  14066. * @param buffer defines the buffer to bind
  14067. * @param location defines the index where to bind the buffer
  14068. */
  14069. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  14070. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  14071. };
  14072. /**
  14073. * Bind a specific block at a given index in a specific shader program
  14074. * @param shaderProgram defines the shader program
  14075. * @param blockName defines the block name
  14076. * @param index defines the index where to bind the block
  14077. */
  14078. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  14079. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  14080. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  14081. };
  14082. Engine.prototype.bindIndexBuffer = function (buffer) {
  14083. if (!this._vaoRecordInProgress) {
  14084. this._unbindVertexArrayObject();
  14085. }
  14086. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  14087. };
  14088. Engine.prototype.bindBuffer = function (buffer, target) {
  14089. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  14090. this._gl.bindBuffer(target, buffer);
  14091. this._currentBoundBuffer[target] = buffer;
  14092. }
  14093. };
  14094. /**
  14095. * update the bound buffer with the given data
  14096. * @param data defines the data to update
  14097. */
  14098. Engine.prototype.updateArrayBuffer = function (data) {
  14099. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14100. };
  14101. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  14102. var pointer = this._currentBufferPointers[indx];
  14103. var changed = false;
  14104. if (!pointer.active) {
  14105. changed = true;
  14106. pointer.active = true;
  14107. pointer.index = indx;
  14108. pointer.size = size;
  14109. pointer.type = type;
  14110. pointer.normalized = normalized;
  14111. pointer.stride = stride;
  14112. pointer.offset = offset;
  14113. pointer.buffer = buffer;
  14114. }
  14115. else {
  14116. if (pointer.buffer !== buffer) {
  14117. pointer.buffer = buffer;
  14118. changed = true;
  14119. }
  14120. if (pointer.size !== size) {
  14121. pointer.size = size;
  14122. changed = true;
  14123. }
  14124. if (pointer.type !== type) {
  14125. pointer.type = type;
  14126. changed = true;
  14127. }
  14128. if (pointer.normalized !== normalized) {
  14129. pointer.normalized = normalized;
  14130. changed = true;
  14131. }
  14132. if (pointer.stride !== stride) {
  14133. pointer.stride = stride;
  14134. changed = true;
  14135. }
  14136. if (pointer.offset !== offset) {
  14137. pointer.offset = offset;
  14138. changed = true;
  14139. }
  14140. }
  14141. if (changed || this._vaoRecordInProgress) {
  14142. this.bindArrayBuffer(buffer);
  14143. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  14144. }
  14145. };
  14146. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  14147. if (indexBuffer == null) {
  14148. return;
  14149. }
  14150. if (this._cachedIndexBuffer !== indexBuffer) {
  14151. this._cachedIndexBuffer = indexBuffer;
  14152. this.bindIndexBuffer(indexBuffer);
  14153. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  14154. }
  14155. };
  14156. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  14157. var attributes = effect.getAttributesNames();
  14158. if (!this._vaoRecordInProgress) {
  14159. this._unbindVertexArrayObject();
  14160. }
  14161. this.unbindAllAttributes();
  14162. for (var index = 0; index < attributes.length; index++) {
  14163. var order = effect.getAttributeLocation(index);
  14164. if (order >= 0) {
  14165. var vertexBuffer = vertexBuffers[attributes[index]];
  14166. if (!vertexBuffer) {
  14167. continue;
  14168. }
  14169. this._gl.enableVertexAttribArray(order);
  14170. if (!this._vaoRecordInProgress) {
  14171. this._vertexAttribArraysEnabled[order] = true;
  14172. }
  14173. var buffer = vertexBuffer.getBuffer();
  14174. if (buffer) {
  14175. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  14176. if (vertexBuffer.getIsInstanced()) {
  14177. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  14178. if (!this._vaoRecordInProgress) {
  14179. this._currentInstanceLocations.push(order);
  14180. this._currentInstanceBuffers.push(buffer);
  14181. }
  14182. }
  14183. }
  14184. }
  14185. }
  14186. };
  14187. /**
  14188. * Records a vertex array object
  14189. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14190. * @param vertexBuffers defines the list of vertex buffers to store
  14191. * @param indexBuffer defines the index buffer to store
  14192. * @param effect defines the effect to store
  14193. * @returns the new vertex array object
  14194. */
  14195. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  14196. var vao = this._gl.createVertexArray();
  14197. this._vaoRecordInProgress = true;
  14198. this._gl.bindVertexArray(vao);
  14199. this._mustWipeVertexAttributes = true;
  14200. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14201. this.bindIndexBuffer(indexBuffer);
  14202. this._vaoRecordInProgress = false;
  14203. this._gl.bindVertexArray(null);
  14204. return vao;
  14205. };
  14206. /**
  14207. * Bind a specific vertex array object
  14208. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14209. * @param vertexArrayObject defines the vertex array object to bind
  14210. * @param indexBuffer defines the index buffer to bind
  14211. */
  14212. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  14213. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  14214. this._cachedVertexArrayObject = vertexArrayObject;
  14215. this._gl.bindVertexArray(vertexArrayObject);
  14216. this._cachedVertexBuffers = null;
  14217. this._cachedIndexBuffer = null;
  14218. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  14219. this._mustWipeVertexAttributes = true;
  14220. }
  14221. };
  14222. /**
  14223. * Bind webGl buffers directly to the webGL context
  14224. * @param vertexBuffer defines the vertex buffer to bind
  14225. * @param indexBuffer defines the index buffer to bind
  14226. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  14227. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  14228. * @param effect defines the effect associated with the vertex buffer
  14229. */
  14230. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  14231. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  14232. this._cachedVertexBuffers = vertexBuffer;
  14233. this._cachedEffectForVertexBuffers = effect;
  14234. var attributesCount = effect.getAttributesCount();
  14235. this._unbindVertexArrayObject();
  14236. this.unbindAllAttributes();
  14237. var offset = 0;
  14238. for (var index = 0; index < attributesCount; index++) {
  14239. if (index < vertexDeclaration.length) {
  14240. var order = effect.getAttributeLocation(index);
  14241. if (order >= 0) {
  14242. this._gl.enableVertexAttribArray(order);
  14243. this._vertexAttribArraysEnabled[order] = true;
  14244. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  14245. }
  14246. offset += vertexDeclaration[index] * 4;
  14247. }
  14248. }
  14249. }
  14250. this._bindIndexBufferWithCache(indexBuffer);
  14251. };
  14252. Engine.prototype._unbindVertexArrayObject = function () {
  14253. if (!this._cachedVertexArrayObject) {
  14254. return;
  14255. }
  14256. this._cachedVertexArrayObject = null;
  14257. this._gl.bindVertexArray(null);
  14258. };
  14259. /**
  14260. * Bind a list of vertex buffers to the webGL context
  14261. * @param vertexBuffers defines the list of vertex buffers to bind
  14262. * @param indexBuffer defines the index buffer to bind
  14263. * @param effect defines the effect associated with the vertex buffers
  14264. */
  14265. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  14266. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  14267. this._cachedVertexBuffers = vertexBuffers;
  14268. this._cachedEffectForVertexBuffers = effect;
  14269. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14270. }
  14271. this._bindIndexBufferWithCache(indexBuffer);
  14272. };
  14273. /**
  14274. * Unbind all instance attributes
  14275. */
  14276. Engine.prototype.unbindInstanceAttributes = function () {
  14277. var boundBuffer;
  14278. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  14279. var instancesBuffer = this._currentInstanceBuffers[i];
  14280. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  14281. boundBuffer = instancesBuffer;
  14282. this.bindArrayBuffer(instancesBuffer);
  14283. }
  14284. var offsetLocation = this._currentInstanceLocations[i];
  14285. this._gl.vertexAttribDivisor(offsetLocation, 0);
  14286. }
  14287. this._currentInstanceBuffers.length = 0;
  14288. this._currentInstanceLocations.length = 0;
  14289. };
  14290. /**
  14291. * Release and free the memory of a vertex array object
  14292. * @param vao defines the vertex array object to delete
  14293. */
  14294. Engine.prototype.releaseVertexArrayObject = function (vao) {
  14295. this._gl.deleteVertexArray(vao);
  14296. };
  14297. /** @hidden */
  14298. Engine.prototype._releaseBuffer = function (buffer) {
  14299. buffer.references--;
  14300. if (buffer.references === 0) {
  14301. this._gl.deleteBuffer(buffer);
  14302. return true;
  14303. }
  14304. return false;
  14305. };
  14306. /**
  14307. * Creates a webGL buffer to use with instanciation
  14308. * @param capacity defines the size of the buffer
  14309. * @returns the webGL buffer
  14310. */
  14311. Engine.prototype.createInstancesBuffer = function (capacity) {
  14312. var buffer = this._gl.createBuffer();
  14313. if (!buffer) {
  14314. throw new Error("Unable to create instance buffer");
  14315. }
  14316. buffer.capacity = capacity;
  14317. this.bindArrayBuffer(buffer);
  14318. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  14319. return buffer;
  14320. };
  14321. /**
  14322. * Delete a webGL buffer used with instanciation
  14323. * @param buffer defines the webGL buffer to delete
  14324. */
  14325. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  14326. this._gl.deleteBuffer(buffer);
  14327. };
  14328. /**
  14329. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  14330. * @param instancesBuffer defines the webGL buffer to update and bind
  14331. * @param data defines the data to store in the buffer
  14332. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  14333. */
  14334. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  14335. this.bindArrayBuffer(instancesBuffer);
  14336. if (data) {
  14337. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14338. }
  14339. if (offsetLocations[0].index !== undefined) {
  14340. var stride = 0;
  14341. for (var i = 0; i < offsetLocations.length; i++) {
  14342. var ai = offsetLocations[i];
  14343. stride += ai.attributeSize * 4;
  14344. }
  14345. for (var i = 0; i < offsetLocations.length; i++) {
  14346. var ai = offsetLocations[i];
  14347. if (!this._vertexAttribArraysEnabled[ai.index]) {
  14348. this._gl.enableVertexAttribArray(ai.index);
  14349. this._vertexAttribArraysEnabled[ai.index] = true;
  14350. }
  14351. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  14352. this._gl.vertexAttribDivisor(ai.index, 1);
  14353. this._currentInstanceLocations.push(ai.index);
  14354. this._currentInstanceBuffers.push(instancesBuffer);
  14355. }
  14356. }
  14357. else {
  14358. for (var index = 0; index < 4; index++) {
  14359. var offsetLocation = offsetLocations[index];
  14360. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  14361. this._gl.enableVertexAttribArray(offsetLocation);
  14362. this._vertexAttribArraysEnabled[offsetLocation] = true;
  14363. }
  14364. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  14365. this._gl.vertexAttribDivisor(offsetLocation, 1);
  14366. this._currentInstanceLocations.push(offsetLocation);
  14367. this._currentInstanceBuffers.push(instancesBuffer);
  14368. }
  14369. }
  14370. };
  14371. /**
  14372. * Apply all cached states (depth, culling, stencil and alpha)
  14373. */
  14374. Engine.prototype.applyStates = function () {
  14375. this._depthCullingState.apply(this._gl);
  14376. this._stencilState.apply(this._gl);
  14377. this._alphaState.apply(this._gl);
  14378. };
  14379. /**
  14380. * Send a draw order
  14381. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14382. * @param indexStart defines the starting index
  14383. * @param indexCount defines the number of index to draw
  14384. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14385. */
  14386. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  14387. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  14388. };
  14389. /**
  14390. * Draw a list of points
  14391. * @param verticesStart defines the index of first vertex to draw
  14392. * @param verticesCount defines the count of vertices to draw
  14393. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14394. */
  14395. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  14396. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  14397. };
  14398. /**
  14399. * Draw a list of unindexed primitives
  14400. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14401. * @param verticesStart defines the index of first vertex to draw
  14402. * @param verticesCount defines the count of vertices to draw
  14403. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14404. */
  14405. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  14406. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  14407. };
  14408. /**
  14409. * Draw a list of indexed primitives
  14410. * @param fillMode defines the primitive to use
  14411. * @param indexStart defines the starting index
  14412. * @param indexCount defines the number of index to draw
  14413. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14414. */
  14415. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  14416. // Apply states
  14417. this.applyStates();
  14418. this._drawCalls.addCount(1, false);
  14419. // Render
  14420. var drawMode = this._drawMode(fillMode);
  14421. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  14422. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  14423. if (instancesCount) {
  14424. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  14425. }
  14426. else {
  14427. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  14428. }
  14429. };
  14430. /**
  14431. * Draw a list of unindexed primitives
  14432. * @param fillMode defines the primitive to use
  14433. * @param verticesStart defines the index of first vertex to draw
  14434. * @param verticesCount defines the count of vertices to draw
  14435. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14436. */
  14437. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  14438. // Apply states
  14439. this.applyStates();
  14440. this._drawCalls.addCount(1, false);
  14441. var drawMode = this._drawMode(fillMode);
  14442. if (instancesCount) {
  14443. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  14444. }
  14445. else {
  14446. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  14447. }
  14448. };
  14449. Engine.prototype._drawMode = function (fillMode) {
  14450. switch (fillMode) {
  14451. // Triangle views
  14452. case BABYLON.Material.TriangleFillMode:
  14453. return this._gl.TRIANGLES;
  14454. case BABYLON.Material.PointFillMode:
  14455. return this._gl.POINTS;
  14456. case BABYLON.Material.WireFrameFillMode:
  14457. return this._gl.LINES;
  14458. // Draw modes
  14459. case BABYLON.Material.PointListDrawMode:
  14460. return this._gl.POINTS;
  14461. case BABYLON.Material.LineListDrawMode:
  14462. return this._gl.LINES;
  14463. case BABYLON.Material.LineLoopDrawMode:
  14464. return this._gl.LINE_LOOP;
  14465. case BABYLON.Material.LineStripDrawMode:
  14466. return this._gl.LINE_STRIP;
  14467. case BABYLON.Material.TriangleStripDrawMode:
  14468. return this._gl.TRIANGLE_STRIP;
  14469. case BABYLON.Material.TriangleFanDrawMode:
  14470. return this._gl.TRIANGLE_FAN;
  14471. default:
  14472. return this._gl.TRIANGLES;
  14473. }
  14474. };
  14475. // Shaders
  14476. /** @hidden */
  14477. Engine.prototype._releaseEffect = function (effect) {
  14478. if (this._compiledEffects[effect._key]) {
  14479. delete this._compiledEffects[effect._key];
  14480. this._deleteProgram(effect.getProgram());
  14481. }
  14482. };
  14483. /** @hidden */
  14484. Engine.prototype._deleteProgram = function (program) {
  14485. if (program) {
  14486. program.__SPECTOR_rebuildProgram = null;
  14487. if (program.transformFeedback) {
  14488. this.deleteTransformFeedback(program.transformFeedback);
  14489. program.transformFeedback = null;
  14490. }
  14491. this._gl.deleteProgram(program);
  14492. }
  14493. };
  14494. /**
  14495. * Create a new effect (used to store vertex/fragment shaders)
  14496. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14497. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14498. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14499. * @param samplers defines an array of string used to represent textures
  14500. * @param defines defines the string containing the defines to use to compile the shaders
  14501. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14502. * @param onCompiled defines a function to call when the effect creation is successful
  14503. * @param onError defines a function to call when the effect creation has failed
  14504. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14505. * @returns the new Effect
  14506. */
  14507. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14508. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14509. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14510. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14511. if (this._compiledEffects[name]) {
  14512. var compiledEffect = this._compiledEffects[name];
  14513. if (onCompiled && compiledEffect.isReady()) {
  14514. onCompiled(compiledEffect);
  14515. }
  14516. return compiledEffect;
  14517. }
  14518. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14519. effect._key = name;
  14520. this._compiledEffects[name] = effect;
  14521. return effect;
  14522. };
  14523. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  14524. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  14525. };
  14526. Engine.prototype._compileRawShader = function (source, type) {
  14527. var gl = this._gl;
  14528. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  14529. if (!shader) {
  14530. throw new Error("Something went wrong while compile the shader.");
  14531. }
  14532. gl.shaderSource(shader, source);
  14533. gl.compileShader(shader);
  14534. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  14535. var log = gl.getShaderInfoLog(shader);
  14536. if (log) {
  14537. throw new Error(log);
  14538. }
  14539. }
  14540. return shader;
  14541. };
  14542. /**
  14543. * Directly creates a webGL program
  14544. * @param vertexCode defines the vertex shader code to use
  14545. * @param fragmentCode defines the fragment shader code to use
  14546. * @param context defines the webGL context to use (if not set, the current one will be used)
  14547. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14548. * @returns the new webGL program
  14549. */
  14550. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14551. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14552. context = context || this._gl;
  14553. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  14554. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  14555. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14556. };
  14557. /**
  14558. * Creates a webGL program
  14559. * @param vertexCode defines the vertex shader code to use
  14560. * @param fragmentCode defines the fragment shader code to use
  14561. * @param defines defines the string containing the defines to use to compile the shaders
  14562. * @param context defines the webGL context to use (if not set, the current one will be used)
  14563. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14564. * @returns the new webGL program
  14565. */
  14566. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14567. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14568. context = context || this._gl;
  14569. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14570. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14571. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  14572. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  14573. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14574. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14575. return program;
  14576. };
  14577. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14578. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14579. var shaderProgram = context.createProgram();
  14580. if (!shaderProgram) {
  14581. throw new Error("Unable to create program");
  14582. }
  14583. context.attachShader(shaderProgram, vertexShader);
  14584. context.attachShader(shaderProgram, fragmentShader);
  14585. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14586. var transformFeedback = this.createTransformFeedback();
  14587. this.bindTransformFeedback(transformFeedback);
  14588. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14589. shaderProgram.transformFeedback = transformFeedback;
  14590. }
  14591. context.linkProgram(shaderProgram);
  14592. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14593. this.bindTransformFeedback(null);
  14594. }
  14595. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14596. if (!linked) {
  14597. var error = context.getProgramInfoLog(shaderProgram);
  14598. if (error) {
  14599. throw new Error(error);
  14600. }
  14601. }
  14602. if (this.validateShaderPrograms) {
  14603. context.validateProgram(shaderProgram);
  14604. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14605. if (!validated) {
  14606. var error = context.getProgramInfoLog(shaderProgram);
  14607. if (error) {
  14608. throw new Error(error);
  14609. }
  14610. }
  14611. }
  14612. context.deleteShader(vertexShader);
  14613. context.deleteShader(fragmentShader);
  14614. return shaderProgram;
  14615. };
  14616. /**
  14617. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14618. * @param shaderProgram defines the webGL program to use
  14619. * @param uniformsNames defines the list of uniform names
  14620. * @returns an array of webGL uniform locations
  14621. */
  14622. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14623. var results = new Array();
  14624. for (var index = 0; index < uniformsNames.length; index++) {
  14625. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14626. }
  14627. return results;
  14628. };
  14629. /**
  14630. * Gets the lsit of active attributes for a given webGL program
  14631. * @param shaderProgram defines the webGL program to use
  14632. * @param attributesNames defines the list of attribute names to get
  14633. * @returns an array of indices indicating the offset of each attribute
  14634. */
  14635. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14636. var results = [];
  14637. for (var index = 0; index < attributesNames.length; index++) {
  14638. try {
  14639. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14640. }
  14641. catch (e) {
  14642. results.push(-1);
  14643. }
  14644. }
  14645. return results;
  14646. };
  14647. /**
  14648. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14649. * @param effect defines the effect to activate
  14650. */
  14651. Engine.prototype.enableEffect = function (effect) {
  14652. if (!effect || effect === this._currentEffect) {
  14653. return;
  14654. }
  14655. // Use program
  14656. this.bindSamplers(effect);
  14657. this._currentEffect = effect;
  14658. if (effect.onBind) {
  14659. effect.onBind(effect);
  14660. }
  14661. if (effect._onBindObservable) {
  14662. effect._onBindObservable.notifyObservers(effect);
  14663. }
  14664. };
  14665. /**
  14666. * Set the value of an uniform to an array of int32
  14667. * @param uniform defines the webGL uniform location where to store the value
  14668. * @param array defines the array of int32 to store
  14669. */
  14670. Engine.prototype.setIntArray = function (uniform, array) {
  14671. if (!uniform) {
  14672. return;
  14673. }
  14674. this._gl.uniform1iv(uniform, array);
  14675. };
  14676. /**
  14677. * Set the value of an uniform to an array of int32 (stored as vec2)
  14678. * @param uniform defines the webGL uniform location where to store the value
  14679. * @param array defines the array of int32 to store
  14680. */
  14681. Engine.prototype.setIntArray2 = function (uniform, array) {
  14682. if (!uniform || array.length % 2 !== 0) {
  14683. return;
  14684. }
  14685. this._gl.uniform2iv(uniform, array);
  14686. };
  14687. /**
  14688. * Set the value of an uniform to an array of int32 (stored as vec3)
  14689. * @param uniform defines the webGL uniform location where to store the value
  14690. * @param array defines the array of int32 to store
  14691. */
  14692. Engine.prototype.setIntArray3 = function (uniform, array) {
  14693. if (!uniform || array.length % 3 !== 0) {
  14694. return;
  14695. }
  14696. this._gl.uniform3iv(uniform, array);
  14697. };
  14698. /**
  14699. * Set the value of an uniform to an array of int32 (stored as vec4)
  14700. * @param uniform defines the webGL uniform location where to store the value
  14701. * @param array defines the array of int32 to store
  14702. */
  14703. Engine.prototype.setIntArray4 = function (uniform, array) {
  14704. if (!uniform || array.length % 4 !== 0) {
  14705. return;
  14706. }
  14707. this._gl.uniform4iv(uniform, array);
  14708. };
  14709. /**
  14710. * Set the value of an uniform to an array of float32
  14711. * @param uniform defines the webGL uniform location where to store the value
  14712. * @param array defines the array of float32 to store
  14713. */
  14714. Engine.prototype.setFloatArray = function (uniform, array) {
  14715. if (!uniform) {
  14716. return;
  14717. }
  14718. this._gl.uniform1fv(uniform, array);
  14719. };
  14720. /**
  14721. * Set the value of an uniform to an array of float32 (stored as vec2)
  14722. * @param uniform defines the webGL uniform location where to store the value
  14723. * @param array defines the array of float32 to store
  14724. */
  14725. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14726. if (!uniform || array.length % 2 !== 0) {
  14727. return;
  14728. }
  14729. this._gl.uniform2fv(uniform, array);
  14730. };
  14731. /**
  14732. * Set the value of an uniform to an array of float32 (stored as vec3)
  14733. * @param uniform defines the webGL uniform location where to store the value
  14734. * @param array defines the array of float32 to store
  14735. */
  14736. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14737. if (!uniform || array.length % 3 !== 0) {
  14738. return;
  14739. }
  14740. this._gl.uniform3fv(uniform, array);
  14741. };
  14742. /**
  14743. * Set the value of an uniform to an array of float32 (stored as vec4)
  14744. * @param uniform defines the webGL uniform location where to store the value
  14745. * @param array defines the array of float32 to store
  14746. */
  14747. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14748. if (!uniform || array.length % 4 !== 0) {
  14749. return;
  14750. }
  14751. this._gl.uniform4fv(uniform, array);
  14752. };
  14753. /**
  14754. * Set the value of an uniform to an array of number
  14755. * @param uniform defines the webGL uniform location where to store the value
  14756. * @param array defines the array of number to store
  14757. */
  14758. Engine.prototype.setArray = function (uniform, array) {
  14759. if (!uniform) {
  14760. return;
  14761. }
  14762. this._gl.uniform1fv(uniform, array);
  14763. };
  14764. /**
  14765. * Set the value of an uniform to an array of number (stored as vec2)
  14766. * @param uniform defines the webGL uniform location where to store the value
  14767. * @param array defines the array of number to store
  14768. */
  14769. Engine.prototype.setArray2 = function (uniform, array) {
  14770. if (!uniform || array.length % 2 !== 0) {
  14771. return;
  14772. }
  14773. this._gl.uniform2fv(uniform, array);
  14774. };
  14775. /**
  14776. * Set the value of an uniform to an array of number (stored as vec3)
  14777. * @param uniform defines the webGL uniform location where to store the value
  14778. * @param array defines the array of number to store
  14779. */
  14780. Engine.prototype.setArray3 = function (uniform, array) {
  14781. if (!uniform || array.length % 3 !== 0) {
  14782. return;
  14783. }
  14784. this._gl.uniform3fv(uniform, array);
  14785. };
  14786. /**
  14787. * Set the value of an uniform to an array of number (stored as vec4)
  14788. * @param uniform defines the webGL uniform location where to store the value
  14789. * @param array defines the array of number to store
  14790. */
  14791. Engine.prototype.setArray4 = function (uniform, array) {
  14792. if (!uniform || array.length % 4 !== 0) {
  14793. return;
  14794. }
  14795. this._gl.uniform4fv(uniform, array);
  14796. };
  14797. /**
  14798. * Set the value of an uniform to an array of float32 (stored as matrices)
  14799. * @param uniform defines the webGL uniform location where to store the value
  14800. * @param matrices defines the array of float32 to store
  14801. */
  14802. Engine.prototype.setMatrices = function (uniform, matrices) {
  14803. if (!uniform) {
  14804. return;
  14805. }
  14806. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14807. };
  14808. /**
  14809. * Set the value of an uniform to a matrix
  14810. * @param uniform defines the webGL uniform location where to store the value
  14811. * @param matrix defines the matrix to store
  14812. */
  14813. Engine.prototype.setMatrix = function (uniform, matrix) {
  14814. if (!uniform) {
  14815. return;
  14816. }
  14817. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14818. };
  14819. /**
  14820. * Set the value of an uniform to a matrix (3x3)
  14821. * @param uniform defines the webGL uniform location where to store the value
  14822. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14823. */
  14824. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14825. if (!uniform) {
  14826. return;
  14827. }
  14828. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14829. };
  14830. /**
  14831. * Set the value of an uniform to a matrix (2x2)
  14832. * @param uniform defines the webGL uniform location where to store the value
  14833. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14834. */
  14835. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14836. if (!uniform) {
  14837. return;
  14838. }
  14839. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14840. };
  14841. /**
  14842. * Set the value of an uniform to a number (int)
  14843. * @param uniform defines the webGL uniform location where to store the value
  14844. * @param value defines the int number to store
  14845. */
  14846. Engine.prototype.setInt = function (uniform, value) {
  14847. if (!uniform) {
  14848. return;
  14849. }
  14850. this._gl.uniform1i(uniform, value);
  14851. };
  14852. /**
  14853. * Set the value of an uniform to a number (float)
  14854. * @param uniform defines the webGL uniform location where to store the value
  14855. * @param value defines the float number to store
  14856. */
  14857. Engine.prototype.setFloat = function (uniform, value) {
  14858. if (!uniform) {
  14859. return;
  14860. }
  14861. this._gl.uniform1f(uniform, value);
  14862. };
  14863. /**
  14864. * Set the value of an uniform to a vec2
  14865. * @param uniform defines the webGL uniform location where to store the value
  14866. * @param x defines the 1st component of the value
  14867. * @param y defines the 2nd component of the value
  14868. */
  14869. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14870. if (!uniform) {
  14871. return;
  14872. }
  14873. this._gl.uniform2f(uniform, x, y);
  14874. };
  14875. /**
  14876. * Set the value of an uniform to a vec3
  14877. * @param uniform defines the webGL uniform location where to store the value
  14878. * @param x defines the 1st component of the value
  14879. * @param y defines the 2nd component of the value
  14880. * @param z defines the 3rd component of the value
  14881. */
  14882. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14883. if (!uniform) {
  14884. return;
  14885. }
  14886. this._gl.uniform3f(uniform, x, y, z);
  14887. };
  14888. /**
  14889. * Set the value of an uniform to a boolean
  14890. * @param uniform defines the webGL uniform location where to store the value
  14891. * @param bool defines the boolean to store
  14892. */
  14893. Engine.prototype.setBool = function (uniform, bool) {
  14894. if (!uniform) {
  14895. return;
  14896. }
  14897. this._gl.uniform1i(uniform, bool);
  14898. };
  14899. /**
  14900. * Set the value of an uniform to a vec4
  14901. * @param uniform defines the webGL uniform location where to store the value
  14902. * @param x defines the 1st component of the value
  14903. * @param y defines the 2nd component of the value
  14904. * @param z defines the 3rd component of the value
  14905. * @param w defines the 4th component of the value
  14906. */
  14907. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14908. if (!uniform) {
  14909. return;
  14910. }
  14911. this._gl.uniform4f(uniform, x, y, z, w);
  14912. };
  14913. /**
  14914. * Set the value of an uniform to a Color3
  14915. * @param uniform defines the webGL uniform location where to store the value
  14916. * @param color3 defines the color to store
  14917. */
  14918. Engine.prototype.setColor3 = function (uniform, color3) {
  14919. if (!uniform) {
  14920. return;
  14921. }
  14922. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14923. };
  14924. /**
  14925. * Set the value of an uniform to a Color3 and an alpha value
  14926. * @param uniform defines the webGL uniform location where to store the value
  14927. * @param color3 defines the color to store
  14928. * @param alpha defines the alpha component to store
  14929. */
  14930. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14931. if (!uniform) {
  14932. return;
  14933. }
  14934. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14935. };
  14936. /**
  14937. * Sets a Color4 on a uniform variable
  14938. * @param uniform defines the uniform location
  14939. * @param color4 defines the value to be set
  14940. */
  14941. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14942. if (!uniform) {
  14943. return;
  14944. }
  14945. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14946. };
  14947. // States
  14948. /**
  14949. * Set various states to the webGL context
  14950. * @param culling defines backface culling state
  14951. * @param zOffset defines the value to apply to zOffset (0 by default)
  14952. * @param force defines if states must be applied even if cache is up to date
  14953. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14954. */
  14955. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14956. if (zOffset === void 0) { zOffset = 0; }
  14957. if (reverseSide === void 0) { reverseSide = false; }
  14958. // Culling
  14959. if (this._depthCullingState.cull !== culling || force) {
  14960. this._depthCullingState.cull = culling;
  14961. }
  14962. // Cull face
  14963. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14964. if (this._depthCullingState.cullFace !== cullFace || force) {
  14965. this._depthCullingState.cullFace = cullFace;
  14966. }
  14967. // Z offset
  14968. this.setZOffset(zOffset);
  14969. // Front face
  14970. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14971. if (this._depthCullingState.frontFace !== frontFace || force) {
  14972. this._depthCullingState.frontFace = frontFace;
  14973. }
  14974. };
  14975. /**
  14976. * Set the z offset to apply to current rendering
  14977. * @param value defines the offset to apply
  14978. */
  14979. Engine.prototype.setZOffset = function (value) {
  14980. this._depthCullingState.zOffset = value;
  14981. };
  14982. /**
  14983. * Gets the current value of the zOffset
  14984. * @returns the current zOffset state
  14985. */
  14986. Engine.prototype.getZOffset = function () {
  14987. return this._depthCullingState.zOffset;
  14988. };
  14989. /**
  14990. * Enable or disable depth buffering
  14991. * @param enable defines the state to set
  14992. */
  14993. Engine.prototype.setDepthBuffer = function (enable) {
  14994. this._depthCullingState.depthTest = enable;
  14995. };
  14996. /**
  14997. * Gets a boolean indicating if depth writing is enabled
  14998. * @returns the current depth writing state
  14999. */
  15000. Engine.prototype.getDepthWrite = function () {
  15001. return this._depthCullingState.depthMask;
  15002. };
  15003. /**
  15004. * Enable or disable depth writing
  15005. * @param enable defines the state to set
  15006. */
  15007. Engine.prototype.setDepthWrite = function (enable) {
  15008. this._depthCullingState.depthMask = enable;
  15009. };
  15010. /**
  15011. * Enable or disable color writing
  15012. * @param enable defines the state to set
  15013. */
  15014. Engine.prototype.setColorWrite = function (enable) {
  15015. this._gl.colorMask(enable, enable, enable, enable);
  15016. this._colorWrite = enable;
  15017. };
  15018. /**
  15019. * Gets a boolean indicating if color writing is enabled
  15020. * @returns the current color writing state
  15021. */
  15022. Engine.prototype.getColorWrite = function () {
  15023. return this._colorWrite;
  15024. };
  15025. /**
  15026. * Sets alpha constants used by some alpha blending modes
  15027. * @param r defines the red component
  15028. * @param g defines the green component
  15029. * @param b defines the blue component
  15030. * @param a defines the alpha component
  15031. */
  15032. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  15033. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  15034. };
  15035. /**
  15036. * Sets the current alpha mode
  15037. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  15038. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  15039. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  15040. */
  15041. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  15042. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  15043. if (this._alphaMode === mode) {
  15044. return;
  15045. }
  15046. switch (mode) {
  15047. case Engine.ALPHA_DISABLE:
  15048. this._alphaState.alphaBlend = false;
  15049. break;
  15050. case Engine.ALPHA_PREMULTIPLIED:
  15051. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  15052. this._alphaState.alphaBlend = true;
  15053. break;
  15054. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  15055. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15056. this._alphaState.alphaBlend = true;
  15057. break;
  15058. case Engine.ALPHA_COMBINE:
  15059. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  15060. this._alphaState.alphaBlend = true;
  15061. break;
  15062. case Engine.ALPHA_ONEONE:
  15063. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  15064. this._alphaState.alphaBlend = true;
  15065. break;
  15066. case Engine.ALPHA_ADD:
  15067. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  15068. this._alphaState.alphaBlend = true;
  15069. break;
  15070. case Engine.ALPHA_SUBTRACT:
  15071. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15072. this._alphaState.alphaBlend = true;
  15073. break;
  15074. case Engine.ALPHA_MULTIPLY:
  15075. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  15076. this._alphaState.alphaBlend = true;
  15077. break;
  15078. case Engine.ALPHA_MAXIMIZED:
  15079. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15080. this._alphaState.alphaBlend = true;
  15081. break;
  15082. case Engine.ALPHA_INTERPOLATE:
  15083. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  15084. this._alphaState.alphaBlend = true;
  15085. break;
  15086. case Engine.ALPHA_SCREENMODE:
  15087. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15088. this._alphaState.alphaBlend = true;
  15089. break;
  15090. }
  15091. if (!noDepthWriteChange) {
  15092. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  15093. }
  15094. this._alphaMode = mode;
  15095. };
  15096. /**
  15097. * Gets the current alpha mode
  15098. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  15099. * @returns the current alpha mode
  15100. */
  15101. Engine.prototype.getAlphaMode = function () {
  15102. return this._alphaMode;
  15103. };
  15104. // Textures
  15105. /**
  15106. * Clears the list of texture accessible through engine.
  15107. * This can help preventing texture load conflict due to name collision.
  15108. */
  15109. Engine.prototype.clearInternalTexturesCache = function () {
  15110. this._internalTexturesCache = [];
  15111. };
  15112. /**
  15113. * Force the entire cache to be cleared
  15114. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  15115. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  15116. */
  15117. Engine.prototype.wipeCaches = function (bruteForce) {
  15118. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  15119. return;
  15120. }
  15121. this._currentEffect = null;
  15122. this._viewportCached.x = 0;
  15123. this._viewportCached.y = 0;
  15124. this._viewportCached.z = 0;
  15125. this._viewportCached.w = 0;
  15126. if (bruteForce) {
  15127. this.resetTextureCache();
  15128. this._currentProgram = null;
  15129. this._stencilState.reset();
  15130. this._depthCullingState.reset();
  15131. this.setDepthFunctionToLessOrEqual();
  15132. this._alphaState.reset();
  15133. this._unpackFlipYCached = null;
  15134. }
  15135. this._resetVertexBufferBinding();
  15136. this._cachedIndexBuffer = null;
  15137. this._cachedEffectForVertexBuffers = null;
  15138. this._unbindVertexArrayObject();
  15139. this.bindIndexBuffer(null);
  15140. };
  15141. /**
  15142. * Set the compressed texture format to use, based on the formats you have, and the formats
  15143. * supported by the hardware / browser.
  15144. *
  15145. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  15146. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  15147. * to API arguments needed to compressed textures. This puts the burden on the container
  15148. * generator to house the arcane code for determining these for current & future formats.
  15149. *
  15150. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  15151. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  15152. *
  15153. * Note: The result of this call is not taken into account when a texture is base64.
  15154. *
  15155. * @param formatsAvailable defines the list of those format families you have created
  15156. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  15157. *
  15158. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  15159. * @returns The extension selected.
  15160. */
  15161. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  15162. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  15163. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  15164. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  15165. return this._textureFormatInUse = this._texturesSupported[i];
  15166. }
  15167. }
  15168. }
  15169. // actively set format to nothing, to allow this to be called more than once
  15170. // and possibly fail the 2nd time
  15171. this._textureFormatInUse = null;
  15172. return null;
  15173. };
  15174. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  15175. var gl = this._gl;
  15176. var magFilter = gl.NEAREST;
  15177. var minFilter = gl.NEAREST;
  15178. switch (samplingMode) {
  15179. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  15180. magFilter = gl.LINEAR;
  15181. if (generateMipMaps) {
  15182. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15183. }
  15184. else {
  15185. minFilter = gl.LINEAR;
  15186. }
  15187. break;
  15188. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  15189. magFilter = gl.LINEAR;
  15190. if (generateMipMaps) {
  15191. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15192. }
  15193. else {
  15194. minFilter = gl.LINEAR;
  15195. }
  15196. break;
  15197. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  15198. magFilter = gl.NEAREST;
  15199. if (generateMipMaps) {
  15200. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15201. }
  15202. else {
  15203. minFilter = gl.NEAREST;
  15204. }
  15205. break;
  15206. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  15207. magFilter = gl.NEAREST;
  15208. if (generateMipMaps) {
  15209. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15210. }
  15211. else {
  15212. minFilter = gl.NEAREST;
  15213. }
  15214. break;
  15215. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  15216. magFilter = gl.NEAREST;
  15217. if (generateMipMaps) {
  15218. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15219. }
  15220. else {
  15221. minFilter = gl.LINEAR;
  15222. }
  15223. break;
  15224. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  15225. magFilter = gl.NEAREST;
  15226. if (generateMipMaps) {
  15227. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15228. }
  15229. else {
  15230. minFilter = gl.LINEAR;
  15231. }
  15232. break;
  15233. case Engine.TEXTURE_NEAREST_LINEAR:
  15234. magFilter = gl.NEAREST;
  15235. minFilter = gl.LINEAR;
  15236. break;
  15237. case Engine.TEXTURE_NEAREST_NEAREST:
  15238. magFilter = gl.NEAREST;
  15239. minFilter = gl.NEAREST;
  15240. break;
  15241. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  15242. magFilter = gl.LINEAR;
  15243. if (generateMipMaps) {
  15244. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15245. }
  15246. else {
  15247. minFilter = gl.NEAREST;
  15248. }
  15249. break;
  15250. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  15251. magFilter = gl.LINEAR;
  15252. if (generateMipMaps) {
  15253. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15254. }
  15255. else {
  15256. minFilter = gl.NEAREST;
  15257. }
  15258. break;
  15259. case Engine.TEXTURE_LINEAR_LINEAR:
  15260. magFilter = gl.LINEAR;
  15261. minFilter = gl.LINEAR;
  15262. break;
  15263. case Engine.TEXTURE_LINEAR_NEAREST:
  15264. magFilter = gl.LINEAR;
  15265. minFilter = gl.NEAREST;
  15266. break;
  15267. }
  15268. return {
  15269. min: minFilter,
  15270. mag: magFilter
  15271. };
  15272. };
  15273. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  15274. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15275. var img;
  15276. var onload = function () {
  15277. loadedImages[index] = img;
  15278. loadedImages._internalCount++;
  15279. if (scene) {
  15280. scene._removePendingData(img);
  15281. }
  15282. if (loadedImages._internalCount === 6) {
  15283. onfinish(loadedImages);
  15284. }
  15285. };
  15286. var onerror = function (message, exception) {
  15287. if (scene) {
  15288. scene._removePendingData(img);
  15289. }
  15290. if (onErrorCallBack) {
  15291. onErrorCallBack(message, exception);
  15292. }
  15293. };
  15294. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  15295. if (scene) {
  15296. scene._addPendingData(img);
  15297. }
  15298. };
  15299. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  15300. if (onError === void 0) { onError = null; }
  15301. var loadedImages = [];
  15302. loadedImages._internalCount = 0;
  15303. for (var index = 0; index < 6; index++) {
  15304. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  15305. }
  15306. };
  15307. /** @hidden */
  15308. Engine.prototype._createTexture = function () {
  15309. var texture = this._gl.createTexture();
  15310. if (!texture) {
  15311. throw new Error("Unable to create texture");
  15312. }
  15313. return texture;
  15314. };
  15315. /**
  15316. * Usually called from BABYLON.Texture.ts.
  15317. * Passed information to create a WebGLTexture
  15318. * @param urlArg defines a value which contains one of the following:
  15319. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  15320. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  15321. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  15322. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  15323. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  15324. * @param scene needed for loading to the correct scene
  15325. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  15326. * @param onLoad optional callback to be called upon successful completion
  15327. * @param onError optional callback to be called upon failure
  15328. * @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
  15329. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  15330. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  15331. * @param forcedExtension defines the extension to use to pick the right loader
  15332. * @returns a InternalTexture for assignment back into BABYLON.Texture
  15333. */
  15334. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  15335. var _this = this;
  15336. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15337. if (onLoad === void 0) { onLoad = null; }
  15338. if (onError === void 0) { onError = null; }
  15339. if (buffer === void 0) { buffer = null; }
  15340. if (fallback === void 0) { fallback = null; }
  15341. if (format === void 0) { format = null; }
  15342. if (forcedExtension === void 0) { forcedExtension = null; }
  15343. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  15344. var fromData = url.substr(0, 5) === "data:";
  15345. var fromBlob = url.substr(0, 5) === "blob:";
  15346. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  15347. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  15348. // establish the file extension, if possible
  15349. var lastDot = url.lastIndexOf('.');
  15350. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  15351. var loader = null;
  15352. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15353. var availableLoader = _a[_i];
  15354. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  15355. loader = availableLoader;
  15356. break;
  15357. }
  15358. }
  15359. if (loader) {
  15360. url = loader.transformUrl(url, this._textureFormatInUse);
  15361. }
  15362. if (scene) {
  15363. scene._addPendingData(texture);
  15364. }
  15365. texture.url = url;
  15366. texture.generateMipMaps = !noMipmap;
  15367. texture.samplingMode = samplingMode;
  15368. texture.invertY = invertY;
  15369. if (!this._doNotHandleContextLost) {
  15370. // Keep a link to the buffer only if we plan to handle context lost
  15371. texture._buffer = buffer;
  15372. }
  15373. var onLoadObserver = null;
  15374. if (onLoad && !fallback) {
  15375. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  15376. }
  15377. if (!fallback) {
  15378. this._internalTexturesCache.push(texture);
  15379. }
  15380. var onInternalError = function (message, exception) {
  15381. if (scene) {
  15382. scene._removePendingData(texture);
  15383. }
  15384. var customFallback = false;
  15385. if (loader) {
  15386. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  15387. if (fallbackUrl) {
  15388. // Add Back
  15389. customFallback = true;
  15390. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15391. }
  15392. }
  15393. if (!customFallback) {
  15394. if (onLoadObserver) {
  15395. texture.onLoadedObservable.remove(onLoadObserver);
  15396. }
  15397. if (BABYLON.Tools.UseFallbackTexture) {
  15398. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15399. }
  15400. }
  15401. if (onError) {
  15402. onError(message || "Unknown error", exception);
  15403. }
  15404. };
  15405. // processing for non-image formats
  15406. if (loader) {
  15407. var callback = function (data) {
  15408. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  15409. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  15410. done();
  15411. return false;
  15412. }, samplingMode);
  15413. });
  15414. };
  15415. if (!buffer) {
  15416. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  15417. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  15418. });
  15419. }
  15420. else {
  15421. callback(buffer);
  15422. }
  15423. }
  15424. else {
  15425. var onload = function (img) {
  15426. if (fromBlob && !_this._doNotHandleContextLost) {
  15427. // We need to store the image if we need to rebuild the texture
  15428. // in case of a webgl context lost
  15429. texture._buffer = img;
  15430. }
  15431. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  15432. var gl = _this._gl;
  15433. var isPot = (img.width === potWidth && img.height === potHeight);
  15434. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  15435. if (isPot) {
  15436. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15437. return false;
  15438. }
  15439. var maxTextureSize = _this._caps.maxTextureSize;
  15440. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  15441. _this._prepareWorkingCanvas();
  15442. if (!_this._workingCanvas || !_this._workingContext) {
  15443. return false;
  15444. }
  15445. _this._workingCanvas.width = potWidth;
  15446. _this._workingCanvas.height = potHeight;
  15447. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  15448. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15449. texture.width = potWidth;
  15450. texture.height = potHeight;
  15451. return false;
  15452. }
  15453. else {
  15454. // Using shaders when possible to rescale because canvas.drawImage is lossy
  15455. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15456. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  15457. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15458. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15459. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15460. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15461. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15462. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  15463. _this._releaseTexture(source_1);
  15464. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15465. continuationCallback();
  15466. });
  15467. }
  15468. return true;
  15469. }, samplingMode);
  15470. };
  15471. if (!fromData || isBase64) {
  15472. if (buffer instanceof HTMLImageElement) {
  15473. onload(buffer);
  15474. }
  15475. else {
  15476. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  15477. }
  15478. }
  15479. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  15480. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  15481. }
  15482. else {
  15483. onload(buffer);
  15484. }
  15485. }
  15486. return texture;
  15487. };
  15488. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  15489. var _this = this;
  15490. var rtt = this.createRenderTargetTexture({
  15491. width: destination.width,
  15492. height: destination.height,
  15493. }, {
  15494. generateMipMaps: false,
  15495. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  15496. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  15497. generateDepthBuffer: false,
  15498. generateStencilBuffer: false
  15499. });
  15500. if (!this._rescalePostProcess) {
  15501. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  15502. }
  15503. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  15504. _this._rescalePostProcess.onApply = function (effect) {
  15505. effect._bindTexture("textureSampler", source);
  15506. };
  15507. var hostingScene = scene;
  15508. if (!hostingScene) {
  15509. hostingScene = _this.scenes[_this.scenes.length - 1];
  15510. }
  15511. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  15512. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  15513. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  15514. _this.unBindFramebuffer(rtt);
  15515. _this._releaseTexture(rtt);
  15516. if (onComplete) {
  15517. onComplete();
  15518. }
  15519. });
  15520. };
  15521. /**
  15522. * Update a raw texture
  15523. * @param texture defines the texture to update
  15524. * @param data defines the data to store in the texture
  15525. * @param format defines the format of the data
  15526. * @param invertY defines if data must be stored with Y axis inverted
  15527. * @param compression defines the compression used (null by default)
  15528. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15529. */
  15530. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  15531. if (compression === void 0) { compression = null; }
  15532. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15533. if (!texture) {
  15534. return;
  15535. }
  15536. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  15537. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  15538. // babylon's internalFormat but gl's texImage2D format
  15539. var internalFormat = this._getInternalFormat(format);
  15540. var textureType = this._getWebGLTextureType(type);
  15541. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15542. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15543. if (!this._doNotHandleContextLost) {
  15544. texture._bufferView = data;
  15545. texture.format = format;
  15546. texture.type = type;
  15547. texture.invertY = invertY;
  15548. texture._compression = compression;
  15549. }
  15550. if (texture.width % 4 !== 0) {
  15551. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15552. }
  15553. if (compression && data) {
  15554. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  15555. }
  15556. else {
  15557. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  15558. }
  15559. if (texture.generateMipMaps) {
  15560. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15561. }
  15562. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15563. // this.resetTextureCache();
  15564. texture.isReady = true;
  15565. };
  15566. /**
  15567. * Creates a raw texture
  15568. * @param data defines the data to store in the texture
  15569. * @param width defines the width of the texture
  15570. * @param height defines the height of the texture
  15571. * @param format defines the format of the data
  15572. * @param generateMipMaps defines if the engine should generate the mip levels
  15573. * @param invertY defines if data must be stored with Y axis inverted
  15574. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15575. * @param compression defines the compression used (null by default)
  15576. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15577. * @returns the raw texture inside an InternalTexture
  15578. */
  15579. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  15580. if (compression === void 0) { compression = null; }
  15581. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15582. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  15583. texture.baseWidth = width;
  15584. texture.baseHeight = height;
  15585. texture.width = width;
  15586. texture.height = height;
  15587. texture.format = format;
  15588. texture.generateMipMaps = generateMipMaps;
  15589. texture.samplingMode = samplingMode;
  15590. texture.invertY = invertY;
  15591. texture._compression = compression;
  15592. texture.type = type;
  15593. if (!this._doNotHandleContextLost) {
  15594. texture._bufferView = data;
  15595. }
  15596. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15597. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15598. // Filters
  15599. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15600. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15601. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15602. if (generateMipMaps) {
  15603. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15604. }
  15605. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15606. this._internalTexturesCache.push(texture);
  15607. return texture;
  15608. };
  15609. /** @hidden */
  15610. Engine.prototype._unpackFlipY = function (value) {
  15611. if (this._unpackFlipYCached !== value) {
  15612. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15613. if (this.enableUnpackFlipYCached) {
  15614. this._unpackFlipYCached = value;
  15615. }
  15616. }
  15617. };
  15618. /** @hidden */
  15619. Engine.prototype._getUnpackAlignement = function () {
  15620. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  15621. };
  15622. /**
  15623. * Creates a dynamic texture
  15624. * @param width defines the width of the texture
  15625. * @param height defines the height of the texture
  15626. * @param generateMipMaps defines if the engine should generate the mip levels
  15627. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15628. * @returns the dynamic texture inside an InternalTexture
  15629. */
  15630. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15631. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15632. texture.baseWidth = width;
  15633. texture.baseHeight = height;
  15634. if (generateMipMaps) {
  15635. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15636. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15637. }
  15638. // this.resetTextureCache();
  15639. texture.width = width;
  15640. texture.height = height;
  15641. texture.isReady = false;
  15642. texture.generateMipMaps = generateMipMaps;
  15643. texture.samplingMode = samplingMode;
  15644. this.updateTextureSamplingMode(samplingMode, texture);
  15645. this._internalTexturesCache.push(texture);
  15646. return texture;
  15647. };
  15648. /**
  15649. * Update the sampling mode of a given texture
  15650. * @param samplingMode defines the required sampling mode
  15651. * @param texture defines the texture to update
  15652. */
  15653. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15654. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  15655. if (texture.isCube) {
  15656. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15657. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15658. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15659. }
  15660. else if (texture.is3D) {
  15661. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15662. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15663. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15664. }
  15665. else {
  15666. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15667. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15668. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15669. }
  15670. texture.samplingMode = samplingMode;
  15671. };
  15672. /**
  15673. * Update the content of a dynamic texture
  15674. * @param texture defines the texture to update
  15675. * @param canvas defines the canvas containing the source
  15676. * @param invertY defines if data must be stored with Y axis inverted
  15677. * @param premulAlpha defines if alpha is stored as premultiplied
  15678. * @param format defines the format of the data
  15679. */
  15680. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15681. if (premulAlpha === void 0) { premulAlpha = false; }
  15682. if (!texture) {
  15683. return;
  15684. }
  15685. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15686. this._unpackFlipY(invertY);
  15687. if (premulAlpha) {
  15688. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15689. }
  15690. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15691. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15692. if (texture.generateMipMaps) {
  15693. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15694. }
  15695. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15696. if (premulAlpha) {
  15697. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15698. }
  15699. texture.isReady = true;
  15700. };
  15701. /**
  15702. * Update a video texture
  15703. * @param texture defines the texture to update
  15704. * @param video defines the video element to use
  15705. * @param invertY defines if data must be stored with Y axis inverted
  15706. */
  15707. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15708. if (!texture || texture._isDisabled) {
  15709. return;
  15710. }
  15711. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15712. this._unpackFlipY(!invertY); // Video are upside down by default
  15713. try {
  15714. // Testing video texture support
  15715. if (this._videoTextureSupported === undefined) {
  15716. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15717. if (this._gl.getError() !== 0) {
  15718. this._videoTextureSupported = false;
  15719. }
  15720. else {
  15721. this._videoTextureSupported = true;
  15722. }
  15723. }
  15724. // Copy video through the current working canvas if video texture is not supported
  15725. if (!this._videoTextureSupported) {
  15726. if (!texture._workingCanvas) {
  15727. texture._workingCanvas = document.createElement("canvas");
  15728. var context = texture._workingCanvas.getContext("2d");
  15729. if (!context) {
  15730. throw new Error("Unable to get 2d context");
  15731. }
  15732. texture._workingContext = context;
  15733. texture._workingCanvas.width = texture.width;
  15734. texture._workingCanvas.height = texture.height;
  15735. }
  15736. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15737. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15738. }
  15739. else {
  15740. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15741. }
  15742. if (texture.generateMipMaps) {
  15743. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15744. }
  15745. if (!wasPreviouslyBound) {
  15746. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15747. }
  15748. // this.resetTextureCache();
  15749. texture.isReady = true;
  15750. }
  15751. catch (ex) {
  15752. // Something unexpected
  15753. // Let's disable the texture
  15754. texture._isDisabled = true;
  15755. }
  15756. };
  15757. /**
  15758. * Updates a depth texture Comparison Mode and Function.
  15759. * If the comparison Function is equal to 0, the mode will be set to none.
  15760. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15761. * @param texture The texture to set the comparison function for
  15762. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15763. */
  15764. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15765. if (this.webGLVersion === 1) {
  15766. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15767. return;
  15768. }
  15769. var gl = this._gl;
  15770. if (texture.isCube) {
  15771. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15772. if (comparisonFunction === 0) {
  15773. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15774. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15775. }
  15776. else {
  15777. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15778. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15779. }
  15780. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15781. }
  15782. else {
  15783. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15784. if (comparisonFunction === 0) {
  15785. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15786. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15787. }
  15788. else {
  15789. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15790. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15791. }
  15792. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15793. }
  15794. texture._comparisonFunction = comparisonFunction;
  15795. };
  15796. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15797. var width = size.width || size;
  15798. var height = size.height || size;
  15799. internalTexture.baseWidth = width;
  15800. internalTexture.baseHeight = height;
  15801. internalTexture.width = width;
  15802. internalTexture.height = height;
  15803. internalTexture.isReady = true;
  15804. internalTexture.samples = 1;
  15805. internalTexture.generateMipMaps = false;
  15806. internalTexture._generateDepthBuffer = true;
  15807. internalTexture._generateStencilBuffer = generateStencil;
  15808. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15809. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15810. internalTexture._comparisonFunction = comparisonFunction;
  15811. var gl = this._gl;
  15812. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15813. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15814. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15815. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15816. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15817. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15818. if (comparisonFunction === 0) {
  15819. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15820. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15821. }
  15822. else {
  15823. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15824. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15825. }
  15826. };
  15827. /**
  15828. * Creates a depth stencil texture.
  15829. * This is only available in WebGL 2 or with the depth texture extension available.
  15830. * @param size The size of face edge in the texture.
  15831. * @param options The options defining the texture.
  15832. * @returns The texture
  15833. */
  15834. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15835. if (options.isCube) {
  15836. var width = size.width || size;
  15837. return this._createDepthStencilCubeTexture(width, options);
  15838. }
  15839. else {
  15840. return this._createDepthStencilTexture(size, options);
  15841. }
  15842. };
  15843. /**
  15844. * Creates a depth stencil texture.
  15845. * This is only available in WebGL 2 or with the depth texture extension available.
  15846. * @param size The size of face edge in the texture.
  15847. * @param options The options defining the texture.
  15848. * @returns The texture
  15849. */
  15850. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15851. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15852. if (!this._caps.depthTextureExtension) {
  15853. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15854. return internalTexture;
  15855. }
  15856. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15857. var gl = this._gl;
  15858. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15859. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15860. if (this.webGLVersion > 1) {
  15861. if (internalOptions.generateStencil) {
  15862. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15863. }
  15864. else {
  15865. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15866. }
  15867. }
  15868. else {
  15869. if (internalOptions.generateStencil) {
  15870. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15871. }
  15872. else {
  15873. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15874. }
  15875. }
  15876. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15877. return internalTexture;
  15878. };
  15879. /**
  15880. * Creates a depth stencil cube texture.
  15881. * This is only available in WebGL 2.
  15882. * @param size The size of face edge in the cube texture.
  15883. * @param options The options defining the cube texture.
  15884. * @returns The cube texture
  15885. */
  15886. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15887. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15888. internalTexture.isCube = true;
  15889. if (this.webGLVersion === 1) {
  15890. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15891. return internalTexture;
  15892. }
  15893. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15894. var gl = this._gl;
  15895. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15896. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15897. // Create the depth/stencil buffer
  15898. for (var face = 0; face < 6; face++) {
  15899. if (internalOptions.generateStencil) {
  15900. 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);
  15901. }
  15902. else {
  15903. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15904. }
  15905. }
  15906. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15907. return internalTexture;
  15908. };
  15909. /**
  15910. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15911. * @param renderTarget The render target to set the frame buffer for
  15912. */
  15913. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15914. // Create the framebuffer
  15915. var internalTexture = renderTarget.getInternalTexture();
  15916. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15917. return;
  15918. }
  15919. var gl = this._gl;
  15920. var depthStencilTexture = renderTarget.depthStencilTexture;
  15921. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15922. if (depthStencilTexture.isCube) {
  15923. if (depthStencilTexture._generateStencilBuffer) {
  15924. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15925. }
  15926. else {
  15927. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15928. }
  15929. }
  15930. else {
  15931. if (depthStencilTexture._generateStencilBuffer) {
  15932. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15933. }
  15934. else {
  15935. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15936. }
  15937. }
  15938. this.bindUnboundFramebuffer(null);
  15939. };
  15940. /**
  15941. * Creates a new render target texture
  15942. * @param size defines the size of the texture
  15943. * @param options defines the options used to create the texture
  15944. * @returns a new render target texture stored in an InternalTexture
  15945. */
  15946. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15947. var fullOptions = new RenderTargetCreationOptions();
  15948. if (options !== undefined && typeof options === "object") {
  15949. fullOptions.generateMipMaps = options.generateMipMaps;
  15950. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15951. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15952. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15953. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15954. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15955. }
  15956. else {
  15957. fullOptions.generateMipMaps = options;
  15958. fullOptions.generateDepthBuffer = true;
  15959. fullOptions.generateStencilBuffer = false;
  15960. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15961. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15962. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15963. }
  15964. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15965. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15966. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15967. }
  15968. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15969. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15970. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15971. }
  15972. var gl = this._gl;
  15973. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15974. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15975. var width = size.width || size;
  15976. var height = size.height || size;
  15977. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15978. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15979. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15980. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15981. }
  15982. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15983. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15984. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15985. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15986. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15987. // Create the framebuffer
  15988. var currentFrameBuffer = this._currentFramebuffer;
  15989. var framebuffer = gl.createFramebuffer();
  15990. this.bindUnboundFramebuffer(framebuffer);
  15991. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15992. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15993. if (fullOptions.generateMipMaps) {
  15994. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15995. }
  15996. // Unbind
  15997. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15998. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15999. this.bindUnboundFramebuffer(currentFrameBuffer);
  16000. texture._framebuffer = framebuffer;
  16001. texture.baseWidth = width;
  16002. texture.baseHeight = height;
  16003. texture.width = width;
  16004. texture.height = height;
  16005. texture.isReady = true;
  16006. texture.samples = 1;
  16007. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  16008. texture.samplingMode = fullOptions.samplingMode;
  16009. texture.type = fullOptions.type;
  16010. texture.format = fullOptions.format;
  16011. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16012. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  16013. // this.resetTextureCache();
  16014. this._internalTexturesCache.push(texture);
  16015. return texture;
  16016. };
  16017. /**
  16018. * Create a multi render target texture
  16019. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  16020. * @param size defines the size of the texture
  16021. * @param options defines the creation options
  16022. * @returns the cube texture as an InternalTexture
  16023. */
  16024. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  16025. var generateMipMaps = false;
  16026. var generateDepthBuffer = true;
  16027. var generateStencilBuffer = false;
  16028. var generateDepthTexture = false;
  16029. var textureCount = 1;
  16030. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  16031. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  16032. var types = new Array();
  16033. var samplingModes = new Array();
  16034. if (options !== undefined) {
  16035. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  16036. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  16037. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  16038. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  16039. textureCount = options.textureCount || 1;
  16040. if (options.types) {
  16041. types = options.types;
  16042. }
  16043. if (options.samplingModes) {
  16044. samplingModes = options.samplingModes;
  16045. }
  16046. }
  16047. var gl = this._gl;
  16048. // Create the framebuffer
  16049. var framebuffer = gl.createFramebuffer();
  16050. this.bindUnboundFramebuffer(framebuffer);
  16051. var width = size.width || size;
  16052. var height = size.height || size;
  16053. var textures = [];
  16054. var attachments = [];
  16055. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  16056. for (var i = 0; i < textureCount; i++) {
  16057. var samplingMode = samplingModes[i] || defaultSamplingMode;
  16058. var type = types[i] || defaultType;
  16059. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16060. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16061. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16062. }
  16063. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16064. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16065. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16066. }
  16067. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16068. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16069. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16070. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  16071. }
  16072. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16073. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16074. textures.push(texture);
  16075. attachments.push(attachment);
  16076. gl.activeTexture(gl["TEXTURE" + i]);
  16077. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  16078. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16079. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16080. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16081. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16082. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16083. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16084. if (generateMipMaps) {
  16085. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16086. }
  16087. // Unbind
  16088. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16089. texture._framebuffer = framebuffer;
  16090. texture._depthStencilBuffer = depthStencilBuffer;
  16091. texture.baseWidth = width;
  16092. texture.baseHeight = height;
  16093. texture.width = width;
  16094. texture.height = height;
  16095. texture.isReady = true;
  16096. texture.samples = 1;
  16097. texture.generateMipMaps = generateMipMaps;
  16098. texture.samplingMode = samplingMode;
  16099. texture.type = type;
  16100. texture._generateDepthBuffer = generateDepthBuffer;
  16101. texture._generateStencilBuffer = generateStencilBuffer;
  16102. texture._attachments = attachments;
  16103. this._internalTexturesCache.push(texture);
  16104. }
  16105. if (generateDepthTexture && this._caps.depthTextureExtension) {
  16106. // Depth texture
  16107. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16108. gl.activeTexture(gl.TEXTURE0);
  16109. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  16110. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16111. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16112. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16113. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16114. 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);
  16115. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  16116. depthTexture._framebuffer = framebuffer;
  16117. depthTexture.baseWidth = width;
  16118. depthTexture.baseHeight = height;
  16119. depthTexture.width = width;
  16120. depthTexture.height = height;
  16121. depthTexture.isReady = true;
  16122. depthTexture.samples = 1;
  16123. depthTexture.generateMipMaps = generateMipMaps;
  16124. depthTexture.samplingMode = gl.NEAREST;
  16125. depthTexture._generateDepthBuffer = generateDepthBuffer;
  16126. depthTexture._generateStencilBuffer = generateStencilBuffer;
  16127. textures.push(depthTexture);
  16128. this._internalTexturesCache.push(depthTexture);
  16129. }
  16130. gl.drawBuffers(attachments);
  16131. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16132. this.bindUnboundFramebuffer(null);
  16133. this.resetTextureCache();
  16134. return textures;
  16135. };
  16136. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  16137. if (samples === void 0) { samples = 1; }
  16138. var depthStencilBuffer = null;
  16139. var gl = this._gl;
  16140. // Create the depth/stencil buffer
  16141. if (generateStencilBuffer) {
  16142. depthStencilBuffer = gl.createRenderbuffer();
  16143. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16144. if (samples > 1) {
  16145. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  16146. }
  16147. else {
  16148. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  16149. }
  16150. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16151. }
  16152. else if (generateDepthBuffer) {
  16153. depthStencilBuffer = gl.createRenderbuffer();
  16154. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16155. if (samples > 1) {
  16156. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  16157. }
  16158. else {
  16159. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  16160. }
  16161. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16162. }
  16163. return depthStencilBuffer;
  16164. };
  16165. /**
  16166. * Updates the sample count of a render target texture
  16167. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16168. * @param texture defines the texture to update
  16169. * @param samples defines the sample count to set
  16170. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16171. */
  16172. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  16173. if (this.webGLVersion < 2 || !texture) {
  16174. return 1;
  16175. }
  16176. if (texture.samples === samples) {
  16177. return samples;
  16178. }
  16179. var gl = this._gl;
  16180. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16181. // Dispose previous render buffers
  16182. if (texture._depthStencilBuffer) {
  16183. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16184. texture._depthStencilBuffer = null;
  16185. }
  16186. if (texture._MSAAFramebuffer) {
  16187. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16188. texture._MSAAFramebuffer = null;
  16189. }
  16190. if (texture._MSAARenderBuffer) {
  16191. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16192. texture._MSAARenderBuffer = null;
  16193. }
  16194. if (samples > 1) {
  16195. var framebuffer = gl.createFramebuffer();
  16196. if (!framebuffer) {
  16197. throw new Error("Unable to create multi sampled framebuffer");
  16198. }
  16199. texture._MSAAFramebuffer = framebuffer;
  16200. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  16201. var colorRenderbuffer = gl.createRenderbuffer();
  16202. if (!colorRenderbuffer) {
  16203. throw new Error("Unable to create multi sampled framebuffer");
  16204. }
  16205. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16206. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16207. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  16208. texture._MSAARenderBuffer = colorRenderbuffer;
  16209. }
  16210. else {
  16211. this.bindUnboundFramebuffer(texture._framebuffer);
  16212. }
  16213. texture.samples = samples;
  16214. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  16215. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16216. this.bindUnboundFramebuffer(null);
  16217. return samples;
  16218. };
  16219. /**
  16220. * Update the sample count for a given multiple render target texture
  16221. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16222. * @param textures defines the textures to update
  16223. * @param samples defines the sample count to set
  16224. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16225. */
  16226. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  16227. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  16228. return 1;
  16229. }
  16230. if (textures[0].samples === samples) {
  16231. return samples;
  16232. }
  16233. var gl = this._gl;
  16234. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16235. // Dispose previous render buffers
  16236. if (textures[0]._depthStencilBuffer) {
  16237. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  16238. textures[0]._depthStencilBuffer = null;
  16239. }
  16240. if (textures[0]._MSAAFramebuffer) {
  16241. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  16242. textures[0]._MSAAFramebuffer = null;
  16243. }
  16244. for (var i = 0; i < textures.length; i++) {
  16245. if (textures[i]._MSAARenderBuffer) {
  16246. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  16247. textures[i]._MSAARenderBuffer = null;
  16248. }
  16249. }
  16250. if (samples > 1) {
  16251. var framebuffer = gl.createFramebuffer();
  16252. if (!framebuffer) {
  16253. throw new Error("Unable to create multi sampled framebuffer");
  16254. }
  16255. this.bindUnboundFramebuffer(framebuffer);
  16256. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  16257. var attachments = [];
  16258. for (var i = 0; i < textures.length; i++) {
  16259. var texture = textures[i];
  16260. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16261. var colorRenderbuffer = gl.createRenderbuffer();
  16262. if (!colorRenderbuffer) {
  16263. throw new Error("Unable to create multi sampled framebuffer");
  16264. }
  16265. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16266. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16267. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  16268. texture._MSAAFramebuffer = framebuffer;
  16269. texture._MSAARenderBuffer = colorRenderbuffer;
  16270. texture.samples = samples;
  16271. texture._depthStencilBuffer = depthStencilBuffer;
  16272. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16273. attachments.push(attachment);
  16274. }
  16275. gl.drawBuffers(attachments);
  16276. }
  16277. else {
  16278. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  16279. }
  16280. this.bindUnboundFramebuffer(null);
  16281. return samples;
  16282. };
  16283. /** @hidden */
  16284. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  16285. if (faceIndex === void 0) { faceIndex = 0; }
  16286. if (lod === void 0) { lod = 0; }
  16287. var gl = this._gl;
  16288. var target = gl.TEXTURE_2D;
  16289. if (texture.isCube) {
  16290. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16291. }
  16292. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  16293. };
  16294. /** @hidden */
  16295. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  16296. if (faceIndex === void 0) { faceIndex = 0; }
  16297. if (lod === void 0) { lod = 0; }
  16298. var gl = this._gl;
  16299. var textureType = this._getWebGLTextureType(texture.type);
  16300. var format = this._getInternalFormat(texture.format);
  16301. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16302. this._unpackFlipY(texture.invertY);
  16303. var target = gl.TEXTURE_2D;
  16304. if (texture.isCube) {
  16305. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16306. }
  16307. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  16308. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  16309. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  16310. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  16311. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  16312. };
  16313. /** @hidden */
  16314. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  16315. if (faceIndex === void 0) { faceIndex = 0; }
  16316. if (lod === void 0) { lod = 0; }
  16317. var gl = this._gl;
  16318. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16319. this._bindTextureDirectly(bindTarget, texture, true);
  16320. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  16321. this._bindTextureDirectly(bindTarget, null, true);
  16322. };
  16323. /** @hidden */
  16324. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  16325. if (faceIndex === void 0) { faceIndex = 0; }
  16326. if (lod === void 0) { lod = 0; }
  16327. var gl = this._gl;
  16328. var textureType = this._getWebGLTextureType(texture.type);
  16329. var format = this._getInternalFormat(texture.format);
  16330. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16331. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16332. this._bindTextureDirectly(bindTarget, texture, true);
  16333. this._unpackFlipY(texture.invertY);
  16334. var target = gl.TEXTURE_2D;
  16335. if (texture.isCube) {
  16336. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16337. }
  16338. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  16339. this._bindTextureDirectly(bindTarget, null, true);
  16340. };
  16341. /**
  16342. * Creates a new render target cube texture
  16343. * @param size defines the size of the texture
  16344. * @param options defines the options used to create the texture
  16345. * @returns a new render target cube texture stored in an InternalTexture
  16346. */
  16347. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  16348. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  16349. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  16350. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16351. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16352. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16353. }
  16354. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16355. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16356. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16357. }
  16358. var gl = this._gl;
  16359. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16360. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16361. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  16362. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16363. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16364. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  16365. }
  16366. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16367. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16368. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16369. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16370. for (var face = 0; face < 6; face++) {
  16371. 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);
  16372. }
  16373. // Create the framebuffer
  16374. var framebuffer = gl.createFramebuffer();
  16375. this.bindUnboundFramebuffer(framebuffer);
  16376. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  16377. // MipMaps
  16378. if (fullOptions.generateMipMaps) {
  16379. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16380. }
  16381. // Unbind
  16382. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16383. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16384. this.bindUnboundFramebuffer(null);
  16385. texture._framebuffer = framebuffer;
  16386. texture.width = size;
  16387. texture.height = size;
  16388. texture.isReady = true;
  16389. texture.isCube = true;
  16390. texture.samples = 1;
  16391. texture.generateMipMaps = fullOptions.generateMipMaps;
  16392. texture.samplingMode = fullOptions.samplingMode;
  16393. texture.type = fullOptions.type;
  16394. texture.format = fullOptions.format;
  16395. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16396. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  16397. this._internalTexturesCache.push(texture);
  16398. return texture;
  16399. };
  16400. /**
  16401. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  16402. * @param rootUrl defines the url where the file to load is located
  16403. * @param scene defines the current scene
  16404. * @param lodScale defines scale to apply to the mip map selection
  16405. * @param lodOffset defines offset to apply to the mip map selection
  16406. * @param onLoad defines an optional callback raised when the texture is loaded
  16407. * @param onError defines an optional callback raised if there is an issue to load the texture
  16408. * @param format defines the format of the data
  16409. * @param forcedExtension defines the extension to use to pick the right loader
  16410. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  16411. * @returns the cube texture as an InternalTexture
  16412. */
  16413. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  16414. var _this = this;
  16415. if (onLoad === void 0) { onLoad = null; }
  16416. if (onError === void 0) { onError = null; }
  16417. if (forcedExtension === void 0) { forcedExtension = null; }
  16418. if (createPolynomials === void 0) { createPolynomials = true; }
  16419. var callback = function (loadData) {
  16420. if (!loadData) {
  16421. if (onLoad) {
  16422. onLoad(null);
  16423. }
  16424. return;
  16425. }
  16426. var texture = loadData.texture;
  16427. if (!createPolynomials) {
  16428. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  16429. }
  16430. else if (loadData.info.sphericalPolynomial) {
  16431. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  16432. }
  16433. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  16434. if (_this._caps.textureLOD) {
  16435. // Do not add extra process if texture lod is supported.
  16436. if (onLoad) {
  16437. onLoad(texture);
  16438. }
  16439. return;
  16440. }
  16441. var mipSlices = 3;
  16442. var gl = _this._gl;
  16443. var width = loadData.width;
  16444. if (!width) {
  16445. return;
  16446. }
  16447. var textures = [];
  16448. for (var i = 0; i < mipSlices; i++) {
  16449. //compute LOD from even spacing in smoothness (matching shader calculation)
  16450. var smoothness = i / (mipSlices - 1);
  16451. var roughness = 1 - smoothness;
  16452. var minLODIndex = lodOffset; // roughness = 0
  16453. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  16454. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  16455. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  16456. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  16457. glTextureFromLod.type = texture.type;
  16458. glTextureFromLod.format = texture.format;
  16459. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  16460. glTextureFromLod.height = glTextureFromLod.width;
  16461. glTextureFromLod.isCube = true;
  16462. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  16463. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16464. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  16465. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16466. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16467. if (loadData.isDDS) {
  16468. var info = loadData.info;
  16469. var data = loadData.data;
  16470. _this._unpackFlipY(info.isCompressed);
  16471. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  16472. }
  16473. else {
  16474. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  16475. }
  16476. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16477. // Wrap in a base texture for easy binding.
  16478. var lodTexture = new BABYLON.BaseTexture(scene);
  16479. lodTexture.isCube = true;
  16480. lodTexture._texture = glTextureFromLod;
  16481. glTextureFromLod.isReady = true;
  16482. textures.push(lodTexture);
  16483. }
  16484. texture._lodTextureHigh = textures[2];
  16485. texture._lodTextureMid = textures[1];
  16486. texture._lodTextureLow = textures[0];
  16487. if (onLoad) {
  16488. onLoad(texture);
  16489. }
  16490. };
  16491. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  16492. };
  16493. /**
  16494. * Creates a cube texture
  16495. * @param rootUrl defines the url where the files to load is located
  16496. * @param scene defines the current scene
  16497. * @param files defines the list of files to load (1 per face)
  16498. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  16499. * @param onLoad defines an optional callback raised when the texture is loaded
  16500. * @param onError defines an optional callback raised if there is an issue to load the texture
  16501. * @param format defines the format of the data
  16502. * @param forcedExtension defines the extension to use to pick the right loader
  16503. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  16504. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  16505. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  16506. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  16507. * @returns the cube texture as an InternalTexture
  16508. */
  16509. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  16510. var _this = this;
  16511. if (onLoad === void 0) { onLoad = null; }
  16512. if (onError === void 0) { onError = null; }
  16513. if (forcedExtension === void 0) { forcedExtension = null; }
  16514. if (createPolynomials === void 0) { createPolynomials = false; }
  16515. if (lodScale === void 0) { lodScale = 0; }
  16516. if (lodOffset === void 0) { lodOffset = 0; }
  16517. if (fallback === void 0) { fallback = null; }
  16518. var gl = this._gl;
  16519. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  16520. texture.isCube = true;
  16521. texture.url = rootUrl;
  16522. texture.generateMipMaps = !noMipmap;
  16523. texture._lodGenerationScale = lodScale;
  16524. texture._lodGenerationOffset = lodOffset;
  16525. if (!this._doNotHandleContextLost) {
  16526. texture._extension = forcedExtension;
  16527. texture._files = files;
  16528. }
  16529. var lastDot = rootUrl.lastIndexOf('.');
  16530. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  16531. var loader = null;
  16532. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  16533. var availableLoader = _a[_i];
  16534. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  16535. loader = availableLoader;
  16536. break;
  16537. }
  16538. }
  16539. var onInternalError = function (request, exception) {
  16540. if (loader) {
  16541. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  16542. if (fallbackUrl) {
  16543. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  16544. }
  16545. }
  16546. if (onError && request) {
  16547. onError(request.status + " " + request.statusText, exception);
  16548. }
  16549. };
  16550. if (loader) {
  16551. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  16552. var onloaddata = function (data) {
  16553. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16554. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  16555. };
  16556. if (files && files.length === 6) {
  16557. if (loader.supportCascades) {
  16558. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  16559. }
  16560. else if (onError) {
  16561. onError("Textures type does not support cascades.");
  16562. }
  16563. }
  16564. else {
  16565. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  16566. }
  16567. }
  16568. else {
  16569. if (!files) {
  16570. throw new Error("Cannot load cubemap because files were not defined");
  16571. }
  16572. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  16573. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  16574. var height = width;
  16575. _this._prepareWorkingCanvas();
  16576. if (!_this._workingCanvas || !_this._workingContext) {
  16577. return;
  16578. }
  16579. _this._workingCanvas.width = width;
  16580. _this._workingCanvas.height = height;
  16581. var faces = [
  16582. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16583. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16584. ];
  16585. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16586. _this._unpackFlipY(false);
  16587. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16588. for (var index = 0; index < faces.length; index++) {
  16589. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16590. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16591. }
  16592. if (!noMipmap) {
  16593. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16594. }
  16595. _this._setCubeMapTextureParams(!noMipmap);
  16596. texture.width = width;
  16597. texture.height = height;
  16598. texture.isReady = true;
  16599. if (format) {
  16600. texture.format = format;
  16601. }
  16602. texture.onLoadedObservable.notifyObservers(texture);
  16603. texture.onLoadedObservable.clear();
  16604. if (onLoad) {
  16605. onLoad();
  16606. }
  16607. }, files, onError);
  16608. }
  16609. this._internalTexturesCache.push(texture);
  16610. return texture;
  16611. };
  16612. /**
  16613. * @hidden
  16614. */
  16615. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  16616. var gl = this._gl;
  16617. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16618. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16619. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16620. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16621. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16622. // this.resetTextureCache();
  16623. };
  16624. /**
  16625. * Update a raw cube texture
  16626. * @param texture defines the texture to udpdate
  16627. * @param data defines the data to store
  16628. * @param format defines the data format
  16629. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16630. * @param invertY defines if data must be stored with Y axis inverted
  16631. * @param compression defines the compression used (null by default)
  16632. * @param level defines which level of the texture to update
  16633. */
  16634. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16635. if (compression === void 0) { compression = null; }
  16636. if (level === void 0) { level = 0; }
  16637. texture._bufferViewArray = data;
  16638. texture.format = format;
  16639. texture.type = type;
  16640. texture.invertY = invertY;
  16641. texture._compression = compression;
  16642. var gl = this._gl;
  16643. var textureType = this._getWebGLTextureType(type);
  16644. var internalFormat = this._getInternalFormat(format);
  16645. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16646. var needConversion = false;
  16647. if (internalFormat === gl.RGB) {
  16648. internalFormat = gl.RGBA;
  16649. needConversion = true;
  16650. }
  16651. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16652. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16653. if (texture.width % 4 !== 0) {
  16654. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16655. }
  16656. // Data are known to be in +X +Y +Z -X -Y -Z
  16657. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16658. var faceData = data[faceIndex];
  16659. if (compression) {
  16660. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16661. }
  16662. else {
  16663. if (needConversion) {
  16664. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16665. }
  16666. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16667. }
  16668. }
  16669. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16670. if (isPot && texture.generateMipMaps && level === 0) {
  16671. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16672. }
  16673. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16674. // this.resetTextureCache();
  16675. texture.isReady = true;
  16676. };
  16677. /**
  16678. * Creates a new raw cube texture
  16679. * @param data defines the array of data to use to create each face
  16680. * @param size defines the size of the textures
  16681. * @param format defines the format of the data
  16682. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16683. * @param generateMipMaps defines if the engine should generate the mip levels
  16684. * @param invertY defines if data must be stored with Y axis inverted
  16685. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16686. * @param compression defines the compression used (null by default)
  16687. * @returns the cube texture as an InternalTexture
  16688. */
  16689. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16690. if (compression === void 0) { compression = null; }
  16691. var gl = this._gl;
  16692. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16693. texture.isCube = true;
  16694. texture.format = format;
  16695. texture.type = type;
  16696. if (!this._doNotHandleContextLost) {
  16697. texture._bufferViewArray = data;
  16698. }
  16699. var textureType = this._getWebGLTextureType(type);
  16700. var internalFormat = this._getInternalFormat(format);
  16701. if (internalFormat === gl.RGB) {
  16702. internalFormat = gl.RGBA;
  16703. }
  16704. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  16705. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16706. generateMipMaps = false;
  16707. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16708. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16709. }
  16710. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16711. generateMipMaps = false;
  16712. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16713. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16714. }
  16715. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  16716. generateMipMaps = false;
  16717. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  16718. }
  16719. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  16720. generateMipMaps = false;
  16721. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  16722. }
  16723. var width = size;
  16724. var height = width;
  16725. texture.width = width;
  16726. texture.height = height;
  16727. // Double check on POT to generate Mips.
  16728. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16729. if (!isPot) {
  16730. generateMipMaps = false;
  16731. }
  16732. // Upload data if needed. The texture won't be ready until then.
  16733. if (data) {
  16734. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16735. }
  16736. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16737. // Filters
  16738. if (data && generateMipMaps) {
  16739. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16740. }
  16741. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16742. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16743. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16744. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16745. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16746. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16747. texture.generateMipMaps = generateMipMaps;
  16748. return texture;
  16749. };
  16750. /**
  16751. * Creates a new raw cube texture from a specified url
  16752. * @param url defines the url where the data is located
  16753. * @param scene defines the current scene
  16754. * @param size defines the size of the textures
  16755. * @param format defines the format of the data
  16756. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16757. * @param noMipmap defines if the engine should avoid generating the mip levels
  16758. * @param callback defines a callback used to extract texture data from loaded data
  16759. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16760. * @param onLoad defines a callback called when texture is loaded
  16761. * @param onError defines a callback called if there is an error
  16762. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16763. * @param invertY defines if data must be stored with Y axis inverted
  16764. * @returns the cube texture as an InternalTexture
  16765. */
  16766. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16767. var _this = this;
  16768. if (onLoad === void 0) { onLoad = null; }
  16769. if (onError === void 0) { onError = null; }
  16770. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16771. if (invertY === void 0) { invertY = false; }
  16772. var gl = this._gl;
  16773. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16774. scene._addPendingData(texture);
  16775. texture.url = url;
  16776. this._internalTexturesCache.push(texture);
  16777. var onerror = function (request, exception) {
  16778. scene._removePendingData(texture);
  16779. if (onError && request) {
  16780. onError(request.status + " " + request.statusText, exception);
  16781. }
  16782. };
  16783. var internalCallback = function (data) {
  16784. var width = texture.width;
  16785. var faceDataArrays = callback(data);
  16786. if (!faceDataArrays) {
  16787. return;
  16788. }
  16789. if (mipmapGenerator) {
  16790. var textureType = _this._getWebGLTextureType(type);
  16791. var internalFormat = _this._getInternalFormat(format);
  16792. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16793. var needConversion = false;
  16794. if (internalFormat === gl.RGB) {
  16795. internalFormat = gl.RGBA;
  16796. needConversion = true;
  16797. }
  16798. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16799. _this._unpackFlipY(false);
  16800. var mipData = mipmapGenerator(faceDataArrays);
  16801. for (var level = 0; level < mipData.length; level++) {
  16802. var mipSize = width >> level;
  16803. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16804. var mipFaceData = mipData[level][faceIndex];
  16805. if (needConversion) {
  16806. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16807. }
  16808. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16809. }
  16810. }
  16811. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16812. }
  16813. else {
  16814. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16815. }
  16816. texture.isReady = true;
  16817. // this.resetTextureCache();
  16818. scene._removePendingData(texture);
  16819. if (onLoad) {
  16820. onLoad();
  16821. }
  16822. };
  16823. this._loadFile(url, function (data) {
  16824. internalCallback(data);
  16825. }, undefined, scene.database, true, onerror);
  16826. return texture;
  16827. };
  16828. /**
  16829. * Update a raw 3D texture
  16830. * @param texture defines the texture to update
  16831. * @param data defines the data to store
  16832. * @param format defines the data format
  16833. * @param invertY defines if data must be stored with Y axis inverted
  16834. * @param compression defines the used compression (can be null)
  16835. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16836. */
  16837. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16838. if (compression === void 0) { compression = null; }
  16839. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16840. var internalType = this._getWebGLTextureType(textureType);
  16841. var internalFormat = this._getInternalFormat(format);
  16842. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16843. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16844. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16845. if (!this._doNotHandleContextLost) {
  16846. texture._bufferView = data;
  16847. texture.format = format;
  16848. texture.invertY = invertY;
  16849. texture._compression = compression;
  16850. }
  16851. if (texture.width % 4 !== 0) {
  16852. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16853. }
  16854. if (compression && data) {
  16855. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16856. }
  16857. else {
  16858. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16859. }
  16860. if (texture.generateMipMaps) {
  16861. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16862. }
  16863. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16864. // this.resetTextureCache();
  16865. texture.isReady = true;
  16866. };
  16867. /**
  16868. * Creates a new raw 3D texture
  16869. * @param data defines the data used to create the texture
  16870. * @param width defines the width of the texture
  16871. * @param height defines the height of the texture
  16872. * @param depth defines the depth of the texture
  16873. * @param format defines the format of the texture
  16874. * @param generateMipMaps defines if the engine must generate mip levels
  16875. * @param invertY defines if data must be stored with Y axis inverted
  16876. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16877. * @param compression defines the compressed used (can be null)
  16878. * @param textureType defines the compressed used (can be null)
  16879. * @returns a new raw 3D texture (stored in an InternalTexture)
  16880. */
  16881. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16882. if (compression === void 0) { compression = null; }
  16883. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16884. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16885. texture.baseWidth = width;
  16886. texture.baseHeight = height;
  16887. texture.baseDepth = depth;
  16888. texture.width = width;
  16889. texture.height = height;
  16890. texture.depth = depth;
  16891. texture.format = format;
  16892. texture.type = textureType;
  16893. texture.generateMipMaps = generateMipMaps;
  16894. texture.samplingMode = samplingMode;
  16895. texture.is3D = true;
  16896. if (!this._doNotHandleContextLost) {
  16897. texture._bufferView = data;
  16898. }
  16899. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16900. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16901. // Filters
  16902. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16903. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16904. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16905. if (generateMipMaps) {
  16906. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16907. }
  16908. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16909. this._internalTexturesCache.push(texture);
  16910. return texture;
  16911. };
  16912. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16913. var gl = this._gl;
  16914. if (!gl) {
  16915. return;
  16916. }
  16917. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16918. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16919. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16920. if (!noMipmap && !isCompressed) {
  16921. gl.generateMipmap(gl.TEXTURE_2D);
  16922. }
  16923. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16924. // this.resetTextureCache();
  16925. if (scene) {
  16926. scene._removePendingData(texture);
  16927. }
  16928. texture.onLoadedObservable.notifyObservers(texture);
  16929. texture.onLoadedObservable.clear();
  16930. };
  16931. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16932. var _this = this;
  16933. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16934. var maxTextureSize = this.getCaps().maxTextureSize;
  16935. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16936. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16937. var gl = this._gl;
  16938. if (!gl) {
  16939. return;
  16940. }
  16941. if (!texture._webGLTexture) {
  16942. // this.resetTextureCache();
  16943. if (scene) {
  16944. scene._removePendingData(texture);
  16945. }
  16946. return;
  16947. }
  16948. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16949. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16950. texture.baseWidth = width;
  16951. texture.baseHeight = height;
  16952. texture.width = potWidth;
  16953. texture.height = potHeight;
  16954. texture.isReady = true;
  16955. if (processFunction(potWidth, potHeight, function () {
  16956. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16957. })) {
  16958. // Returning as texture needs extra async steps
  16959. return;
  16960. }
  16961. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16962. };
  16963. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16964. // Create new RGBA data container.
  16965. var rgbaData;
  16966. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16967. rgbaData = new Float32Array(width * height * 4);
  16968. }
  16969. else {
  16970. rgbaData = new Uint32Array(width * height * 4);
  16971. }
  16972. // Convert each pixel.
  16973. for (var x = 0; x < width; x++) {
  16974. for (var y = 0; y < height; y++) {
  16975. var index = (y * width + x) * 3;
  16976. var newIndex = (y * width + x) * 4;
  16977. // Map Old Value to new value.
  16978. rgbaData[newIndex + 0] = rgbData[index + 0];
  16979. rgbaData[newIndex + 1] = rgbData[index + 1];
  16980. rgbaData[newIndex + 2] = rgbData[index + 2];
  16981. // Add fully opaque alpha channel.
  16982. rgbaData[newIndex + 3] = 1;
  16983. }
  16984. }
  16985. return rgbaData;
  16986. };
  16987. /** @hidden */
  16988. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16989. var gl = this._gl;
  16990. if (texture._framebuffer) {
  16991. gl.deleteFramebuffer(texture._framebuffer);
  16992. texture._framebuffer = null;
  16993. }
  16994. if (texture._depthStencilBuffer) {
  16995. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16996. texture._depthStencilBuffer = null;
  16997. }
  16998. if (texture._MSAAFramebuffer) {
  16999. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  17000. texture._MSAAFramebuffer = null;
  17001. }
  17002. if (texture._MSAARenderBuffer) {
  17003. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  17004. texture._MSAARenderBuffer = null;
  17005. }
  17006. };
  17007. /** @hidden */
  17008. Engine.prototype._releaseTexture = function (texture) {
  17009. var gl = this._gl;
  17010. this._releaseFramebufferObjects(texture);
  17011. gl.deleteTexture(texture._webGLTexture);
  17012. // Unbind channels
  17013. this.unbindAllTextures();
  17014. var index = this._internalTexturesCache.indexOf(texture);
  17015. if (index !== -1) {
  17016. this._internalTexturesCache.splice(index, 1);
  17017. }
  17018. // Integrated fixed lod samplers.
  17019. if (texture._lodTextureHigh) {
  17020. texture._lodTextureHigh.dispose();
  17021. }
  17022. if (texture._lodTextureMid) {
  17023. texture._lodTextureMid.dispose();
  17024. }
  17025. if (texture._lodTextureLow) {
  17026. texture._lodTextureLow.dispose();
  17027. }
  17028. // Set output texture of post process to null if the texture has been released/disposed
  17029. this.scenes.forEach(function (scene) {
  17030. scene.postProcesses.forEach(function (postProcess) {
  17031. if (postProcess._outputTexture == texture) {
  17032. postProcess._outputTexture = null;
  17033. }
  17034. });
  17035. scene.cameras.forEach(function (camera) {
  17036. camera._postProcesses.forEach(function (postProcess) {
  17037. if (postProcess) {
  17038. if (postProcess._outputTexture == texture) {
  17039. postProcess._outputTexture = null;
  17040. }
  17041. }
  17042. });
  17043. });
  17044. });
  17045. };
  17046. Engine.prototype.setProgram = function (program) {
  17047. if (this._currentProgram !== program) {
  17048. this._gl.useProgram(program);
  17049. this._currentProgram = program;
  17050. }
  17051. };
  17052. /**
  17053. * Binds an effect to the webGL context
  17054. * @param effect defines the effect to bind
  17055. */
  17056. Engine.prototype.bindSamplers = function (effect) {
  17057. this.setProgram(effect.getProgram());
  17058. var samplers = effect.getSamplers();
  17059. for (var index = 0; index < samplers.length; index++) {
  17060. var uniform = effect.getUniform(samplers[index]);
  17061. if (uniform) {
  17062. this._boundUniforms[index] = uniform;
  17063. }
  17064. }
  17065. this._currentEffect = null;
  17066. };
  17067. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  17068. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  17069. return;
  17070. }
  17071. // Remove
  17072. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17073. // Bind last to it
  17074. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  17075. // Bind to dummy
  17076. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  17077. };
  17078. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  17079. if (!internalTexture) {
  17080. return -1;
  17081. }
  17082. internalTexture._initialSlot = channel;
  17083. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  17084. if (channel !== internalTexture._designatedSlot) {
  17085. this._textureCollisions.addCount(1, false);
  17086. }
  17087. }
  17088. else {
  17089. if (channel !== internalTexture._designatedSlot) {
  17090. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  17091. return internalTexture._designatedSlot;
  17092. }
  17093. else {
  17094. // No slot for this texture, let's pick a new one (if we find a free slot)
  17095. if (this._nextFreeTextureSlots.length) {
  17096. return this._nextFreeTextureSlots[0];
  17097. }
  17098. // We need to recycle the oldest bound texture, sorry.
  17099. this._textureCollisions.addCount(1, false);
  17100. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  17101. }
  17102. }
  17103. }
  17104. return channel;
  17105. };
  17106. Engine.prototype._linkTrackers = function (previous, next) {
  17107. previous.next = next;
  17108. next.previous = previous;
  17109. };
  17110. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  17111. var currentSlot = internalTexture._designatedSlot;
  17112. if (currentSlot === -1) {
  17113. return -1;
  17114. }
  17115. internalTexture._designatedSlot = -1;
  17116. if (this.disableTextureBindingOptimization) {
  17117. return -1;
  17118. }
  17119. // Remove from bound list
  17120. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17121. // Free the slot
  17122. this._boundTexturesCache[currentSlot] = null;
  17123. this._nextFreeTextureSlots.push(currentSlot);
  17124. return currentSlot;
  17125. };
  17126. Engine.prototype._activateCurrentTexture = function () {
  17127. if (this._currentTextureChannel !== this._activeChannel) {
  17128. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  17129. this._currentTextureChannel = this._activeChannel;
  17130. }
  17131. };
  17132. /** @hidden */
  17133. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  17134. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  17135. if (force === void 0) { force = false; }
  17136. var wasPreviouslyBound = false;
  17137. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  17138. this._activeChannel = texture._designatedSlot;
  17139. }
  17140. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  17141. var isTextureForRendering = texture && texture._initialSlot > -1;
  17142. if (currentTextureBound !== texture || force) {
  17143. if (currentTextureBound) {
  17144. this._removeDesignatedSlot(currentTextureBound);
  17145. }
  17146. this._activateCurrentTexture();
  17147. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  17148. this._boundTexturesCache[this._activeChannel] = texture;
  17149. if (texture) {
  17150. if (!this.disableTextureBindingOptimization) {
  17151. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  17152. if (slotIndex > -1) {
  17153. this._nextFreeTextureSlots.splice(slotIndex, 1);
  17154. }
  17155. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  17156. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  17157. }
  17158. texture._designatedSlot = this._activeChannel;
  17159. }
  17160. }
  17161. else if (forTextureDataUpdate) {
  17162. wasPreviouslyBound = true;
  17163. this._activateCurrentTexture();
  17164. }
  17165. if (isTextureForRendering && !forTextureDataUpdate) {
  17166. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  17167. }
  17168. return wasPreviouslyBound;
  17169. };
  17170. /** @hidden */
  17171. Engine.prototype._bindTexture = function (channel, texture) {
  17172. if (channel < 0) {
  17173. return;
  17174. }
  17175. if (texture) {
  17176. channel = this._getCorrectTextureChannel(channel, texture);
  17177. }
  17178. this._activeChannel = channel;
  17179. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  17180. };
  17181. /**
  17182. * Sets a texture to the webGL context from a postprocess
  17183. * @param channel defines the channel to use
  17184. * @param postProcess defines the source postprocess
  17185. */
  17186. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17187. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  17188. };
  17189. /**
  17190. * Binds the output of the passed in post process to the texture channel specified
  17191. * @param channel The channel the texture should be bound to
  17192. * @param postProcess The post process which's output should be bound
  17193. */
  17194. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  17195. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  17196. };
  17197. /**
  17198. * Unbind all textures from the webGL context
  17199. */
  17200. Engine.prototype.unbindAllTextures = function () {
  17201. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  17202. this._activeChannel = channel;
  17203. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17204. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17205. if (this.webGLVersion > 1) {
  17206. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17207. }
  17208. }
  17209. };
  17210. /**
  17211. * Sets a texture to the according uniform.
  17212. * @param channel The texture channel
  17213. * @param uniform The uniform to set
  17214. * @param texture The texture to apply
  17215. */
  17216. Engine.prototype.setTexture = function (channel, uniform, texture) {
  17217. if (channel < 0) {
  17218. return;
  17219. }
  17220. if (uniform) {
  17221. this._boundUniforms[channel] = uniform;
  17222. }
  17223. this._setTexture(channel, texture);
  17224. };
  17225. /**
  17226. * Sets a depth stencil texture from a render target to the according uniform.
  17227. * @param channel The texture channel
  17228. * @param uniform The uniform to set
  17229. * @param texture The render target texture containing the depth stencil texture to apply
  17230. */
  17231. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  17232. if (channel < 0) {
  17233. return;
  17234. }
  17235. if (uniform) {
  17236. this._boundUniforms[channel] = uniform;
  17237. }
  17238. if (!texture || !texture.depthStencilTexture) {
  17239. this._setTexture(channel, null);
  17240. }
  17241. else {
  17242. this._setTexture(channel, texture, false, true);
  17243. }
  17244. };
  17245. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  17246. var uniform = this._boundUniforms[sourceSlot];
  17247. if (uniform._currentState === destination) {
  17248. return;
  17249. }
  17250. this._gl.uniform1i(uniform, destination);
  17251. uniform._currentState = destination;
  17252. };
  17253. Engine.prototype._getTextureWrapMode = function (mode) {
  17254. switch (mode) {
  17255. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  17256. return this._gl.REPEAT;
  17257. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  17258. return this._gl.CLAMP_TO_EDGE;
  17259. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  17260. return this._gl.MIRRORED_REPEAT;
  17261. }
  17262. return this._gl.REPEAT;
  17263. };
  17264. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  17265. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  17266. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  17267. // Not ready?
  17268. if (!texture) {
  17269. if (this._boundTexturesCache[channel] != null) {
  17270. this._activeChannel = channel;
  17271. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17272. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17273. if (this.webGLVersion > 1) {
  17274. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17275. }
  17276. }
  17277. return false;
  17278. }
  17279. // Video
  17280. if (texture.video) {
  17281. this._activeChannel = channel;
  17282. texture.update();
  17283. }
  17284. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  17285. texture.delayLoad();
  17286. return false;
  17287. }
  17288. var internalTexture;
  17289. if (depthStencilTexture) {
  17290. internalTexture = texture.depthStencilTexture;
  17291. }
  17292. else if (texture.isReady()) {
  17293. internalTexture = texture.getInternalTexture();
  17294. }
  17295. else if (texture.isCube) {
  17296. internalTexture = this.emptyCubeTexture;
  17297. }
  17298. else if (texture.is3D) {
  17299. internalTexture = this.emptyTexture3D;
  17300. }
  17301. else {
  17302. internalTexture = this.emptyTexture;
  17303. }
  17304. if (!isPartOfTextureArray) {
  17305. channel = this._getCorrectTextureChannel(channel, internalTexture);
  17306. }
  17307. var needToBind = true;
  17308. if (this._boundTexturesCache[channel] === internalTexture) {
  17309. this._moveBoundTextureOnTop(internalTexture);
  17310. if (!isPartOfTextureArray) {
  17311. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  17312. }
  17313. needToBind = false;
  17314. }
  17315. this._activeChannel = channel;
  17316. if (internalTexture && internalTexture.is3D) {
  17317. if (needToBind) {
  17318. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  17319. }
  17320. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17321. internalTexture._cachedWrapU = texture.wrapU;
  17322. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17323. }
  17324. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17325. internalTexture._cachedWrapV = texture.wrapV;
  17326. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17327. }
  17328. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  17329. internalTexture._cachedWrapR = texture.wrapR;
  17330. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  17331. }
  17332. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  17333. }
  17334. else if (internalTexture && internalTexture.isCube) {
  17335. if (needToBind) {
  17336. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  17337. }
  17338. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  17339. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  17340. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  17341. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  17342. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  17343. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  17344. }
  17345. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  17346. }
  17347. else {
  17348. if (needToBind) {
  17349. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  17350. }
  17351. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17352. internalTexture._cachedWrapU = texture.wrapU;
  17353. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17354. }
  17355. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17356. internalTexture._cachedWrapV = texture.wrapV;
  17357. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17358. }
  17359. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  17360. }
  17361. return true;
  17362. };
  17363. /**
  17364. * Sets an array of texture to the webGL context
  17365. * @param channel defines the channel where the texture array must be set
  17366. * @param uniform defines the associated uniform location
  17367. * @param textures defines the array of textures to bind
  17368. */
  17369. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  17370. if (channel < 0 || !uniform) {
  17371. return;
  17372. }
  17373. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  17374. this._textureUnits = new Int32Array(textures.length);
  17375. }
  17376. for (var i = 0; i < textures.length; i++) {
  17377. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  17378. }
  17379. this._gl.uniform1iv(uniform, this._textureUnits);
  17380. for (var index = 0; index < textures.length; index++) {
  17381. this._setTexture(this._textureUnits[index], textures[index], true);
  17382. }
  17383. };
  17384. /** @hidden */
  17385. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  17386. var internalTexture = texture.getInternalTexture();
  17387. if (!internalTexture) {
  17388. return;
  17389. }
  17390. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  17391. var value = texture.anisotropicFilteringLevel;
  17392. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  17393. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  17394. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  17395. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  17396. }
  17397. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  17398. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  17399. internalTexture._cachedAnisotropicFilteringLevel = value;
  17400. }
  17401. };
  17402. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  17403. this._bindTextureDirectly(target, texture, true, true);
  17404. this._gl.texParameterf(target, parameter, value);
  17405. };
  17406. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  17407. if (texture) {
  17408. this._bindTextureDirectly(target, texture, true, true);
  17409. }
  17410. this._gl.texParameteri(target, parameter, value);
  17411. };
  17412. /**
  17413. * Reads pixels from the current frame buffer. Please note that this function can be slow
  17414. * @param x defines the x coordinate of the rectangle where pixels must be read
  17415. * @param y defines the y coordinate of the rectangle where pixels must be read
  17416. * @param width defines the width of the rectangle where pixels must be read
  17417. * @param height defines the height of the rectangle where pixels must be read
  17418. * @returns a Uint8Array containing RGBA colors
  17419. */
  17420. Engine.prototype.readPixels = function (x, y, width, height) {
  17421. var data = new Uint8Array(height * width * 4);
  17422. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  17423. return data;
  17424. };
  17425. /**
  17426. * Add an externaly attached data from its key.
  17427. * This method call will fail and return false, if such key already exists.
  17428. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17429. * @param key the unique key that identifies the data
  17430. * @param data the data object to associate to the key for this Engine instance
  17431. * @return true if no such key were already present and the data was added successfully, false otherwise
  17432. */
  17433. Engine.prototype.addExternalData = function (key, data) {
  17434. if (!this._externalData) {
  17435. this._externalData = new BABYLON.StringDictionary();
  17436. }
  17437. return this._externalData.add(key, data);
  17438. };
  17439. /**
  17440. * Get an externaly attached data from its key
  17441. * @param key the unique key that identifies the data
  17442. * @return the associated data, if present (can be null), or undefined if not present
  17443. */
  17444. Engine.prototype.getExternalData = function (key) {
  17445. if (!this._externalData) {
  17446. this._externalData = new BABYLON.StringDictionary();
  17447. }
  17448. return this._externalData.get(key);
  17449. };
  17450. /**
  17451. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17452. * @param key the unique key that identifies the data
  17453. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17454. * @return the associated data, can be null if the factory returned null.
  17455. */
  17456. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17457. if (!this._externalData) {
  17458. this._externalData = new BABYLON.StringDictionary();
  17459. }
  17460. return this._externalData.getOrAddWithFactory(key, factory);
  17461. };
  17462. /**
  17463. * Remove an externaly attached data from the Engine instance
  17464. * @param key the unique key that identifies the data
  17465. * @return true if the data was successfully removed, false if it doesn't exist
  17466. */
  17467. Engine.prototype.removeExternalData = function (key) {
  17468. if (!this._externalData) {
  17469. this._externalData = new BABYLON.StringDictionary();
  17470. }
  17471. return this._externalData.remove(key);
  17472. };
  17473. /**
  17474. * Unbind all vertex attributes from the webGL context
  17475. */
  17476. Engine.prototype.unbindAllAttributes = function () {
  17477. if (this._mustWipeVertexAttributes) {
  17478. this._mustWipeVertexAttributes = false;
  17479. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  17480. this._gl.disableVertexAttribArray(i);
  17481. this._vertexAttribArraysEnabled[i] = false;
  17482. this._currentBufferPointers[i].active = false;
  17483. }
  17484. return;
  17485. }
  17486. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  17487. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  17488. continue;
  17489. }
  17490. this._gl.disableVertexAttribArray(i);
  17491. this._vertexAttribArraysEnabled[i] = false;
  17492. this._currentBufferPointers[i].active = false;
  17493. }
  17494. };
  17495. /**
  17496. * 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
  17497. */
  17498. Engine.prototype.releaseEffects = function () {
  17499. for (var name in this._compiledEffects) {
  17500. this._deleteProgram(this._compiledEffects[name]._program);
  17501. }
  17502. this._compiledEffects = {};
  17503. };
  17504. /**
  17505. * Dispose and release all associated resources
  17506. */
  17507. Engine.prototype.dispose = function () {
  17508. this.hideLoadingUI();
  17509. this.stopRenderLoop();
  17510. // Release postProcesses
  17511. while (this.postProcesses.length) {
  17512. this.postProcesses[0].dispose();
  17513. }
  17514. // Empty texture
  17515. if (this._emptyTexture) {
  17516. this._releaseTexture(this._emptyTexture);
  17517. this._emptyTexture = null;
  17518. }
  17519. if (this._emptyCubeTexture) {
  17520. this._releaseTexture(this._emptyCubeTexture);
  17521. this._emptyCubeTexture = null;
  17522. }
  17523. // Rescale PP
  17524. if (this._rescalePostProcess) {
  17525. this._rescalePostProcess.dispose();
  17526. }
  17527. // Release scenes
  17528. while (this.scenes.length) {
  17529. this.scenes[0].dispose();
  17530. }
  17531. // Release audio engine
  17532. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  17533. Engine.audioEngine.dispose();
  17534. }
  17535. // Release effects
  17536. this.releaseEffects();
  17537. // Unbind
  17538. this.unbindAllAttributes();
  17539. this._boundUniforms = [];
  17540. if (this._dummyFramebuffer) {
  17541. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  17542. }
  17543. //WebVR
  17544. this.disableVR();
  17545. // Events
  17546. if (BABYLON.Tools.IsWindowObjectExist()) {
  17547. window.removeEventListener("blur", this._onBlur);
  17548. window.removeEventListener("focus", this._onFocus);
  17549. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  17550. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  17551. if (this._renderingCanvas) {
  17552. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  17553. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  17554. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  17555. if (!this._doNotHandleContextLost) {
  17556. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  17557. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  17558. }
  17559. }
  17560. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  17561. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  17562. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  17563. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  17564. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  17565. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  17566. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  17567. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  17568. if (this._onVrDisplayConnect) {
  17569. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  17570. if (this._onVrDisplayDisconnect) {
  17571. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  17572. }
  17573. if (this._onVrDisplayPresentChange) {
  17574. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  17575. }
  17576. this._onVrDisplayConnect = null;
  17577. this._onVrDisplayDisconnect = null;
  17578. }
  17579. }
  17580. // Remove from Instances
  17581. var index = Engine.Instances.indexOf(this);
  17582. if (index >= 0) {
  17583. Engine.Instances.splice(index, 1);
  17584. }
  17585. this._workingCanvas = null;
  17586. this._workingContext = null;
  17587. this._currentBufferPointers = [];
  17588. this._renderingCanvas = null;
  17589. this._currentProgram = null;
  17590. this._bindedRenderFunction = null;
  17591. this.onResizeObservable.clear();
  17592. this.onCanvasBlurObservable.clear();
  17593. this.onCanvasFocusObservable.clear();
  17594. this.onCanvasPointerOutObservable.clear();
  17595. this.onBeginFrameObservable.clear();
  17596. this.onEndFrameObservable.clear();
  17597. BABYLON.Effect.ResetCache();
  17598. // Abort active requests
  17599. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17600. var request = _a[_i];
  17601. request.abort();
  17602. }
  17603. };
  17604. // Loading screen
  17605. /**
  17606. * Display the loading screen
  17607. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17608. */
  17609. Engine.prototype.displayLoadingUI = function () {
  17610. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17611. return;
  17612. }
  17613. var loadingScreen = this.loadingScreen;
  17614. if (loadingScreen) {
  17615. loadingScreen.displayLoadingUI();
  17616. }
  17617. };
  17618. /**
  17619. * Hide the loading screen
  17620. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17621. */
  17622. Engine.prototype.hideLoadingUI = function () {
  17623. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17624. return;
  17625. }
  17626. var loadingScreen = this.loadingScreen;
  17627. if (loadingScreen) {
  17628. loadingScreen.hideLoadingUI();
  17629. }
  17630. };
  17631. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17632. /**
  17633. * Gets the current loading screen object
  17634. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17635. */
  17636. get: function () {
  17637. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas) {
  17638. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17639. }
  17640. return this._loadingScreen;
  17641. },
  17642. /**
  17643. * Sets the current loading screen object
  17644. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17645. */
  17646. set: function (loadingScreen) {
  17647. this._loadingScreen = loadingScreen;
  17648. },
  17649. enumerable: true,
  17650. configurable: true
  17651. });
  17652. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17653. /**
  17654. * Sets the current loading screen text
  17655. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17656. */
  17657. set: function (text) {
  17658. this.loadingScreen.loadingUIText = text;
  17659. },
  17660. enumerable: true,
  17661. configurable: true
  17662. });
  17663. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17664. /**
  17665. * Sets the current loading screen background color
  17666. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17667. */
  17668. set: function (color) {
  17669. this.loadingScreen.loadingUIBackgroundColor = color;
  17670. },
  17671. enumerable: true,
  17672. configurable: true
  17673. });
  17674. /**
  17675. * Attach a new callback raised when context lost event is fired
  17676. * @param callback defines the callback to call
  17677. */
  17678. Engine.prototype.attachContextLostEvent = function (callback) {
  17679. if (this._renderingCanvas) {
  17680. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17681. }
  17682. };
  17683. /**
  17684. * Attach a new callback raised when context restored event is fired
  17685. * @param callback defines the callback to call
  17686. */
  17687. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17688. if (this._renderingCanvas) {
  17689. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17690. }
  17691. };
  17692. /**
  17693. * Gets the source code of the vertex shader associated with a specific webGL program
  17694. * @param program defines the program to use
  17695. * @returns a string containing the source code of the vertex shader associated with the program
  17696. */
  17697. Engine.prototype.getVertexShaderSource = function (program) {
  17698. var shaders = this._gl.getAttachedShaders(program);
  17699. if (!shaders) {
  17700. return null;
  17701. }
  17702. return this._gl.getShaderSource(shaders[0]);
  17703. };
  17704. /**
  17705. * Gets the source code of the fragment shader associated with a specific webGL program
  17706. * @param program defines the program to use
  17707. * @returns a string containing the source code of the fragment shader associated with the program
  17708. */
  17709. Engine.prototype.getFragmentShaderSource = function (program) {
  17710. var shaders = this._gl.getAttachedShaders(program);
  17711. if (!shaders) {
  17712. return null;
  17713. }
  17714. return this._gl.getShaderSource(shaders[1]);
  17715. };
  17716. /**
  17717. * Get the current error code of the webGL context
  17718. * @returns the error code
  17719. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17720. */
  17721. Engine.prototype.getError = function () {
  17722. return this._gl.getError();
  17723. };
  17724. // FPS
  17725. /**
  17726. * Gets the current framerate
  17727. * @returns a number representing the framerate
  17728. */
  17729. Engine.prototype.getFps = function () {
  17730. return this._fps;
  17731. };
  17732. /**
  17733. * Gets the time spent between current and previous frame
  17734. * @returns a number representing the delta time in ms
  17735. */
  17736. Engine.prototype.getDeltaTime = function () {
  17737. return this._deltaTime;
  17738. };
  17739. Engine.prototype._measureFps = function () {
  17740. this._performanceMonitor.sampleFrame();
  17741. this._fps = this._performanceMonitor.averageFPS;
  17742. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17743. };
  17744. /** @hidden */
  17745. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17746. if (faceIndex === void 0) { faceIndex = -1; }
  17747. if (level === void 0) { level = 0; }
  17748. if (buffer === void 0) { buffer = null; }
  17749. var gl = this._gl;
  17750. if (!this._dummyFramebuffer) {
  17751. var dummy = gl.createFramebuffer();
  17752. if (!dummy) {
  17753. throw new Error("Unable to create dummy framebuffer");
  17754. }
  17755. this._dummyFramebuffer = dummy;
  17756. }
  17757. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17758. if (faceIndex > -1) {
  17759. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17760. }
  17761. else {
  17762. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17763. }
  17764. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17765. switch (readType) {
  17766. case gl.UNSIGNED_BYTE:
  17767. if (!buffer) {
  17768. buffer = new Uint8Array(4 * width * height);
  17769. }
  17770. readType = gl.UNSIGNED_BYTE;
  17771. break;
  17772. default:
  17773. if (!buffer) {
  17774. buffer = new Float32Array(4 * width * height);
  17775. }
  17776. readType = gl.FLOAT;
  17777. break;
  17778. }
  17779. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17780. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17781. return buffer;
  17782. };
  17783. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17784. if (this._webGLVersion > 1) {
  17785. return this._caps.colorBufferFloat;
  17786. }
  17787. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17788. };
  17789. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17790. if (this._webGLVersion > 1) {
  17791. return this._caps.colorBufferFloat;
  17792. }
  17793. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17794. };
  17795. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17796. Engine.prototype._canRenderToFramebuffer = function (type) {
  17797. var gl = this._gl;
  17798. //clear existing errors
  17799. while (gl.getError() !== gl.NO_ERROR) { }
  17800. var successful = true;
  17801. var texture = gl.createTexture();
  17802. gl.bindTexture(gl.TEXTURE_2D, texture);
  17803. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17804. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17805. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17806. var fb = gl.createFramebuffer();
  17807. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17808. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17809. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17810. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17811. successful = successful && (gl.getError() === gl.NO_ERROR);
  17812. //try render by clearing frame buffer's color buffer
  17813. if (successful) {
  17814. gl.clear(gl.COLOR_BUFFER_BIT);
  17815. successful = successful && (gl.getError() === gl.NO_ERROR);
  17816. }
  17817. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17818. if (successful) {
  17819. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17820. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17821. var readFormat = gl.RGBA;
  17822. var readType = gl.UNSIGNED_BYTE;
  17823. var buffer = new Uint8Array(4);
  17824. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17825. successful = successful && (gl.getError() === gl.NO_ERROR);
  17826. }
  17827. //clean up
  17828. gl.deleteTexture(texture);
  17829. gl.deleteFramebuffer(fb);
  17830. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17831. //clear accumulated errors
  17832. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17833. return successful;
  17834. };
  17835. /** @hidden */
  17836. Engine.prototype._getWebGLTextureType = function (type) {
  17837. if (this._webGLVersion === 1) {
  17838. switch (type) {
  17839. case Engine.TEXTURETYPE_FLOAT:
  17840. return this._gl.FLOAT;
  17841. case Engine.TEXTURETYPE_HALF_FLOAT:
  17842. return this._gl.HALF_FLOAT_OES;
  17843. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17844. return this._gl.UNSIGNED_BYTE;
  17845. }
  17846. return this._gl.UNSIGNED_BYTE;
  17847. }
  17848. switch (type) {
  17849. case Engine.TEXTURETYPE_BYTE:
  17850. return this._gl.BYTE;
  17851. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17852. return this._gl.UNSIGNED_BYTE;
  17853. case Engine.TEXTURETYPE_SHORT:
  17854. return this._gl.SHORT;
  17855. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17856. return this._gl.UNSIGNED_SHORT;
  17857. case Engine.TEXTURETYPE_INT:
  17858. return this._gl.INT;
  17859. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17860. return this._gl.UNSIGNED_INT;
  17861. case Engine.TEXTURETYPE_FLOAT:
  17862. return this._gl.FLOAT;
  17863. case Engine.TEXTURETYPE_HALF_FLOAT:
  17864. return this._gl.HALF_FLOAT;
  17865. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17866. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17867. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17868. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17869. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17870. return this._gl.UNSIGNED_SHORT_5_6_5;
  17871. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17872. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17873. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17874. return this._gl.UNSIGNED_INT_24_8;
  17875. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17876. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17877. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17878. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17879. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17880. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17881. }
  17882. return this._gl.UNSIGNED_BYTE;
  17883. };
  17884. Engine.prototype._getInternalFormat = function (format) {
  17885. var internalFormat = this._gl.RGBA;
  17886. switch (format) {
  17887. case Engine.TEXTUREFORMAT_ALPHA:
  17888. internalFormat = this._gl.ALPHA;
  17889. break;
  17890. case Engine.TEXTUREFORMAT_LUMINANCE:
  17891. internalFormat = this._gl.LUMINANCE;
  17892. break;
  17893. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17894. internalFormat = this._gl.LUMINANCE_ALPHA;
  17895. break;
  17896. case Engine.TEXTUREFORMAT_RED:
  17897. internalFormat = this._gl.RED;
  17898. break;
  17899. case Engine.TEXTUREFORMAT_RG:
  17900. internalFormat = this._gl.RG;
  17901. break;
  17902. case Engine.TEXTUREFORMAT_RGB:
  17903. internalFormat = this._gl.RGB;
  17904. break;
  17905. case Engine.TEXTUREFORMAT_RGBA:
  17906. internalFormat = this._gl.RGBA;
  17907. break;
  17908. }
  17909. if (this._webGLVersion > 1) {
  17910. switch (format) {
  17911. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17912. internalFormat = this._gl.RED_INTEGER;
  17913. break;
  17914. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17915. internalFormat = this._gl.RG_INTEGER;
  17916. break;
  17917. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17918. internalFormat = this._gl.RGB_INTEGER;
  17919. break;
  17920. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17921. internalFormat = this._gl.RGBA_INTEGER;
  17922. break;
  17923. }
  17924. }
  17925. return internalFormat;
  17926. };
  17927. /** @hidden */
  17928. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17929. if (this._webGLVersion === 1) {
  17930. if (format !== undefined) {
  17931. switch (format) {
  17932. case Engine.TEXTUREFORMAT_ALPHA:
  17933. return this._gl.ALPHA;
  17934. case Engine.TEXTUREFORMAT_LUMINANCE:
  17935. return this._gl.LUMINANCE;
  17936. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17937. return this._gl.LUMINANCE_ALPHA;
  17938. }
  17939. }
  17940. return this._gl.RGBA;
  17941. }
  17942. switch (type) {
  17943. case Engine.TEXTURETYPE_BYTE:
  17944. switch (format) {
  17945. case Engine.TEXTUREFORMAT_RED:
  17946. return this._gl.R8_SNORM;
  17947. case Engine.TEXTUREFORMAT_RG:
  17948. return this._gl.RG8_SNORM;
  17949. case Engine.TEXTUREFORMAT_RGB:
  17950. return this._gl.RGB8_SNORM;
  17951. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17952. return this._gl.R8I;
  17953. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17954. return this._gl.RG8I;
  17955. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17956. return this._gl.RGB8I;
  17957. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17958. return this._gl.RGBA8I;
  17959. default:
  17960. return this._gl.RGBA8_SNORM;
  17961. }
  17962. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17963. switch (format) {
  17964. case Engine.TEXTUREFORMAT_RED:
  17965. return this._gl.R8;
  17966. case Engine.TEXTUREFORMAT_RG:
  17967. return this._gl.RG8;
  17968. case Engine.TEXTUREFORMAT_RGB:
  17969. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17970. case Engine.TEXTUREFORMAT_RGBA:
  17971. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17972. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17973. return this._gl.R8UI;
  17974. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17975. return this._gl.RG8UI;
  17976. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17977. return this._gl.RGB8UI;
  17978. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17979. return this._gl.RGBA8UI;
  17980. default:
  17981. return this._gl.RGBA8;
  17982. }
  17983. case Engine.TEXTURETYPE_SHORT:
  17984. switch (format) {
  17985. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17986. return this._gl.R16I;
  17987. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17988. return this._gl.RG16I;
  17989. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17990. return this._gl.RGB16I;
  17991. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17992. return this._gl.RGBA16I;
  17993. default:
  17994. return this._gl.RGBA16I;
  17995. }
  17996. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17997. switch (format) {
  17998. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17999. return this._gl.R16UI;
  18000. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18001. return this._gl.RG16UI;
  18002. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18003. return this._gl.RGB16UI;
  18004. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18005. return this._gl.RGBA16UI;
  18006. default:
  18007. return this._gl.RGBA16UI;
  18008. }
  18009. case Engine.TEXTURETYPE_INT:
  18010. switch (format) {
  18011. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18012. return this._gl.R32I;
  18013. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18014. return this._gl.RG32I;
  18015. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18016. return this._gl.RGB32I;
  18017. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18018. return this._gl.RGBA32I;
  18019. default:
  18020. return this._gl.RGBA32I;
  18021. }
  18022. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  18023. switch (format) {
  18024. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18025. return this._gl.R32UI;
  18026. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18027. return this._gl.RG32UI;
  18028. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18029. return this._gl.RGB32UI;
  18030. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18031. return this._gl.RGBA32UI;
  18032. default:
  18033. return this._gl.RGBA32UI;
  18034. }
  18035. case Engine.TEXTURETYPE_FLOAT:
  18036. switch (format) {
  18037. case Engine.TEXTUREFORMAT_RED:
  18038. return this._gl.R32F; // By default. Other possibility is R16F.
  18039. case Engine.TEXTUREFORMAT_RG:
  18040. return this._gl.RG32F; // By default. Other possibility is RG16F.
  18041. case Engine.TEXTUREFORMAT_RGB:
  18042. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  18043. case Engine.TEXTUREFORMAT_RGBA:
  18044. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  18045. default:
  18046. return this._gl.RGBA32F;
  18047. }
  18048. case Engine.TEXTURETYPE_HALF_FLOAT:
  18049. switch (format) {
  18050. case Engine.TEXTUREFORMAT_RED:
  18051. return this._gl.R16F;
  18052. case Engine.TEXTUREFORMAT_RG:
  18053. return this._gl.RG16F;
  18054. case Engine.TEXTUREFORMAT_RGB:
  18055. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  18056. case Engine.TEXTUREFORMAT_RGBA:
  18057. return this._gl.RGBA16F;
  18058. default:
  18059. return this._gl.RGBA16F;
  18060. }
  18061. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  18062. return this._gl.RGB565;
  18063. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  18064. return this._gl.R11F_G11F_B10F;
  18065. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  18066. return this._gl.RGB9_E5;
  18067. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  18068. return this._gl.RGBA4;
  18069. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  18070. return this._gl.RGB5_A1;
  18071. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  18072. switch (format) {
  18073. case Engine.TEXTUREFORMAT_RGBA:
  18074. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  18075. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18076. return this._gl.RGB10_A2UI;
  18077. default:
  18078. return this._gl.RGB10_A2;
  18079. }
  18080. }
  18081. return this._gl.RGBA8;
  18082. };
  18083. /** @hidden */
  18084. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  18085. if (type === Engine.TEXTURETYPE_FLOAT) {
  18086. return this._gl.RGBA32F;
  18087. }
  18088. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  18089. return this._gl.RGBA16F;
  18090. }
  18091. return this._gl.RGBA8;
  18092. };
  18093. /** @hidden */
  18094. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  18095. var _this = this;
  18096. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  18097. this._activeRequests.push(request);
  18098. request.onCompleteObservable.add(function (request) {
  18099. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  18100. });
  18101. return request;
  18102. };
  18103. /** @hidden */
  18104. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  18105. var _this = this;
  18106. return new Promise(function (resolve, reject) {
  18107. _this._loadFile(url, function (data) {
  18108. resolve(data);
  18109. }, undefined, database, useArrayBuffer, function (request, exception) {
  18110. reject(exception);
  18111. });
  18112. });
  18113. };
  18114. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  18115. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  18116. var onload = function (data) {
  18117. loadedFiles[index] = data;
  18118. loadedFiles._internalCount++;
  18119. if (loadedFiles._internalCount === 6) {
  18120. onfinish(loadedFiles);
  18121. }
  18122. };
  18123. var onerror = function (request, exception) {
  18124. if (onErrorCallBack && request) {
  18125. onErrorCallBack(request.status + " " + request.statusText, exception);
  18126. }
  18127. };
  18128. this._loadFile(url, onload, undefined, undefined, true, onerror);
  18129. };
  18130. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  18131. if (onError === void 0) { onError = null; }
  18132. var loadedFiles = [];
  18133. loadedFiles._internalCount = 0;
  18134. for (var index = 0; index < 6; index++) {
  18135. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  18136. }
  18137. };
  18138. // Statics
  18139. /**
  18140. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  18141. * @returns true if the engine can be created
  18142. * @ignorenaming
  18143. */
  18144. Engine.isSupported = function () {
  18145. try {
  18146. var tempcanvas = document.createElement("canvas");
  18147. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  18148. return gl != null && !!window.WebGLRenderingContext;
  18149. }
  18150. catch (e) {
  18151. return false;
  18152. }
  18153. };
  18154. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  18155. Engine.ExceptionList = [
  18156. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  18157. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18158. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18159. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18160. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18161. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  18162. ];
  18163. /** Gets the list of created engines */
  18164. Engine.Instances = new Array();
  18165. /**
  18166. * Hidden
  18167. */
  18168. Engine._TextureLoaders = [];
  18169. // Const statics
  18170. /** Defines that alpha blending is disabled */
  18171. Engine.ALPHA_DISABLE = 0;
  18172. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  18173. Engine.ALPHA_ADD = 1;
  18174. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  18175. Engine.ALPHA_COMBINE = 2;
  18176. /** Defines that alpha blending to DEST - SRC * DEST */
  18177. Engine.ALPHA_SUBTRACT = 3;
  18178. /** Defines that alpha blending to SRC * DEST */
  18179. Engine.ALPHA_MULTIPLY = 4;
  18180. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  18181. Engine.ALPHA_MAXIMIZED = 5;
  18182. /** Defines that alpha blending to SRC + DEST */
  18183. Engine.ALPHA_ONEONE = 6;
  18184. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  18185. Engine.ALPHA_PREMULTIPLIED = 7;
  18186. /**
  18187. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  18188. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  18189. */
  18190. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  18191. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  18192. Engine.ALPHA_INTERPOLATE = 9;
  18193. /**
  18194. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  18195. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  18196. */
  18197. Engine.ALPHA_SCREENMODE = 10;
  18198. /** Defines that the ressource is not delayed*/
  18199. Engine.DELAYLOADSTATE_NONE = 0;
  18200. /** Defines that the ressource was successfully delay loaded */
  18201. Engine.DELAYLOADSTATE_LOADED = 1;
  18202. /** Defines that the ressource is currently delay loading */
  18203. Engine.DELAYLOADSTATE_LOADING = 2;
  18204. /** Defines that the ressource is delayed and has not started loading */
  18205. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  18206. // Depht or Stencil test Constants.
  18207. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  18208. Engine.NEVER = 0x0200;
  18209. /** 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 */
  18210. Engine.ALWAYS = 0x0207;
  18211. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  18212. Engine.LESS = 0x0201;
  18213. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  18214. Engine.EQUAL = 0x0202;
  18215. /** 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 */
  18216. Engine.LEQUAL = 0x0203;
  18217. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  18218. Engine.GREATER = 0x0204;
  18219. /** 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 */
  18220. Engine.GEQUAL = 0x0206;
  18221. /** 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 */
  18222. Engine.NOTEQUAL = 0x0205;
  18223. // Stencil Actions Constants.
  18224. /** Passed to stencilOperation to specify that stencil value must be kept */
  18225. Engine.KEEP = 0x1E00;
  18226. /** Passed to stencilOperation to specify that stencil value must be replaced */
  18227. Engine.REPLACE = 0x1E01;
  18228. /** Passed to stencilOperation to specify that stencil value must be incremented */
  18229. Engine.INCR = 0x1E02;
  18230. /** Passed to stencilOperation to specify that stencil value must be decremented */
  18231. Engine.DECR = 0x1E03;
  18232. /** Passed to stencilOperation to specify that stencil value must be inverted */
  18233. Engine.INVERT = 0x150A;
  18234. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  18235. Engine.INCR_WRAP = 0x8507;
  18236. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  18237. Engine.DECR_WRAP = 0x8508;
  18238. /** Texture is not repeating outside of 0..1 UVs */
  18239. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  18240. /** Texture is repeating outside of 0..1 UVs */
  18241. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  18242. /** Texture is repeating and mirrored */
  18243. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  18244. /** ALPHA */
  18245. Engine.TEXTUREFORMAT_ALPHA = 0;
  18246. /** LUMINANCE */
  18247. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  18248. /** LUMINANCE_ALPHA */
  18249. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  18250. /** RGB */
  18251. Engine.TEXTUREFORMAT_RGB = 4;
  18252. /** RGBA */
  18253. Engine.TEXTUREFORMAT_RGBA = 5;
  18254. /** RED */
  18255. Engine.TEXTUREFORMAT_RED = 6;
  18256. /** RED (2nd reference) */
  18257. Engine.TEXTUREFORMAT_R = 6;
  18258. /** RG */
  18259. Engine.TEXTUREFORMAT_RG = 7;
  18260. /** RED_INTEGER */
  18261. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  18262. /** RED_INTEGER (2nd reference) */
  18263. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  18264. /** RG_INTEGER */
  18265. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  18266. /** RGB_INTEGER */
  18267. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  18268. /** RGBA_INTEGER */
  18269. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  18270. /** UNSIGNED_BYTE */
  18271. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  18272. /** UNSIGNED_BYTE (2nd reference) */
  18273. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  18274. /** FLOAT */
  18275. Engine.TEXTURETYPE_FLOAT = 1;
  18276. /** HALF_FLOAT */
  18277. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  18278. /** BYTE */
  18279. Engine.TEXTURETYPE_BYTE = 3;
  18280. /** SHORT */
  18281. Engine.TEXTURETYPE_SHORT = 4;
  18282. /** UNSIGNED_SHORT */
  18283. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  18284. /** INT */
  18285. Engine.TEXTURETYPE_INT = 6;
  18286. /** UNSIGNED_INT */
  18287. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  18288. /** UNSIGNED_SHORT_4_4_4_4 */
  18289. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  18290. /** UNSIGNED_SHORT_5_5_5_1 */
  18291. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  18292. /** UNSIGNED_SHORT_5_6_5 */
  18293. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  18294. /** UNSIGNED_INT_2_10_10_10_REV */
  18295. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  18296. /** UNSIGNED_INT_24_8 */
  18297. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  18298. /** UNSIGNED_INT_10F_11F_11F_REV */
  18299. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  18300. /** UNSIGNED_INT_5_9_9_9_REV */
  18301. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  18302. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  18303. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  18304. /** nearest is mag = nearest and min = nearest and mip = linear */
  18305. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  18306. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18307. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  18308. /** Trilinear is mag = linear and min = linear and mip = linear */
  18309. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  18310. /** nearest is mag = nearest and min = nearest and mip = linear */
  18311. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  18312. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18313. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  18314. /** Trilinear is mag = linear and min = linear and mip = linear */
  18315. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  18316. /** mag = nearest and min = nearest and mip = nearest */
  18317. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  18318. /** mag = nearest and min = linear and mip = nearest */
  18319. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  18320. /** mag = nearest and min = linear and mip = linear */
  18321. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  18322. /** mag = nearest and min = linear and mip = none */
  18323. Engine.TEXTURE_NEAREST_LINEAR = 7;
  18324. /** mag = nearest and min = nearest and mip = none */
  18325. Engine.TEXTURE_NEAREST_NEAREST = 8;
  18326. /** mag = linear and min = nearest and mip = nearest */
  18327. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  18328. /** mag = linear and min = nearest and mip = linear */
  18329. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  18330. /** mag = linear and min = linear and mip = none */
  18331. Engine.TEXTURE_LINEAR_LINEAR = 11;
  18332. /** mag = linear and min = nearest and mip = none */
  18333. Engine.TEXTURE_LINEAR_NEAREST = 12;
  18334. /** Explicit coordinates mode */
  18335. Engine.TEXTURE_EXPLICIT_MODE = 0;
  18336. /** Spherical coordinates mode */
  18337. Engine.TEXTURE_SPHERICAL_MODE = 1;
  18338. /** Planar coordinates mode */
  18339. Engine.TEXTURE_PLANAR_MODE = 2;
  18340. /** Cubic coordinates mode */
  18341. Engine.TEXTURE_CUBIC_MODE = 3;
  18342. /** Projection coordinates mode */
  18343. Engine.TEXTURE_PROJECTION_MODE = 4;
  18344. /** Skybox coordinates mode */
  18345. Engine.TEXTURE_SKYBOX_MODE = 5;
  18346. /** Inverse Cubic coordinates mode */
  18347. Engine.TEXTURE_INVCUBIC_MODE = 6;
  18348. /** Equirectangular coordinates mode */
  18349. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  18350. /** Equirectangular Fixed coordinates mode */
  18351. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  18352. /** Equirectangular Fixed Mirrored coordinates mode */
  18353. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18354. // Texture rescaling mode
  18355. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  18356. Engine.SCALEMODE_FLOOR = 1;
  18357. /** Defines that texture rescaling will look for the nearest power of 2 size */
  18358. Engine.SCALEMODE_NEAREST = 2;
  18359. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  18360. Engine.SCALEMODE_CEILING = 3;
  18361. // Updatable statics so stick with vars here
  18362. /**
  18363. * Gets or sets the epsilon value used by collision engine
  18364. */
  18365. Engine.CollisionsEpsilon = 0.001;
  18366. /**
  18367. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  18368. */
  18369. Engine.CodeRepository = "src/";
  18370. /**
  18371. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  18372. */
  18373. Engine.ShadersRepository = "src/Shaders/";
  18374. return Engine;
  18375. }());
  18376. BABYLON.Engine = Engine;
  18377. })(BABYLON || (BABYLON = {}));
  18378. //# sourceMappingURL=babylon.engine.js.map
  18379. var BABYLON;
  18380. (function (BABYLON) {
  18381. /**
  18382. * Node is the basic class for all scene objects (Mesh, Light, Camera.)
  18383. */
  18384. var Node = /** @class */ (function () {
  18385. /**
  18386. * Creates a new Node
  18387. * @param name the name and id to be given to this node
  18388. * @param scene the scene this node will be added to
  18389. */
  18390. function Node(name, scene) {
  18391. if (scene === void 0) { scene = null; }
  18392. /**
  18393. * Gets or sets a string used to store user defined state for the node
  18394. */
  18395. this.state = "";
  18396. /**
  18397. * Gets or sets an object used to store user defined information for the node
  18398. */
  18399. this.metadata = null;
  18400. /**
  18401. * Gets or sets a boolean used to define if the node must be serialized
  18402. */
  18403. this.doNotSerialize = false;
  18404. /** @hidden */
  18405. this._isDisposed = false;
  18406. /**
  18407. * Gets a list of Animations associated with the node
  18408. */
  18409. this.animations = new Array();
  18410. this._ranges = {};
  18411. this._isEnabled = true;
  18412. this._isParentEnabled = true;
  18413. this._isReady = true;
  18414. /** @hidden */
  18415. this._currentRenderId = -1;
  18416. this._parentRenderId = -1;
  18417. this._childRenderId = -1;
  18418. /** @hidden */
  18419. this._worldMatrix = BABYLON.Matrix.Identity();
  18420. /** @hidden */
  18421. this._worldMatrixDeterminant = 0;
  18422. /** @hidden */
  18423. this._sceneRootNodesIndex = -1;
  18424. this._animationPropertiesOverride = null;
  18425. /**
  18426. * An event triggered when the mesh is disposed
  18427. */
  18428. this.onDisposeObservable = new BABYLON.Observable();
  18429. // Behaviors
  18430. this._behaviors = new Array();
  18431. this.name = name;
  18432. this.id = name;
  18433. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  18434. this.uniqueId = this._scene.getUniqueId();
  18435. this._initCache();
  18436. this.addToSceneRootNodes();
  18437. }
  18438. /**
  18439. * Add a new node constructor
  18440. * @param type defines the type name of the node to construct
  18441. * @param constructorFunc defines the constructor function
  18442. */
  18443. Node.AddNodeConstructor = function (type, constructorFunc) {
  18444. this._NodeConstructors[type] = constructorFunc;
  18445. };
  18446. /**
  18447. * Returns a node constructor based on type name
  18448. * @param type defines the type name
  18449. * @param name defines the new node name
  18450. * @param scene defines the hosting scene
  18451. * @param options defines optional options to transmit to constructors
  18452. * @returns the new constructor or null
  18453. */
  18454. Node.Construct = function (type, name, scene, options) {
  18455. var constructorFunc = this._NodeConstructors[type];
  18456. if (!constructorFunc) {
  18457. return null;
  18458. }
  18459. return constructorFunc(name, scene, options);
  18460. };
  18461. /**
  18462. * Gets a boolean indicating if the node has been disposed
  18463. * @returns true if the node was disposed
  18464. */
  18465. Node.prototype.isDisposed = function () {
  18466. return this._isDisposed;
  18467. };
  18468. Object.defineProperty(Node.prototype, "parent", {
  18469. get: function () {
  18470. return this._parentNode;
  18471. },
  18472. /**
  18473. * Gets or sets the parent of the node
  18474. */
  18475. set: function (parent) {
  18476. if (this._parentNode === parent) {
  18477. return;
  18478. }
  18479. var previousParentNode = this._parentNode;
  18480. // Remove self from list of children of parent
  18481. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  18482. var index = this._parentNode._children.indexOf(this);
  18483. if (index !== -1) {
  18484. this._parentNode._children.splice(index, 1);
  18485. }
  18486. if (!parent) {
  18487. this.addToSceneRootNodes();
  18488. }
  18489. }
  18490. // Store new parent
  18491. this._parentNode = parent;
  18492. // Add as child to new parent
  18493. if (this._parentNode) {
  18494. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  18495. this._parentNode._children = new Array();
  18496. }
  18497. this._parentNode._children.push(this);
  18498. if (!previousParentNode) {
  18499. this.removeFromSceneRootNodes();
  18500. }
  18501. }
  18502. // Enabled state
  18503. this._syncParentEnabledState();
  18504. },
  18505. enumerable: true,
  18506. configurable: true
  18507. });
  18508. Node.prototype.addToSceneRootNodes = function () {
  18509. if (this._sceneRootNodesIndex === -1) {
  18510. this._sceneRootNodesIndex = this._scene.rootNodes.length;
  18511. this._scene.rootNodes.push(this);
  18512. }
  18513. };
  18514. Node.prototype.removeFromSceneRootNodes = function () {
  18515. if (this._sceneRootNodesIndex !== -1) {
  18516. var rootNodes = this._scene.rootNodes;
  18517. var lastIdx = rootNodes.length - 1;
  18518. rootNodes[this._sceneRootNodesIndex] = rootNodes[lastIdx];
  18519. rootNodes[this._sceneRootNodesIndex]._sceneRootNodesIndex = this._sceneRootNodesIndex;
  18520. this._scene.rootNodes.pop();
  18521. this._sceneRootNodesIndex = -1;
  18522. }
  18523. };
  18524. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  18525. /**
  18526. * Gets or sets the animation properties override
  18527. */
  18528. get: function () {
  18529. if (!this._animationPropertiesOverride) {
  18530. return this._scene.animationPropertiesOverride;
  18531. }
  18532. return this._animationPropertiesOverride;
  18533. },
  18534. set: function (value) {
  18535. this._animationPropertiesOverride = value;
  18536. },
  18537. enumerable: true,
  18538. configurable: true
  18539. });
  18540. /**
  18541. * Gets a string idenfifying the name of the class
  18542. * @returns "Node" string
  18543. */
  18544. Node.prototype.getClassName = function () {
  18545. return "Node";
  18546. };
  18547. Object.defineProperty(Node.prototype, "onDispose", {
  18548. /**
  18549. * Sets a callback that will be raised when the node will be disposed
  18550. */
  18551. set: function (callback) {
  18552. if (this._onDisposeObserver) {
  18553. this.onDisposeObservable.remove(this._onDisposeObserver);
  18554. }
  18555. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18556. },
  18557. enumerable: true,
  18558. configurable: true
  18559. });
  18560. /**
  18561. * Gets the scene of the node
  18562. * @returns a scene
  18563. */
  18564. Node.prototype.getScene = function () {
  18565. return this._scene;
  18566. };
  18567. /**
  18568. * Gets the engine of the node
  18569. * @returns a Engine
  18570. */
  18571. Node.prototype.getEngine = function () {
  18572. return this._scene.getEngine();
  18573. };
  18574. /**
  18575. * Attach a behavior to the node
  18576. * @see http://doc.babylonjs.com/features/behaviour
  18577. * @param behavior defines the behavior to attach
  18578. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  18579. * @returns the current Node
  18580. */
  18581. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  18582. var _this = this;
  18583. if (attachImmediately === void 0) { attachImmediately = false; }
  18584. var index = this._behaviors.indexOf(behavior);
  18585. if (index !== -1) {
  18586. return this;
  18587. }
  18588. behavior.init();
  18589. if (this._scene.isLoading && !attachImmediately) {
  18590. // We defer the attach when the scene will be loaded
  18591. this._scene.onDataLoadedObservable.addOnce(function () {
  18592. behavior.attach(_this);
  18593. });
  18594. }
  18595. else {
  18596. behavior.attach(this);
  18597. }
  18598. this._behaviors.push(behavior);
  18599. return this;
  18600. };
  18601. /**
  18602. * Remove an attached behavior
  18603. * @see http://doc.babylonjs.com/features/behaviour
  18604. * @param behavior defines the behavior to attach
  18605. * @returns the current Node
  18606. */
  18607. Node.prototype.removeBehavior = function (behavior) {
  18608. var index = this._behaviors.indexOf(behavior);
  18609. if (index === -1) {
  18610. return this;
  18611. }
  18612. this._behaviors[index].detach();
  18613. this._behaviors.splice(index, 1);
  18614. return this;
  18615. };
  18616. Object.defineProperty(Node.prototype, "behaviors", {
  18617. /**
  18618. * Gets the list of attached behaviors
  18619. * @see http://doc.babylonjs.com/features/behaviour
  18620. */
  18621. get: function () {
  18622. return this._behaviors;
  18623. },
  18624. enumerable: true,
  18625. configurable: true
  18626. });
  18627. /**
  18628. * Gets an attached behavior by name
  18629. * @param name defines the name of the behavior to look for
  18630. * @see http://doc.babylonjs.com/features/behaviour
  18631. * @returns null if behavior was not found else the requested behavior
  18632. */
  18633. Node.prototype.getBehaviorByName = function (name) {
  18634. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  18635. var behavior = _a[_i];
  18636. if (behavior.name === name) {
  18637. return behavior;
  18638. }
  18639. }
  18640. return null;
  18641. };
  18642. /**
  18643. * Returns the latest update of the World matrix
  18644. * @returns a Matrix
  18645. */
  18646. Node.prototype.getWorldMatrix = function () {
  18647. if (this._currentRenderId !== this._scene.getRenderId()) {
  18648. this.computeWorldMatrix();
  18649. }
  18650. return this._worldMatrix;
  18651. };
  18652. /** @hidden */
  18653. Node.prototype._getWorldMatrixDeterminant = function () {
  18654. return this._worldMatrixDeterminant;
  18655. };
  18656. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  18657. /**
  18658. * Returns directly the latest state of the mesh World matrix.
  18659. * A Matrix is returned.
  18660. */
  18661. get: function () {
  18662. return this._worldMatrix;
  18663. },
  18664. enumerable: true,
  18665. configurable: true
  18666. });
  18667. // override it in derived class if you add new variables to the cache
  18668. // and call the parent class method
  18669. /** @hidden */
  18670. Node.prototype._initCache = function () {
  18671. this._cache = {};
  18672. this._cache.parent = undefined;
  18673. };
  18674. /** @hidden */
  18675. Node.prototype.updateCache = function (force) {
  18676. if (!force && this.isSynchronized()) {
  18677. return;
  18678. }
  18679. this._cache.parent = this.parent;
  18680. this._updateCache();
  18681. };
  18682. // override it in derived class if you add new variables to the cache
  18683. // and call the parent class method if !ignoreParentClass
  18684. /** @hidden */
  18685. Node.prototype._updateCache = function (ignoreParentClass) {
  18686. };
  18687. // override it in derived class if you add new variables to the cache
  18688. /** @hidden */
  18689. Node.prototype._isSynchronized = function () {
  18690. return true;
  18691. };
  18692. /** @hidden */
  18693. Node.prototype._markSyncedWithParent = function () {
  18694. if (this._parentNode) {
  18695. this._parentRenderId = this._parentNode._childRenderId;
  18696. }
  18697. };
  18698. /** @hidden */
  18699. Node.prototype.isSynchronizedWithParent = function () {
  18700. if (!this._parentNode) {
  18701. return true;
  18702. }
  18703. if (this._parentRenderId !== this._parentNode._childRenderId) {
  18704. return false;
  18705. }
  18706. return this._parentNode.isSynchronized();
  18707. };
  18708. /** @hidden */
  18709. Node.prototype.isSynchronized = function () {
  18710. if (this._cache.parent != this._parentNode) {
  18711. this._cache.parent = this._parentNode;
  18712. return false;
  18713. }
  18714. if (this._parentNode && !this.isSynchronizedWithParent()) {
  18715. return false;
  18716. }
  18717. return this._isSynchronized();
  18718. };
  18719. /**
  18720. * Is this node ready to be used/rendered
  18721. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18722. * @return true if the node is ready
  18723. */
  18724. Node.prototype.isReady = function (completeCheck) {
  18725. if (completeCheck === void 0) { completeCheck = false; }
  18726. return this._isReady;
  18727. };
  18728. /**
  18729. * Is this node enabled?
  18730. * 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
  18731. * @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
  18732. * @return whether this node (and its parent) is enabled
  18733. */
  18734. Node.prototype.isEnabled = function (checkAncestors) {
  18735. if (checkAncestors === void 0) { checkAncestors = true; }
  18736. if (checkAncestors === false) {
  18737. return this._isEnabled;
  18738. }
  18739. if (!this._isEnabled) {
  18740. return false;
  18741. }
  18742. return this._isParentEnabled;
  18743. };
  18744. /** @hidden */
  18745. Node.prototype._syncParentEnabledState = function () {
  18746. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  18747. if (this._children) {
  18748. this._children.forEach(function (c) {
  18749. c._syncParentEnabledState(); // Force children to update accordingly
  18750. });
  18751. }
  18752. };
  18753. /**
  18754. * Set the enabled state of this node
  18755. * @param value defines the new enabled state
  18756. */
  18757. Node.prototype.setEnabled = function (value) {
  18758. this._isEnabled = value;
  18759. this._syncParentEnabledState();
  18760. };
  18761. /**
  18762. * Is this node a descendant of the given node?
  18763. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18764. * @param ancestor defines the parent node to inspect
  18765. * @returns a boolean indicating if this node is a descendant of the given node
  18766. */
  18767. Node.prototype.isDescendantOf = function (ancestor) {
  18768. if (this.parent) {
  18769. if (this.parent === ancestor) {
  18770. return true;
  18771. }
  18772. return this.parent.isDescendantOf(ancestor);
  18773. }
  18774. return false;
  18775. };
  18776. /** @hidden */
  18777. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18778. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18779. if (!this._children) {
  18780. return;
  18781. }
  18782. for (var index = 0; index < this._children.length; index++) {
  18783. var item = this._children[index];
  18784. if (!predicate || predicate(item)) {
  18785. results.push(item);
  18786. }
  18787. if (!directDescendantsOnly) {
  18788. item._getDescendants(results, false, predicate);
  18789. }
  18790. }
  18791. };
  18792. /**
  18793. * Will return all nodes that have this node as ascendant
  18794. * @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
  18795. * @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
  18796. * @return all children nodes of all types
  18797. */
  18798. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18799. var results = new Array();
  18800. this._getDescendants(results, directDescendantsOnly, predicate);
  18801. return results;
  18802. };
  18803. /**
  18804. * Get all child-meshes of this node
  18805. * @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
  18806. * @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
  18807. * @returns an array of AbstractMesh
  18808. */
  18809. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18810. var results = [];
  18811. this._getDescendants(results, directDescendantsOnly, function (node) {
  18812. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18813. });
  18814. return results;
  18815. };
  18816. /**
  18817. * Get all child-transformNodes of this node
  18818. * @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
  18819. * @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
  18820. * @returns an array of TransformNode
  18821. */
  18822. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18823. var results = [];
  18824. this._getDescendants(results, directDescendantsOnly, function (node) {
  18825. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18826. });
  18827. return results;
  18828. };
  18829. /**
  18830. * Get all direct children of this node
  18831. * @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
  18832. * @returns an array of Node
  18833. */
  18834. Node.prototype.getChildren = function (predicate) {
  18835. return this.getDescendants(true, predicate);
  18836. };
  18837. /** @hidden */
  18838. Node.prototype._setReady = function (state) {
  18839. if (state === this._isReady) {
  18840. return;
  18841. }
  18842. if (!state) {
  18843. this._isReady = false;
  18844. return;
  18845. }
  18846. if (this.onReady) {
  18847. this.onReady(this);
  18848. }
  18849. this._isReady = true;
  18850. };
  18851. /**
  18852. * Get an animation by name
  18853. * @param name defines the name of the animation to look for
  18854. * @returns null if not found else the requested animation
  18855. */
  18856. Node.prototype.getAnimationByName = function (name) {
  18857. for (var i = 0; i < this.animations.length; i++) {
  18858. var animation = this.animations[i];
  18859. if (animation.name === name) {
  18860. return animation;
  18861. }
  18862. }
  18863. return null;
  18864. };
  18865. /**
  18866. * Creates an animation range for this node
  18867. * @param name defines the name of the range
  18868. * @param from defines the starting key
  18869. * @param to defines the end key
  18870. */
  18871. Node.prototype.createAnimationRange = function (name, from, to) {
  18872. // check name not already in use
  18873. if (!this._ranges[name]) {
  18874. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18875. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18876. if (this.animations[i]) {
  18877. this.animations[i].createRange(name, from, to);
  18878. }
  18879. }
  18880. }
  18881. };
  18882. /**
  18883. * Delete a specific animation range
  18884. * @param name defines the name of the range to delete
  18885. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18886. */
  18887. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18888. if (deleteFrames === void 0) { deleteFrames = true; }
  18889. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18890. if (this.animations[i]) {
  18891. this.animations[i].deleteRange(name, deleteFrames);
  18892. }
  18893. }
  18894. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18895. };
  18896. /**
  18897. * Get an animation range by name
  18898. * @param name defines the name of the animation range to look for
  18899. * @returns null if not found else the requested animation range
  18900. */
  18901. Node.prototype.getAnimationRange = function (name) {
  18902. return this._ranges[name];
  18903. };
  18904. /**
  18905. * Will start the animation sequence
  18906. * @param name defines the range frames for animation sequence
  18907. * @param loop defines if the animation should loop (false by default)
  18908. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18909. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18910. * @returns the object created for this animation. If range does not exist, it will return null
  18911. */
  18912. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18913. var range = this.getAnimationRange(name);
  18914. if (!range) {
  18915. return null;
  18916. }
  18917. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18918. };
  18919. /**
  18920. * Serialize animation ranges into a JSON compatible object
  18921. * @returns serialization object
  18922. */
  18923. Node.prototype.serializeAnimationRanges = function () {
  18924. var serializationRanges = [];
  18925. for (var name in this._ranges) {
  18926. var localRange = this._ranges[name];
  18927. if (!localRange) {
  18928. continue;
  18929. }
  18930. var range = {};
  18931. range.name = name;
  18932. range.from = localRange.from;
  18933. range.to = localRange.to;
  18934. serializationRanges.push(range);
  18935. }
  18936. return serializationRanges;
  18937. };
  18938. /**
  18939. * Computes the world matrix of the node
  18940. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18941. * @returns the world matrix
  18942. */
  18943. Node.prototype.computeWorldMatrix = function (force) {
  18944. if (!this._worldMatrix) {
  18945. this._worldMatrix = BABYLON.Matrix.Identity();
  18946. }
  18947. return this._worldMatrix;
  18948. };
  18949. /**
  18950. * Releases resources associated with this node.
  18951. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18952. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18953. */
  18954. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18955. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18956. if (!doNotRecurse) {
  18957. var nodes = this.getDescendants(true);
  18958. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18959. var node = nodes_1[_i];
  18960. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18961. }
  18962. }
  18963. else {
  18964. var transformNodes = this.getChildTransformNodes(true);
  18965. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18966. var transformNode = transformNodes_1[_a];
  18967. transformNode.parent = null;
  18968. transformNode.computeWorldMatrix(true);
  18969. }
  18970. }
  18971. if (!this.parent) {
  18972. this.removeFromSceneRootNodes();
  18973. }
  18974. else {
  18975. this.parent = null;
  18976. }
  18977. // Callback
  18978. this.onDisposeObservable.notifyObservers(this);
  18979. this.onDisposeObservable.clear();
  18980. // Behaviors
  18981. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18982. var behavior = _c[_b];
  18983. behavior.detach();
  18984. }
  18985. this._behaviors = [];
  18986. this._isDisposed = true;
  18987. };
  18988. /**
  18989. * Parse animation range data from a serialization object and store them into a given node
  18990. * @param node defines where to store the animation ranges
  18991. * @param parsedNode defines the serialization object to read data from
  18992. * @param scene defines the hosting scene
  18993. */
  18994. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18995. if (parsedNode.ranges) {
  18996. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18997. var data = parsedNode.ranges[index];
  18998. node.createAnimationRange(data.name, data.from, data.to);
  18999. }
  19000. }
  19001. };
  19002. Node._NodeConstructors = {};
  19003. __decorate([
  19004. BABYLON.serialize()
  19005. ], Node.prototype, "name", void 0);
  19006. __decorate([
  19007. BABYLON.serialize()
  19008. ], Node.prototype, "id", void 0);
  19009. __decorate([
  19010. BABYLON.serialize()
  19011. ], Node.prototype, "uniqueId", void 0);
  19012. __decorate([
  19013. BABYLON.serialize()
  19014. ], Node.prototype, "state", void 0);
  19015. __decorate([
  19016. BABYLON.serialize()
  19017. ], Node.prototype, "metadata", void 0);
  19018. return Node;
  19019. }());
  19020. BABYLON.Node = Node;
  19021. })(BABYLON || (BABYLON = {}));
  19022. //# sourceMappingURL=babylon.node.js.map
  19023. var BABYLON;
  19024. (function (BABYLON) {
  19025. // This matrix is used as a value to reset the bounding box.
  19026. var _identityMatrix = BABYLON.Matrix.Identity();
  19027. /**
  19028. * Class used to store bounding sphere information
  19029. */
  19030. var BoundingSphere = /** @class */ (function () {
  19031. /**
  19032. * Creates a new bounding sphere
  19033. * @param min defines the minimum vector (in local space)
  19034. * @param max defines the maximum vector (in local space)
  19035. */
  19036. function BoundingSphere(min, max) {
  19037. /**
  19038. * Gets the center of the bounding sphere in local space
  19039. */
  19040. this.center = BABYLON.Vector3.Zero();
  19041. /**
  19042. * Gets the center of the bounding sphere in world space
  19043. */
  19044. this.centerWorld = BABYLON.Vector3.Zero();
  19045. /**
  19046. * Gets the minimum vector in local space
  19047. */
  19048. this.minimum = BABYLON.Vector3.Zero();
  19049. /**
  19050. * Gets the maximum vector in local space
  19051. */
  19052. this.maximum = BABYLON.Vector3.Zero();
  19053. this.reConstruct(min, max);
  19054. }
  19055. /**
  19056. * Recreates the entire bounding sphere from scratch
  19057. * @param min defines the new minimum vector (in local space)
  19058. * @param max defines the new maximum vector (in local space)
  19059. */
  19060. BoundingSphere.prototype.reConstruct = function (min, max) {
  19061. this.minimum.copyFrom(min);
  19062. this.maximum.copyFrom(max);
  19063. var distance = BABYLON.Vector3.Distance(min, max);
  19064. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  19065. this.radius = distance * 0.5;
  19066. this.centerWorld.set(0, 0, 0);
  19067. this._update(_identityMatrix);
  19068. };
  19069. /**
  19070. * Scale the current bounding sphere by applying a scale factor
  19071. * @param factor defines the scale factor to apply
  19072. * @returns the current bounding box
  19073. */
  19074. BoundingSphere.prototype.scale = function (factor) {
  19075. var newRadius = this.radius * factor;
  19076. var tempRadiusVector = BABYLON.Tmp.Vector3[0].set(newRadius, newRadius, newRadius);
  19077. var min = BABYLON.Tmp.Vector3[1].copyFrom(this.center).subtractInPlace(tempRadiusVector);
  19078. var max = BABYLON.Tmp.Vector3[2].copyFrom(this.center).addInPlace(tempRadiusVector);
  19079. this.reConstruct(min, max);
  19080. return this;
  19081. };
  19082. // Methods
  19083. /** @hidden */
  19084. BoundingSphere.prototype._update = function (world) {
  19085. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  19086. var tempVector = BABYLON.Tmp.Vector3[0];
  19087. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, tempVector);
  19088. this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius;
  19089. };
  19090. /**
  19091. * Tests if the bounding sphere is intersecting the frustum planes
  19092. * @param frustumPlanes defines the frustum planes to test
  19093. * @returns true if there is an intersection
  19094. */
  19095. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  19096. for (var i = 0; i < 6; i++) {
  19097. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld) {
  19098. return false;
  19099. }
  19100. }
  19101. return true;
  19102. };
  19103. /**
  19104. * Tests if a point is inside the bounding sphere
  19105. * @param point defines the point to test
  19106. * @returns true if the point is inside the bounding sphere
  19107. */
  19108. BoundingSphere.prototype.intersectsPoint = function (point) {
  19109. var x = this.centerWorld.x - point.x;
  19110. var y = this.centerWorld.y - point.y;
  19111. var z = this.centerWorld.z - point.z;
  19112. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  19113. if (this.radiusWorld < distance) {
  19114. return false;
  19115. }
  19116. return true;
  19117. };
  19118. // Statics
  19119. /**
  19120. * Checks if two sphere intersct
  19121. * @param sphere0 sphere 0
  19122. * @param sphere1 sphere 1
  19123. * @returns true if the speres intersect
  19124. */
  19125. BoundingSphere.Intersects = function (sphere0, sphere1) {
  19126. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  19127. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  19128. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  19129. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  19130. if (sphere0.radiusWorld + sphere1.radiusWorld < distance) {
  19131. return false;
  19132. }
  19133. return true;
  19134. };
  19135. return BoundingSphere;
  19136. }());
  19137. BABYLON.BoundingSphere = BoundingSphere;
  19138. })(BABYLON || (BABYLON = {}));
  19139. //# sourceMappingURL=babylon.boundingSphere.js.map
  19140. var BABYLON;
  19141. (function (BABYLON) {
  19142. /**
  19143. * Class used to store bounding box information
  19144. */
  19145. var BoundingBox = /** @class */ (function () {
  19146. /**
  19147. * Creates a new bounding box
  19148. * @param min defines the minimum vector (in local space)
  19149. * @param max defines the maximum vector (in local space)
  19150. */
  19151. function BoundingBox(min, max) {
  19152. /**
  19153. * Gets the 8 vectors representing the bounding box in local space
  19154. */
  19155. this.vectors = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  19156. /**
  19157. * Gets the center of the bounding box in local space
  19158. */
  19159. this.center = BABYLON.Vector3.Zero();
  19160. /**
  19161. * Gets the center of the bounding box in world space
  19162. */
  19163. this.centerWorld = BABYLON.Vector3.Zero();
  19164. /**
  19165. * Gets the extend size in local space
  19166. */
  19167. this.extendSize = BABYLON.Vector3.Zero();
  19168. /**
  19169. * Gets the extend size in world space
  19170. */
  19171. this.extendSizeWorld = BABYLON.Vector3.Zero();
  19172. /**
  19173. * Gets the OBB (object bounding box) directions
  19174. */
  19175. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  19176. /**
  19177. * Gets the 8 vectors representing the bounding box in world space
  19178. */
  19179. this.vectorsWorld = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  19180. /**
  19181. * Gets the minimum vector in world space
  19182. */
  19183. this.minimumWorld = BABYLON.Vector3.Zero();
  19184. /**
  19185. * Gets the maximum vector in world space
  19186. */
  19187. this.maximumWorld = BABYLON.Vector3.Zero();
  19188. /**
  19189. * Gets the minimum vector in local space
  19190. */
  19191. this.minimum = BABYLON.Vector3.Zero();
  19192. /**
  19193. * Gets the maximum vector in local space
  19194. */
  19195. this.maximum = BABYLON.Vector3.Zero();
  19196. this.reConstruct(min, max);
  19197. }
  19198. // Methods
  19199. /**
  19200. * Recreates the entire bounding box from scratch
  19201. * @param min defines the new minimum vector (in local space)
  19202. * @param max defines the new maximum vector (in local space)
  19203. */
  19204. BoundingBox.prototype.reConstruct = function (min, max) {
  19205. this.minimum.copyFrom(min);
  19206. this.maximum.copyFrom(max);
  19207. // Bounding vectors
  19208. this.vectors[0].copyFrom(this.minimum);
  19209. this.vectors[1].copyFrom(this.maximum);
  19210. this.vectors[2].copyFrom(this.minimum);
  19211. this.vectors[3].copyFrom(this.minimum);
  19212. this.vectors[4].copyFrom(this.minimum);
  19213. this.vectors[5].copyFrom(this.maximum);
  19214. this.vectors[6].copyFrom(this.maximum);
  19215. this.vectors[7].copyFrom(this.maximum);
  19216. this.vectors[2].x = this.maximum.x;
  19217. this.vectors[3].y = this.maximum.y;
  19218. this.vectors[4].z = this.maximum.z;
  19219. this.vectors[5].z = this.minimum.z;
  19220. this.vectors[6].x = this.minimum.x;
  19221. this.vectors[7].y = this.minimum.y;
  19222. // OBB
  19223. this.center.copyFrom(this.maximum).addInPlace(this.minimum).scaleInPlace(0.5);
  19224. this.extendSize.copyFrom(this.maximum).subtractInPlace(this.minimum).scaleInPlace(0.5);
  19225. for (var index = 0; index < 3; index++) {
  19226. this.directions[index].copyFromFloats(0, 0, 0);
  19227. }
  19228. // World
  19229. for (var index = 0; index < 8; index++) {
  19230. this.vectorsWorld[index].copyFromFloats(0, 0, 0);
  19231. }
  19232. this.minimumWorld.copyFromFloats(0, 0, 0);
  19233. this.maximumWorld.copyFromFloats(0, 0, 0);
  19234. this.centerWorld.copyFromFloats(0, 0, 0);
  19235. this.extendSizeWorld.copyFromFloats(0, 0, 0);
  19236. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  19237. };
  19238. /**
  19239. * Scale the current bounding box by applying a scale factor
  19240. * @param factor defines the scale factor to apply
  19241. * @returns the current bounding box
  19242. */
  19243. BoundingBox.prototype.scale = function (factor) {
  19244. var diff = BABYLON.Tmp.Vector3[0].copyFrom(this.maximum).subtractInPlace(this.minimum);
  19245. var distance = diff.length() * factor;
  19246. diff.normalize();
  19247. var newRadius = diff.scaleInPlace(distance * 0.5);
  19248. var min = BABYLON.Tmp.Vector3[1].copyFrom(this.center).subtractInPlace(newRadius);
  19249. var max = BABYLON.Tmp.Vector3[2].copyFrom(this.center).addInPlace(newRadius);
  19250. this.reConstruct(min, max);
  19251. return this;
  19252. };
  19253. /**
  19254. * Gets the world matrix of the bounding box
  19255. * @returns a matrix
  19256. */
  19257. BoundingBox.prototype.getWorldMatrix = function () {
  19258. return this._worldMatrix;
  19259. };
  19260. /**
  19261. * Sets the world matrix stored in the bounding box
  19262. * @param matrix defines the matrix to store
  19263. * @returns current bounding box
  19264. */
  19265. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  19266. this._worldMatrix.copyFrom(matrix);
  19267. return this;
  19268. };
  19269. /** @hidden */
  19270. BoundingBox.prototype._update = function (world) {
  19271. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  19272. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  19273. for (var index = 0; index < 8; index++) {
  19274. var v = this.vectorsWorld[index];
  19275. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  19276. this.minimumWorld.minimizeInPlace(v);
  19277. this.maximumWorld.maximizeInPlace(v);
  19278. }
  19279. // Extend
  19280. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  19281. this.extendSizeWorld.scaleInPlace(0.5);
  19282. // OBB
  19283. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  19284. this.centerWorld.scaleInPlace(0.5);
  19285. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  19286. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  19287. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  19288. this._worldMatrix = world;
  19289. };
  19290. /**
  19291. * Tests if the bounding box is intersecting the frustum planes
  19292. * @param frustumPlanes defines the frustum planes to test
  19293. * @returns true if there is an intersection
  19294. */
  19295. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  19296. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  19297. };
  19298. /**
  19299. * Tests if the bounding box is entirely inside the frustum planes
  19300. * @param frustumPlanes defines the frustum planes to test
  19301. * @returns true if there is an inclusion
  19302. */
  19303. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19304. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  19305. };
  19306. /**
  19307. * Tests if a point is inside the bounding box
  19308. * @param point defines the point to test
  19309. * @returns true if the point is inside the bounding box
  19310. */
  19311. BoundingBox.prototype.intersectsPoint = function (point) {
  19312. var delta = -BABYLON.Epsilon;
  19313. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x) {
  19314. return false;
  19315. }
  19316. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y) {
  19317. return false;
  19318. }
  19319. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z) {
  19320. return false;
  19321. }
  19322. return true;
  19323. };
  19324. /**
  19325. * Tests if the bounding box intersects with a bounding sphere
  19326. * @param sphere defines the sphere to test
  19327. * @returns true if there is an intersection
  19328. */
  19329. BoundingBox.prototype.intersectsSphere = function (sphere) {
  19330. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  19331. };
  19332. /**
  19333. * Tests if the bounding box intersects with a box defined by a min and max vectors
  19334. * @param min defines the min vector to use
  19335. * @param max defines the max vector to use
  19336. * @returns true if there is an intersection
  19337. */
  19338. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  19339. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x) {
  19340. return false;
  19341. }
  19342. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y) {
  19343. return false;
  19344. }
  19345. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z) {
  19346. return false;
  19347. }
  19348. return true;
  19349. };
  19350. // Statics
  19351. /**
  19352. * Tests if two bounding boxes are intersections
  19353. * @param box0 defines the first box to test
  19354. * @param box1 defines the second box to test
  19355. * @returns true if there is an intersection
  19356. */
  19357. BoundingBox.Intersects = function (box0, box1) {
  19358. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x) {
  19359. return false;
  19360. }
  19361. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y) {
  19362. return false;
  19363. }
  19364. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z) {
  19365. return false;
  19366. }
  19367. return true;
  19368. };
  19369. /**
  19370. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  19371. * @param minPoint defines the minimum vector of the bounding box
  19372. * @param maxPoint defines the maximum vector of the bounding box
  19373. * @param sphereCenter defines the sphere center
  19374. * @param sphereRadius defines the sphere radius
  19375. * @returns true if there is an intersection
  19376. */
  19377. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  19378. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  19379. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  19380. return (num <= (sphereRadius * sphereRadius));
  19381. };
  19382. /**
  19383. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  19384. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19385. * @param frustumPlanes defines the frustum planes to test
  19386. * @return true if there is an inclusion
  19387. */
  19388. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  19389. for (var p = 0; p < 6; p++) {
  19390. for (var i = 0; i < 8; i++) {
  19391. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19392. return false;
  19393. }
  19394. }
  19395. }
  19396. return true;
  19397. };
  19398. /**
  19399. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  19400. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19401. * @param frustumPlanes defines the frustum planes to test
  19402. * @return true if there is an intersection
  19403. */
  19404. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  19405. for (var p = 0; p < 6; p++) {
  19406. var inCount = 8;
  19407. for (var i = 0; i < 8; i++) {
  19408. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19409. --inCount;
  19410. }
  19411. else {
  19412. break;
  19413. }
  19414. }
  19415. if (inCount === 0) {
  19416. return false;
  19417. }
  19418. }
  19419. return true;
  19420. };
  19421. return BoundingBox;
  19422. }());
  19423. BABYLON.BoundingBox = BoundingBox;
  19424. })(BABYLON || (BABYLON = {}));
  19425. //# sourceMappingURL=babylon.boundingBox.js.map
  19426. var BABYLON;
  19427. (function (BABYLON) {
  19428. var computeBoxExtents = function (axis, box) {
  19429. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  19430. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  19431. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  19432. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  19433. var r = r0 + r1 + r2;
  19434. return {
  19435. min: p - r,
  19436. max: p + r
  19437. };
  19438. };
  19439. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  19440. var axisOverlap = function (axis, box0, box1) {
  19441. var result0 = computeBoxExtents(axis, box0);
  19442. var result1 = computeBoxExtents(axis, box1);
  19443. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  19444. };
  19445. /**
  19446. * Info for a bounding data of a mesh
  19447. */
  19448. var BoundingInfo = /** @class */ (function () {
  19449. /**
  19450. * Constructs bounding info
  19451. * @param minimum min vector of the bounding box/sphere
  19452. * @param maximum max vector of the bounding box/sphere
  19453. */
  19454. function BoundingInfo(minimum, maximum) {
  19455. this._isLocked = false;
  19456. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  19457. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  19458. }
  19459. Object.defineProperty(BoundingInfo.prototype, "minimum", {
  19460. /**
  19461. * min vector of the bounding box/sphere
  19462. */
  19463. get: function () {
  19464. return this.boundingBox.minimum;
  19465. },
  19466. enumerable: true,
  19467. configurable: true
  19468. });
  19469. Object.defineProperty(BoundingInfo.prototype, "maximum", {
  19470. /**
  19471. * max vector of the bounding box/sphere
  19472. */
  19473. get: function () {
  19474. return this.boundingBox.maximum;
  19475. },
  19476. enumerable: true,
  19477. configurable: true
  19478. });
  19479. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  19480. /**
  19481. * If the info is locked and won't be updated to avoid perf overhead
  19482. */
  19483. get: function () {
  19484. return this._isLocked;
  19485. },
  19486. set: function (value) {
  19487. this._isLocked = value;
  19488. },
  19489. enumerable: true,
  19490. configurable: true
  19491. });
  19492. // Methods
  19493. /**
  19494. * Updates the boudning sphere and box
  19495. * @param world world matrix to be used to update
  19496. */
  19497. BoundingInfo.prototype.update = function (world) {
  19498. if (this._isLocked) {
  19499. return;
  19500. }
  19501. this.boundingBox._update(world);
  19502. this.boundingSphere._update(world);
  19503. };
  19504. /**
  19505. * Recreate the bounding info to be centered around a specific point given a specific extend.
  19506. * @param center New center of the bounding info
  19507. * @param extend New extend of the bounding info
  19508. * @returns the current bounding info
  19509. */
  19510. BoundingInfo.prototype.centerOn = function (center, extend) {
  19511. var minimum = BABYLON.Tmp.Vector3[0].copyFrom(center).subtractInPlace(extend);
  19512. var maximum = BABYLON.Tmp.Vector3[1].copyFrom(center).addInPlace(extend);
  19513. this.boundingBox.reConstruct(minimum, maximum);
  19514. this.boundingSphere.reConstruct(minimum, maximum);
  19515. return this;
  19516. };
  19517. /**
  19518. * Scale the current bounding info by applying a scale factor
  19519. * @param factor defines the scale factor to apply
  19520. * @returns the current bounding info
  19521. */
  19522. BoundingInfo.prototype.scale = function (factor) {
  19523. this.boundingBox.scale(factor);
  19524. this.boundingSphere.scale(factor);
  19525. return this;
  19526. };
  19527. /**
  19528. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  19529. * @param frustumPlanes defines the frustum to test
  19530. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  19531. * @returns true if the bounding info is in the frustum planes
  19532. */
  19533. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  19534. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  19535. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  19536. return false;
  19537. }
  19538. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  19539. return true;
  19540. }
  19541. return this.boundingBox.isInFrustum(frustumPlanes);
  19542. };
  19543. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  19544. /**
  19545. * Gets the world distance between the min and max points of the bounding box
  19546. */
  19547. get: function () {
  19548. var boundingBox = this.boundingBox;
  19549. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  19550. return size.length();
  19551. },
  19552. enumerable: true,
  19553. configurable: true
  19554. });
  19555. /**
  19556. * Checks if a cullable object (mesh...) is in the camera frustum
  19557. * Unlike isInFrustum this cheks the full bounding box
  19558. * @param frustumPlanes Camera near/planes
  19559. * @returns true if the object is in frustum otherwise false
  19560. */
  19561. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19562. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  19563. };
  19564. /** @hidden */
  19565. BoundingInfo.prototype._checkCollision = function (collider) {
  19566. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  19567. };
  19568. /**
  19569. * Checks if a point is inside the bounding box and bounding sphere or the mesh
  19570. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19571. * @param point the point to check intersection with
  19572. * @returns if the point intersects
  19573. */
  19574. BoundingInfo.prototype.intersectsPoint = function (point) {
  19575. if (!this.boundingSphere.centerWorld) {
  19576. return false;
  19577. }
  19578. if (!this.boundingSphere.intersectsPoint(point)) {
  19579. return false;
  19580. }
  19581. if (!this.boundingBox.intersectsPoint(point)) {
  19582. return false;
  19583. }
  19584. return true;
  19585. };
  19586. /**
  19587. * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh
  19588. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19589. * @param boundingInfo the bounding info to check intersection with
  19590. * @param precise if the intersection should be done using OBB
  19591. * @returns if the bounding info intersects
  19592. */
  19593. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  19594. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  19595. return false;
  19596. }
  19597. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  19598. return false;
  19599. }
  19600. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  19601. return false;
  19602. }
  19603. if (!precise) {
  19604. return true;
  19605. }
  19606. var box0 = this.boundingBox;
  19607. var box1 = boundingInfo.boundingBox;
  19608. if (!axisOverlap(box0.directions[0], box0, box1)) {
  19609. return false;
  19610. }
  19611. if (!axisOverlap(box0.directions[1], box0, box1)) {
  19612. return false;
  19613. }
  19614. if (!axisOverlap(box0.directions[2], box0, box1)) {
  19615. return false;
  19616. }
  19617. if (!axisOverlap(box1.directions[0], box0, box1)) {
  19618. return false;
  19619. }
  19620. if (!axisOverlap(box1.directions[1], box0, box1)) {
  19621. return false;
  19622. }
  19623. if (!axisOverlap(box1.directions[2], box0, box1)) {
  19624. return false;
  19625. }
  19626. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1)) {
  19627. return false;
  19628. }
  19629. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1)) {
  19630. return false;
  19631. }
  19632. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1)) {
  19633. return false;
  19634. }
  19635. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1)) {
  19636. return false;
  19637. }
  19638. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1)) {
  19639. return false;
  19640. }
  19641. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1)) {
  19642. return false;
  19643. }
  19644. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1)) {
  19645. return false;
  19646. }
  19647. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1)) {
  19648. return false;
  19649. }
  19650. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1)) {
  19651. return false;
  19652. }
  19653. return true;
  19654. };
  19655. return BoundingInfo;
  19656. }());
  19657. BABYLON.BoundingInfo = BoundingInfo;
  19658. })(BABYLON || (BABYLON = {}));
  19659. //# sourceMappingURL=babylon.boundingInfo.js.map
  19660. var BABYLON;
  19661. (function (BABYLON) {
  19662. /**
  19663. * A TransformNode is an object that is not rendered but can be used as a center of transformation. This can decrease memory usage and increase rendering speed compared to using an empty mesh as a parent and is less complicated than using a pivot matrix.
  19664. * @see https://doc.babylonjs.com/how_to/transformnode
  19665. */
  19666. var TransformNode = /** @class */ (function (_super) {
  19667. __extends(TransformNode, _super);
  19668. function TransformNode(name, scene, isPure) {
  19669. if (scene === void 0) { scene = null; }
  19670. if (isPure === void 0) { isPure = true; }
  19671. var _this = _super.call(this, name, scene) || this;
  19672. _this._forward = new BABYLON.Vector3(0, 0, 1);
  19673. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  19674. _this._up = new BABYLON.Vector3(0, 1, 0);
  19675. _this._right = new BABYLON.Vector3(1, 0, 0);
  19676. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  19677. // Properties
  19678. _this._position = BABYLON.Vector3.Zero();
  19679. _this._rotation = BABYLON.Vector3.Zero();
  19680. _this._scaling = BABYLON.Vector3.One();
  19681. _this._isDirty = false;
  19682. /**
  19683. * Set the billboard mode. Default is 0.
  19684. *
  19685. * | Value | Type | Description |
  19686. * | --- | --- | --- |
  19687. * | 0 | BILLBOARDMODE_NONE | |
  19688. * | 1 | BILLBOARDMODE_X | |
  19689. * | 2 | BILLBOARDMODE_Y | |
  19690. * | 4 | BILLBOARDMODE_Z | |
  19691. * | 7 | BILLBOARDMODE_ALL | |
  19692. *
  19693. */
  19694. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  19695. /**
  19696. * Multiplication factor on scale x/y/z when computing the world matrix. Eg. for a 1x1x1 cube setting this to 2 will make it a 2x2x2 cube
  19697. */
  19698. _this.scalingDeterminant = 1;
  19699. /**
  19700. * Sets the distance of the object to max, often used by skybox
  19701. */
  19702. _this.infiniteDistance = false;
  19703. /**
  19704. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  19705. * By default the system will update normals to compensate
  19706. */
  19707. _this.ignoreNonUniformScaling = false;
  19708. _this._localWorld = BABYLON.Matrix.Zero();
  19709. _this._absolutePosition = BABYLON.Vector3.Zero();
  19710. _this._pivotMatrix = BABYLON.Matrix.Identity();
  19711. _this._postMultiplyPivotMatrix = false;
  19712. _this._isWorldMatrixFrozen = false;
  19713. /**
  19714. * An event triggered after the world matrix is updated
  19715. */
  19716. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  19717. _this._nonUniformScaling = false;
  19718. if (isPure) {
  19719. _this.getScene().addTransformNode(_this);
  19720. }
  19721. return _this;
  19722. }
  19723. /**
  19724. * Gets a string identifying the name of the class
  19725. * @returns "TransformNode" string
  19726. */
  19727. TransformNode.prototype.getClassName = function () {
  19728. return "TransformNode";
  19729. };
  19730. Object.defineProperty(TransformNode.prototype, "position", {
  19731. /**
  19732. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  19733. */
  19734. get: function () {
  19735. return this._position;
  19736. },
  19737. set: function (newPosition) {
  19738. this._position = newPosition;
  19739. this._isDirty = true;
  19740. },
  19741. enumerable: true,
  19742. configurable: true
  19743. });
  19744. Object.defineProperty(TransformNode.prototype, "rotation", {
  19745. /**
  19746. * Gets or sets the rotation property : a Vector3 defining the rotation value in radians around each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  19747. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  19748. */
  19749. get: function () {
  19750. return this._rotation;
  19751. },
  19752. set: function (newRotation) {
  19753. this._rotation = newRotation;
  19754. this._isDirty = true;
  19755. },
  19756. enumerable: true,
  19757. configurable: true
  19758. });
  19759. Object.defineProperty(TransformNode.prototype, "scaling", {
  19760. /**
  19761. * Gets or sets the scaling property : a Vector3 defining the node scaling along each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  19762. */
  19763. get: function () {
  19764. return this._scaling;
  19765. },
  19766. set: function (newScaling) {
  19767. this._scaling = newScaling;
  19768. this._isDirty = true;
  19769. },
  19770. enumerable: true,
  19771. configurable: true
  19772. });
  19773. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  19774. /**
  19775. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  19776. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  19777. */
  19778. get: function () {
  19779. return this._rotationQuaternion;
  19780. },
  19781. set: function (quaternion) {
  19782. this._rotationQuaternion = quaternion;
  19783. //reset the rotation vector.
  19784. if (quaternion && this.rotation.length()) {
  19785. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  19786. }
  19787. },
  19788. enumerable: true,
  19789. configurable: true
  19790. });
  19791. Object.defineProperty(TransformNode.prototype, "forward", {
  19792. /**
  19793. * The forward direction of that transform in world space.
  19794. */
  19795. get: function () {
  19796. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  19797. },
  19798. enumerable: true,
  19799. configurable: true
  19800. });
  19801. Object.defineProperty(TransformNode.prototype, "up", {
  19802. /**
  19803. * The up direction of that transform in world space.
  19804. */
  19805. get: function () {
  19806. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  19807. },
  19808. enumerable: true,
  19809. configurable: true
  19810. });
  19811. Object.defineProperty(TransformNode.prototype, "right", {
  19812. /**
  19813. * The right direction of that transform in world space.
  19814. */
  19815. get: function () {
  19816. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  19817. },
  19818. enumerable: true,
  19819. configurable: true
  19820. });
  19821. /**
  19822. * Copies the parameter passed Matrix into the mesh Pose matrix.
  19823. * @param matrix the matrix to copy the pose from
  19824. * @returns this TransformNode.
  19825. */
  19826. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  19827. this._poseMatrix.copyFrom(matrix);
  19828. return this;
  19829. };
  19830. /**
  19831. * Returns the mesh Pose matrix.
  19832. * @returns the pose matrix
  19833. */
  19834. TransformNode.prototype.getPoseMatrix = function () {
  19835. return this._poseMatrix;
  19836. };
  19837. /** @hidden */
  19838. TransformNode.prototype._isSynchronized = function () {
  19839. if (this._isDirty) {
  19840. return false;
  19841. }
  19842. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19843. return false;
  19844. }
  19845. if (this._cache.pivotMatrixUpdated) {
  19846. return false;
  19847. }
  19848. if (this.infiniteDistance) {
  19849. return false;
  19850. }
  19851. if (!this._cache.position.equals(this._position)) {
  19852. return false;
  19853. }
  19854. if (this._rotationQuaternion) {
  19855. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion)) {
  19856. return false;
  19857. }
  19858. }
  19859. if (!this._cache.rotation.equals(this._rotation)) {
  19860. return false;
  19861. }
  19862. if (!this._cache.scaling.equals(this._scaling)) {
  19863. return false;
  19864. }
  19865. return true;
  19866. };
  19867. /** @hidden */
  19868. TransformNode.prototype._initCache = function () {
  19869. _super.prototype._initCache.call(this);
  19870. this._cache.localMatrixUpdated = false;
  19871. this._cache.position = BABYLON.Vector3.Zero();
  19872. this._cache.scaling = BABYLON.Vector3.Zero();
  19873. this._cache.rotation = BABYLON.Vector3.Zero();
  19874. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  19875. this._cache.billboardMode = -1;
  19876. };
  19877. /**
  19878. * Flag the transform node as dirty (Forcing it to update everything)
  19879. * @param property if set to "rotation" the objects rotationQuaternion will be set to null
  19880. * @returns this transform node
  19881. */
  19882. TransformNode.prototype.markAsDirty = function (property) {
  19883. if (property === "rotation") {
  19884. this.rotationQuaternion = null;
  19885. }
  19886. this._currentRenderId = Number.MAX_VALUE;
  19887. this._isDirty = true;
  19888. return this;
  19889. };
  19890. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  19891. /**
  19892. * Returns the current mesh absolute position.
  19893. * Returns a Vector3.
  19894. */
  19895. get: function () {
  19896. return this._absolutePosition;
  19897. },
  19898. enumerable: true,
  19899. configurable: true
  19900. });
  19901. /**
  19902. * Sets a new matrix to apply before all other transformation
  19903. * @param matrix defines the transform matrix
  19904. * @returns the current TransformNode
  19905. */
  19906. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  19907. return this.setPivotMatrix(matrix, false);
  19908. };
  19909. /**
  19910. * Sets a new pivot matrix to the current node
  19911. * @param matrix defines the new pivot matrix to use
  19912. * @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
  19913. * @returns the current TransformNode
  19914. */
  19915. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  19916. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  19917. this._pivotMatrix = matrix.clone();
  19918. this._cache.pivotMatrixUpdated = true;
  19919. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  19920. if (this._postMultiplyPivotMatrix) {
  19921. if (!this._pivotMatrixInverse) {
  19922. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  19923. }
  19924. else {
  19925. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  19926. }
  19927. }
  19928. return this;
  19929. };
  19930. /**
  19931. * Returns the mesh pivot matrix.
  19932. * Default : Identity.
  19933. * @returns the matrix
  19934. */
  19935. TransformNode.prototype.getPivotMatrix = function () {
  19936. return this._pivotMatrix;
  19937. };
  19938. /**
  19939. * Prevents the World matrix to be computed any longer.
  19940. * @returns the TransformNode.
  19941. */
  19942. TransformNode.prototype.freezeWorldMatrix = function () {
  19943. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  19944. this.computeWorldMatrix(true);
  19945. this._isWorldMatrixFrozen = true;
  19946. return this;
  19947. };
  19948. /**
  19949. * Allows back the World matrix computation.
  19950. * @returns the TransformNode.
  19951. */
  19952. TransformNode.prototype.unfreezeWorldMatrix = function () {
  19953. this._isWorldMatrixFrozen = false;
  19954. this.computeWorldMatrix(true);
  19955. return this;
  19956. };
  19957. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  19958. /**
  19959. * True if the World matrix has been frozen.
  19960. */
  19961. get: function () {
  19962. return this._isWorldMatrixFrozen;
  19963. },
  19964. enumerable: true,
  19965. configurable: true
  19966. });
  19967. /**
  19968. * Retuns the mesh absolute position in the World.
  19969. * @returns a Vector3.
  19970. */
  19971. TransformNode.prototype.getAbsolutePosition = function () {
  19972. this.computeWorldMatrix();
  19973. return this._absolutePosition;
  19974. };
  19975. /**
  19976. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  19977. * @param absolutePosition the absolute position to set
  19978. * @returns the TransformNode.
  19979. */
  19980. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  19981. if (!absolutePosition) {
  19982. return this;
  19983. }
  19984. var absolutePositionX;
  19985. var absolutePositionY;
  19986. var absolutePositionZ;
  19987. if (absolutePosition.x === undefined) {
  19988. if (arguments.length < 3) {
  19989. return this;
  19990. }
  19991. absolutePositionX = arguments[0];
  19992. absolutePositionY = arguments[1];
  19993. absolutePositionZ = arguments[2];
  19994. }
  19995. else {
  19996. absolutePositionX = absolutePosition.x;
  19997. absolutePositionY = absolutePosition.y;
  19998. absolutePositionZ = absolutePosition.z;
  19999. }
  20000. if (this.parent) {
  20001. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  20002. invertParentWorldMatrix.invert();
  20003. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  20004. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  20005. }
  20006. else {
  20007. this.position.x = absolutePositionX;
  20008. this.position.y = absolutePositionY;
  20009. this.position.z = absolutePositionZ;
  20010. }
  20011. return this;
  20012. };
  20013. /**
  20014. * Sets the mesh position in its local space.
  20015. * @param vector3 the position to set in localspace
  20016. * @returns the TransformNode.
  20017. */
  20018. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  20019. this.computeWorldMatrix();
  20020. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  20021. return this;
  20022. };
  20023. /**
  20024. * Returns the mesh position in the local space from the current World matrix values.
  20025. * @returns a new Vector3.
  20026. */
  20027. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  20028. this.computeWorldMatrix();
  20029. var invLocalWorldMatrix = this._localWorld.clone();
  20030. invLocalWorldMatrix.invert();
  20031. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  20032. };
  20033. /**
  20034. * Translates the mesh along the passed Vector3 in its local space.
  20035. * @param vector3 the distance to translate in localspace
  20036. * @returns the TransformNode.
  20037. */
  20038. TransformNode.prototype.locallyTranslate = function (vector3) {
  20039. this.computeWorldMatrix(true);
  20040. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  20041. return this;
  20042. };
  20043. /**
  20044. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  20045. * @param targetPoint the position (must be in same space as current mesh) to look at
  20046. * @param yawCor optional yaw (y-axis) correction in radians
  20047. * @param pitchCor optional pitch (x-axis) correction in radians
  20048. * @param rollCor optional roll (z-axis) correction in radians
  20049. * @param space the choosen space of the target
  20050. * @returns the TransformNode.
  20051. */
  20052. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  20053. if (yawCor === void 0) { yawCor = 0; }
  20054. if (pitchCor === void 0) { pitchCor = 0; }
  20055. if (rollCor === void 0) { rollCor = 0; }
  20056. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  20057. var dv = TransformNode._lookAtVectorCache;
  20058. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  20059. targetPoint.subtractToRef(pos, dv);
  20060. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  20061. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  20062. var pitch = Math.atan2(dv.y, len);
  20063. if (this.rotationQuaternion) {
  20064. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  20065. }
  20066. else {
  20067. this.rotation.x = pitch + pitchCor;
  20068. this.rotation.y = yaw + yawCor;
  20069. this.rotation.z = rollCor;
  20070. }
  20071. return this;
  20072. };
  20073. /**
  20074. * Returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  20075. * This Vector3 is expressed in the World space.
  20076. * @param localAxis axis to rotate
  20077. * @returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  20078. */
  20079. TransformNode.prototype.getDirection = function (localAxis) {
  20080. var result = BABYLON.Vector3.Zero();
  20081. this.getDirectionToRef(localAxis, result);
  20082. return result;
  20083. };
  20084. /**
  20085. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  20086. * localAxis is expressed in the mesh local space.
  20087. * result is computed in the Wordl space from the mesh World matrix.
  20088. * @param localAxis axis to rotate
  20089. * @param result the resulting transformnode
  20090. * @returns this TransformNode.
  20091. */
  20092. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  20093. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20094. return this;
  20095. };
  20096. /**
  20097. * Sets a new pivot point to the current node
  20098. * @param point defines the new pivot point to use
  20099. * @param space defines if the point is in world or local space (local by default)
  20100. * @returns the current TransformNode
  20101. */
  20102. TransformNode.prototype.setPivotPoint = function (point, space) {
  20103. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  20104. if (this.getScene().getRenderId() == 0) {
  20105. this.computeWorldMatrix(true);
  20106. }
  20107. var wm = this.getWorldMatrix();
  20108. if (space == BABYLON.Space.WORLD) {
  20109. var tmat = BABYLON.Tmp.Matrix[0];
  20110. wm.invertToRef(tmat);
  20111. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  20112. }
  20113. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  20114. };
  20115. /**
  20116. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  20117. * @returns the pivot point
  20118. */
  20119. TransformNode.prototype.getPivotPoint = function () {
  20120. var point = BABYLON.Vector3.Zero();
  20121. this.getPivotPointToRef(point);
  20122. return point;
  20123. };
  20124. /**
  20125. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  20126. * @param result the vector3 to store the result
  20127. * @returns this TransformNode.
  20128. */
  20129. TransformNode.prototype.getPivotPointToRef = function (result) {
  20130. result.x = -this._pivotMatrix.m[12];
  20131. result.y = -this._pivotMatrix.m[13];
  20132. result.z = -this._pivotMatrix.m[14];
  20133. return this;
  20134. };
  20135. /**
  20136. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  20137. * @returns a new Vector3 set with the mesh pivot point World coordinates.
  20138. */
  20139. TransformNode.prototype.getAbsolutePivotPoint = function () {
  20140. var point = BABYLON.Vector3.Zero();
  20141. this.getAbsolutePivotPointToRef(point);
  20142. return point;
  20143. };
  20144. /**
  20145. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  20146. * @param result vector3 to store the result
  20147. * @returns this TransformNode.
  20148. */
  20149. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  20150. result.x = this._pivotMatrix.m[12];
  20151. result.y = this._pivotMatrix.m[13];
  20152. result.z = this._pivotMatrix.m[14];
  20153. this.getPivotPointToRef(result);
  20154. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  20155. return this;
  20156. };
  20157. /**
  20158. * Defines the passed node as the parent of the current node.
  20159. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  20160. * @param node the node ot set as the parent
  20161. * @returns this TransformNode.
  20162. */
  20163. TransformNode.prototype.setParent = function (node) {
  20164. if (!node && !this.parent) {
  20165. return this;
  20166. }
  20167. if (!node) {
  20168. var rotation = BABYLON.Tmp.Quaternion[0];
  20169. var position = BABYLON.Tmp.Vector3[0];
  20170. var scale = BABYLON.Tmp.Vector3[1];
  20171. if (this.parent && this.parent.computeWorldMatrix) {
  20172. this.parent.computeWorldMatrix(true);
  20173. }
  20174. this.computeWorldMatrix(true);
  20175. this.getWorldMatrix().decompose(scale, rotation, position);
  20176. if (this.rotationQuaternion) {
  20177. this.rotationQuaternion.copyFrom(rotation);
  20178. }
  20179. else {
  20180. rotation.toEulerAnglesToRef(this.rotation);
  20181. }
  20182. this.scaling.x = scale.x;
  20183. this.scaling.y = scale.y;
  20184. this.scaling.z = scale.z;
  20185. this.position.x = position.x;
  20186. this.position.y = position.y;
  20187. this.position.z = position.z;
  20188. }
  20189. else {
  20190. var rotation = BABYLON.Tmp.Quaternion[0];
  20191. var position = BABYLON.Tmp.Vector3[0];
  20192. var scale = BABYLON.Tmp.Vector3[1];
  20193. var diffMatrix = BABYLON.Tmp.Matrix[0];
  20194. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  20195. this.computeWorldMatrix(true);
  20196. node.computeWorldMatrix(true);
  20197. node.getWorldMatrix().invertToRef(invParentMatrix);
  20198. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  20199. diffMatrix.decompose(scale, rotation, position);
  20200. if (this.rotationQuaternion) {
  20201. this.rotationQuaternion.copyFrom(rotation);
  20202. }
  20203. else {
  20204. rotation.toEulerAnglesToRef(this.rotation);
  20205. }
  20206. this.position.x = position.x;
  20207. this.position.y = position.y;
  20208. this.position.z = position.z;
  20209. this.scaling.x = scale.x;
  20210. this.scaling.y = scale.y;
  20211. this.scaling.z = scale.z;
  20212. }
  20213. this.parent = node;
  20214. return this;
  20215. };
  20216. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  20217. /**
  20218. * True if the scaling property of this object is non uniform eg. (1,2,1)
  20219. */
  20220. get: function () {
  20221. return this._nonUniformScaling;
  20222. },
  20223. enumerable: true,
  20224. configurable: true
  20225. });
  20226. /** @hidden */
  20227. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  20228. if (this._nonUniformScaling === value) {
  20229. return false;
  20230. }
  20231. this._nonUniformScaling = value;
  20232. return true;
  20233. };
  20234. /**
  20235. * Attach the current TransformNode to another TransformNode associated with a bone
  20236. * @param bone Bone affecting the TransformNode
  20237. * @param affectedTransformNode TransformNode associated with the bone
  20238. * @returns this object
  20239. */
  20240. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  20241. this._transformToBoneReferal = affectedTransformNode;
  20242. this.parent = bone;
  20243. if (bone.getWorldMatrix().determinant() < 0) {
  20244. this.scalingDeterminant *= -1;
  20245. }
  20246. return this;
  20247. };
  20248. /**
  20249. * Detach the transform node if its associated with a bone
  20250. * @returns this object
  20251. */
  20252. TransformNode.prototype.detachFromBone = function () {
  20253. if (!this.parent) {
  20254. return this;
  20255. }
  20256. if (this.parent.getWorldMatrix().determinant() < 0) {
  20257. this.scalingDeterminant *= -1;
  20258. }
  20259. this._transformToBoneReferal = null;
  20260. this.parent = null;
  20261. return this;
  20262. };
  20263. /**
  20264. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  20265. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20266. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20267. * The passed axis is also normalized.
  20268. * @param axis the axis to rotate around
  20269. * @param amount the amount to rotate in radians
  20270. * @param space Space to rotate in (Default: local)
  20271. * @returns the TransformNode.
  20272. */
  20273. TransformNode.prototype.rotate = function (axis, amount, space) {
  20274. axis.normalize();
  20275. if (!this.rotationQuaternion) {
  20276. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20277. this.rotation = BABYLON.Vector3.Zero();
  20278. }
  20279. var rotationQuaternion;
  20280. if (!space || space === BABYLON.Space.LOCAL) {
  20281. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20282. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  20283. }
  20284. else {
  20285. if (this.parent) {
  20286. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  20287. invertParentWorldMatrix.invert();
  20288. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  20289. }
  20290. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20291. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20292. }
  20293. return this;
  20294. };
  20295. /**
  20296. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  20297. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20298. * The passed axis is also normalized. .
  20299. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  20300. * @param point the point to rotate around
  20301. * @param axis the axis to rotate around
  20302. * @param amount the amount to rotate in radians
  20303. * @returns the TransformNode
  20304. */
  20305. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  20306. axis.normalize();
  20307. if (!this.rotationQuaternion) {
  20308. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20309. this.rotation.copyFromFloats(0, 0, 0);
  20310. }
  20311. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  20312. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  20313. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  20314. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  20315. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  20316. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  20317. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  20318. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  20319. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20320. return this;
  20321. };
  20322. /**
  20323. * Translates the mesh along the axis vector for the passed distance in the given space.
  20324. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20325. * @param axis the axis to translate in
  20326. * @param distance the distance to translate
  20327. * @param space Space to rotate in (Default: local)
  20328. * @returns the TransformNode.
  20329. */
  20330. TransformNode.prototype.translate = function (axis, distance, space) {
  20331. var displacementVector = axis.scale(distance);
  20332. if (!space || space === BABYLON.Space.LOCAL) {
  20333. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  20334. this.setPositionWithLocalVector(tempV3);
  20335. }
  20336. else {
  20337. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  20338. }
  20339. return this;
  20340. };
  20341. /**
  20342. * Adds a rotation step to the mesh current rotation.
  20343. * x, y, z are Euler angles expressed in radians.
  20344. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  20345. * This means this rotation is made in the mesh local space only.
  20346. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  20347. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  20348. * ```javascript
  20349. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  20350. * ```
  20351. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  20352. * 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.
  20353. * @param x Rotation to add
  20354. * @param y Rotation to add
  20355. * @param z Rotation to add
  20356. * @returns the TransformNode.
  20357. */
  20358. TransformNode.prototype.addRotation = function (x, y, z) {
  20359. var rotationQuaternion;
  20360. if (this.rotationQuaternion) {
  20361. rotationQuaternion = this.rotationQuaternion;
  20362. }
  20363. else {
  20364. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  20365. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  20366. }
  20367. var accumulation = BABYLON.Tmp.Quaternion[0];
  20368. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  20369. rotationQuaternion.multiplyInPlace(accumulation);
  20370. if (!this.rotationQuaternion) {
  20371. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  20372. }
  20373. return this;
  20374. };
  20375. /**
  20376. * Computes the world matrix of the node
  20377. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  20378. * @returns the world matrix
  20379. */
  20380. TransformNode.prototype.computeWorldMatrix = function (force) {
  20381. if (this._isWorldMatrixFrozen) {
  20382. return this._worldMatrix;
  20383. }
  20384. if (!force && this.isSynchronized()) {
  20385. this._currentRenderId = this.getScene().getRenderId();
  20386. return this._worldMatrix;
  20387. }
  20388. this._updateCache();
  20389. this._cache.position.copyFrom(this.position);
  20390. this._cache.scaling.copyFrom(this.scaling);
  20391. this._cache.pivotMatrixUpdated = false;
  20392. this._cache.billboardMode = this.billboardMode;
  20393. this._currentRenderId = this.getScene().getRenderId();
  20394. this._childRenderId = this.getScene().getRenderId();
  20395. this._isDirty = false;
  20396. // Scaling
  20397. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  20398. // Rotation
  20399. //rotate, if quaternion is set and rotation was used
  20400. if (this.rotationQuaternion) {
  20401. var len = this.rotation.length();
  20402. if (len) {
  20403. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  20404. this.rotation.copyFromFloats(0, 0, 0);
  20405. }
  20406. }
  20407. if (this.rotationQuaternion) {
  20408. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  20409. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  20410. }
  20411. else {
  20412. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  20413. this._cache.rotation.copyFrom(this.rotation);
  20414. }
  20415. // Translation
  20416. var camera = this.getScene().activeCamera;
  20417. if (this.infiniteDistance && !this.parent && camera) {
  20418. var cameraWorldMatrix = camera.getWorldMatrix();
  20419. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  20420. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  20421. }
  20422. else {
  20423. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  20424. }
  20425. // Composing transformations
  20426. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  20427. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20428. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  20429. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  20430. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  20431. // Need to decompose each rotation here
  20432. var currentPosition = BABYLON.Tmp.Vector3[3];
  20433. if (this.parent && this.parent.getWorldMatrix) {
  20434. if (this._transformToBoneReferal) {
  20435. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20436. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  20437. }
  20438. else {
  20439. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  20440. }
  20441. }
  20442. else {
  20443. currentPosition.copyFrom(this.position);
  20444. }
  20445. currentPosition.subtractInPlace(camera.globalPosition);
  20446. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  20447. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  20448. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  20449. }
  20450. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  20451. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  20452. }
  20453. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  20454. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  20455. }
  20456. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  20457. }
  20458. else {
  20459. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  20460. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  20461. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  20462. }
  20463. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  20464. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20465. }
  20466. // Post multiply inverse of pivotMatrix
  20467. if (this._postMultiplyPivotMatrix) {
  20468. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  20469. }
  20470. // Local world
  20471. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  20472. // Parent
  20473. if (this.parent && this.parent.getWorldMatrix) {
  20474. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  20475. if (this._transformToBoneReferal) {
  20476. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20477. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  20478. }
  20479. else {
  20480. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  20481. }
  20482. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  20483. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  20484. this._worldMatrix.copyFrom(this._localWorld);
  20485. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  20486. }
  20487. else {
  20488. if (this._transformToBoneReferal) {
  20489. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20490. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  20491. }
  20492. else {
  20493. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  20494. }
  20495. }
  20496. this._markSyncedWithParent();
  20497. }
  20498. else {
  20499. this._worldMatrix.copyFrom(this._localWorld);
  20500. }
  20501. // Normal matrix
  20502. if (!this.ignoreNonUniformScaling) {
  20503. if (this.scaling.isNonUniform) {
  20504. this._updateNonUniformScalingState(true);
  20505. }
  20506. else if (this.parent && this.parent._nonUniformScaling) {
  20507. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  20508. }
  20509. else {
  20510. this._updateNonUniformScalingState(false);
  20511. }
  20512. }
  20513. else {
  20514. this._updateNonUniformScalingState(false);
  20515. }
  20516. this._afterComputeWorldMatrix();
  20517. // Absolute position
  20518. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  20519. // Callbacks
  20520. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  20521. if (!this._poseMatrix) {
  20522. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  20523. }
  20524. // Cache the determinant
  20525. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  20526. return this._worldMatrix;
  20527. };
  20528. TransformNode.prototype._afterComputeWorldMatrix = function () {
  20529. };
  20530. /**
  20531. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  20532. * @param func callback function to add
  20533. *
  20534. * @returns the TransformNode.
  20535. */
  20536. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  20537. this.onAfterWorldMatrixUpdateObservable.add(func);
  20538. return this;
  20539. };
  20540. /**
  20541. * Removes a registered callback function.
  20542. * @param func callback function to remove
  20543. * @returns the TransformNode.
  20544. */
  20545. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  20546. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  20547. return this;
  20548. };
  20549. /**
  20550. * Clone the current transform node
  20551. * @param name Name of the new clone
  20552. * @param newParent New parent for the clone
  20553. * @param doNotCloneChildren Do not clone children hierarchy
  20554. * @returns the new transform node
  20555. */
  20556. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20557. var _this = this;
  20558. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  20559. result.name = name;
  20560. result.id = name;
  20561. if (newParent) {
  20562. result.parent = newParent;
  20563. }
  20564. if (!doNotCloneChildren) {
  20565. // Children
  20566. var directDescendants = this.getDescendants(true);
  20567. for (var index = 0; index < directDescendants.length; index++) {
  20568. var child = directDescendants[index];
  20569. if (child.clone) {
  20570. child.clone(name + "." + child.name, result);
  20571. }
  20572. }
  20573. }
  20574. return result;
  20575. };
  20576. /**
  20577. * Serializes the objects information.
  20578. * @param currentSerializationObject defines the object to serialize in
  20579. * @returns the serialized object
  20580. */
  20581. TransformNode.prototype.serialize = function (currentSerializationObject) {
  20582. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  20583. serializationObject.type = this.getClassName();
  20584. // Parent
  20585. if (this.parent) {
  20586. serializationObject.parentId = this.parent.id;
  20587. }
  20588. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  20589. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20590. }
  20591. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20592. serializationObject.isEnabled = this.isEnabled();
  20593. // Parent
  20594. if (this.parent) {
  20595. serializationObject.parentId = this.parent.id;
  20596. }
  20597. return serializationObject;
  20598. };
  20599. // Statics
  20600. /**
  20601. * Returns a new TransformNode object parsed from the source provided.
  20602. * @param parsedTransformNode is the source.
  20603. * @param scene the scne the object belongs to
  20604. * @param rootUrl is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20605. * @returns a new TransformNode object parsed from the source provided.
  20606. */
  20607. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  20608. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  20609. if (BABYLON.Tags) {
  20610. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  20611. }
  20612. if (parsedTransformNode.localMatrix) {
  20613. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  20614. }
  20615. else if (parsedTransformNode.pivotMatrix) {
  20616. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  20617. }
  20618. transformNode.setEnabled(parsedTransformNode.isEnabled);
  20619. // Parent
  20620. if (parsedTransformNode.parentId) {
  20621. transformNode._waitingParentId = parsedTransformNode.parentId;
  20622. }
  20623. return transformNode;
  20624. };
  20625. /**
  20626. * Releases resources associated with this transform node.
  20627. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20628. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20629. */
  20630. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20631. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20632. // Animations
  20633. this.getScene().stopAnimation(this);
  20634. // Remove from scene
  20635. this.getScene().removeTransformNode(this);
  20636. this.onAfterWorldMatrixUpdateObservable.clear();
  20637. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20638. };
  20639. // Statics
  20640. /**
  20641. * Object will not rotate to face the camera
  20642. */
  20643. TransformNode.BILLBOARDMODE_NONE = 0;
  20644. /**
  20645. * Object will rotate to face the camera but only on the x axis
  20646. */
  20647. TransformNode.BILLBOARDMODE_X = 1;
  20648. /**
  20649. * Object will rotate to face the camera but only on the y axis
  20650. */
  20651. TransformNode.BILLBOARDMODE_Y = 2;
  20652. /**
  20653. * Object will rotate to face the camera but only on the z axis
  20654. */
  20655. TransformNode.BILLBOARDMODE_Z = 4;
  20656. /**
  20657. * Object will rotate to face the camera
  20658. */
  20659. TransformNode.BILLBOARDMODE_ALL = 7;
  20660. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  20661. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  20662. __decorate([
  20663. BABYLON.serializeAsVector3("position")
  20664. ], TransformNode.prototype, "_position", void 0);
  20665. __decorate([
  20666. BABYLON.serializeAsVector3("rotation")
  20667. ], TransformNode.prototype, "_rotation", void 0);
  20668. __decorate([
  20669. BABYLON.serializeAsQuaternion("rotationQuaternion")
  20670. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  20671. __decorate([
  20672. BABYLON.serializeAsVector3("scaling")
  20673. ], TransformNode.prototype, "_scaling", void 0);
  20674. __decorate([
  20675. BABYLON.serialize()
  20676. ], TransformNode.prototype, "billboardMode", void 0);
  20677. __decorate([
  20678. BABYLON.serialize()
  20679. ], TransformNode.prototype, "scalingDeterminant", void 0);
  20680. __decorate([
  20681. BABYLON.serialize()
  20682. ], TransformNode.prototype, "infiniteDistance", void 0);
  20683. __decorate([
  20684. BABYLON.serialize()
  20685. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  20686. return TransformNode;
  20687. }(BABYLON.Node));
  20688. BABYLON.TransformNode = TransformNode;
  20689. })(BABYLON || (BABYLON = {}));
  20690. //# sourceMappingURL=babylon.transformNode.js.map
  20691. var BABYLON;
  20692. (function (BABYLON) {
  20693. /** @hidden */
  20694. var _FacetDataStorage = /** @class */ (function () {
  20695. function _FacetDataStorage() {
  20696. this.facetNb = 0; // facet number
  20697. this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  20698. this.partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  20699. this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  20700. this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  20701. this.bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  20702. this.subDiv = {
  20703. max: 1,
  20704. X: 1,
  20705. Y: 1,
  20706. Z: 1
  20707. };
  20708. this.facetDepthSort = false; // is the facet depth sort to be computed
  20709. this.facetDepthSortEnabled = false; // is the facet depth sort initialized
  20710. }
  20711. return _FacetDataStorage;
  20712. }());
  20713. /**
  20714. * Class used to store all common mesh properties
  20715. */
  20716. var AbstractMesh = /** @class */ (function (_super) {
  20717. __extends(AbstractMesh, _super);
  20718. // Constructor
  20719. /**
  20720. * Creates a new AbstractMesh
  20721. * @param name defines the name of the mesh
  20722. * @param scene defines the hosting scene
  20723. */
  20724. function AbstractMesh(name, scene) {
  20725. if (scene === void 0) { scene = null; }
  20726. var _this = _super.call(this, name, scene, false) || this;
  20727. _this._facetData = new _FacetDataStorage();
  20728. /** Gets ot sets the culling strategy to use to find visible meshes */
  20729. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  20730. // Events
  20731. /**
  20732. * An event triggered when this mesh collides with another one
  20733. */
  20734. _this.onCollideObservable = new BABYLON.Observable();
  20735. /**
  20736. * An event triggered when the collision's position changes
  20737. */
  20738. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  20739. /**
  20740. * An event triggered when material is changed
  20741. */
  20742. _this.onMaterialChangedObservable = new BABYLON.Observable();
  20743. // Properties
  20744. /**
  20745. * Gets or sets the orientation for POV movement & rotation
  20746. */
  20747. _this.definedFacingForward = true;
  20748. _this._visibility = 1.0;
  20749. /** Gets or sets the alpha index used to sort transparent meshes
  20750. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  20751. */
  20752. _this.alphaIndex = Number.MAX_VALUE;
  20753. /**
  20754. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  20755. */
  20756. _this.isVisible = true;
  20757. /**
  20758. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  20759. */
  20760. _this.isPickable = true;
  20761. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  20762. _this.showSubMeshesBoundingBox = false;
  20763. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  20764. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  20765. */
  20766. _this.isBlocker = false;
  20767. /**
  20768. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  20769. */
  20770. _this.enablePointerMoveEvents = false;
  20771. /**
  20772. * Specifies the rendering group id for this mesh (0 by default)
  20773. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  20774. */
  20775. _this.renderingGroupId = 0;
  20776. _this._receiveShadows = false;
  20777. /** Defines color to use when rendering outline */
  20778. _this.outlineColor = BABYLON.Color3.Red();
  20779. /** Define width to use when rendering outline */
  20780. _this.outlineWidth = 0.02;
  20781. /** Defines color to use when rendering overlay */
  20782. _this.overlayColor = BABYLON.Color3.Red();
  20783. /** Defines alpha to use when rendering overlay */
  20784. _this.overlayAlpha = 0.5;
  20785. _this._hasVertexAlpha = false;
  20786. _this._useVertexColors = true;
  20787. _this._computeBonesUsingShaders = true;
  20788. _this._numBoneInfluencers = 4;
  20789. _this._applyFog = true;
  20790. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  20791. _this.useOctreeForRenderingSelection = true;
  20792. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  20793. _this.useOctreeForPicking = true;
  20794. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  20795. _this.useOctreeForCollisions = true;
  20796. _this._layerMask = 0x0FFFFFFF;
  20797. /**
  20798. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  20799. */
  20800. _this.alwaysSelectAsActiveMesh = false;
  20801. /**
  20802. * Gets or sets the current action manager
  20803. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  20804. */
  20805. _this.actionManager = null;
  20806. // Collisions
  20807. _this._checkCollisions = false;
  20808. _this._collisionMask = -1;
  20809. _this._collisionGroup = -1;
  20810. /**
  20811. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  20812. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20813. */
  20814. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  20815. /**
  20816. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  20817. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20818. */
  20819. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  20820. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20821. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20822. // Edges
  20823. /**
  20824. * Defines edge width used when edgesRenderer is enabled
  20825. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20826. */
  20827. _this.edgesWidth = 1;
  20828. /**
  20829. * Defines edge color used when edgesRenderer is enabled
  20830. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20831. */
  20832. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  20833. /** @hidden */
  20834. _this._renderId = 0;
  20835. /** @hidden */
  20836. _this._intersectionsInProgress = new Array();
  20837. /** @hidden */
  20838. _this._unIndexed = false;
  20839. /** @hidden */
  20840. _this._lightSources = new Array();
  20841. /**
  20842. * An event triggered when the mesh is rebuilt.
  20843. */
  20844. _this.onRebuildObservable = new BABYLON.Observable();
  20845. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  20846. if (collidedMesh === void 0) { collidedMesh = null; }
  20847. //TODO move this to the collision coordinator!
  20848. if (_this.getScene().workerCollisions) {
  20849. newPosition.multiplyInPlace(_this._collider._radius);
  20850. }
  20851. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  20852. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  20853. _this.position.addInPlace(_this._diffPositionForCollisions);
  20854. }
  20855. if (collidedMesh) {
  20856. _this.onCollideObservable.notifyObservers(collidedMesh);
  20857. }
  20858. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  20859. };
  20860. _this.getScene().addMesh(_this);
  20861. _this._resyncLightSources();
  20862. return _this;
  20863. }
  20864. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  20865. /**
  20866. * No billboard
  20867. */
  20868. get: function () {
  20869. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  20870. },
  20871. enumerable: true,
  20872. configurable: true
  20873. });
  20874. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  20875. /** Billboard on X axis */
  20876. get: function () {
  20877. return BABYLON.TransformNode.BILLBOARDMODE_X;
  20878. },
  20879. enumerable: true,
  20880. configurable: true
  20881. });
  20882. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  20883. /** Billboard on Y axis */
  20884. get: function () {
  20885. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  20886. },
  20887. enumerable: true,
  20888. configurable: true
  20889. });
  20890. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  20891. /** Billboard on Z axis */
  20892. get: function () {
  20893. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  20894. },
  20895. enumerable: true,
  20896. configurable: true
  20897. });
  20898. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  20899. /** Billboard on all axes */
  20900. get: function () {
  20901. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  20902. },
  20903. enumerable: true,
  20904. configurable: true
  20905. });
  20906. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  20907. /**
  20908. * Gets the number of facets in the mesh
  20909. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20910. */
  20911. get: function () {
  20912. return this._facetData.facetNb;
  20913. },
  20914. enumerable: true,
  20915. configurable: true
  20916. });
  20917. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  20918. /**
  20919. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  20920. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20921. */
  20922. get: function () {
  20923. return this._facetData.partitioningSubdivisions;
  20924. },
  20925. set: function (nb) {
  20926. this._facetData.partitioningSubdivisions = nb;
  20927. },
  20928. enumerable: true,
  20929. configurable: true
  20930. });
  20931. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  20932. /**
  20933. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  20934. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  20935. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20936. */
  20937. get: function () {
  20938. return this._facetData.partitioningBBoxRatio;
  20939. },
  20940. set: function (ratio) {
  20941. this._facetData.partitioningBBoxRatio = ratio;
  20942. },
  20943. enumerable: true,
  20944. configurable: true
  20945. });
  20946. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  20947. /**
  20948. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  20949. * Works only for updatable meshes.
  20950. * Doesn't work with multi-materials
  20951. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20952. */
  20953. get: function () {
  20954. return this._facetData.facetDepthSort;
  20955. },
  20956. set: function (sort) {
  20957. this._facetData.facetDepthSort = sort;
  20958. },
  20959. enumerable: true,
  20960. configurable: true
  20961. });
  20962. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  20963. /**
  20964. * The location (Vector3) where the facet depth sort must be computed from.
  20965. * By default, the active camera position.
  20966. * Used only when facet depth sort is enabled
  20967. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20968. */
  20969. get: function () {
  20970. return this._facetData.facetDepthSortFrom;
  20971. },
  20972. set: function (location) {
  20973. this._facetData.facetDepthSortFrom = location;
  20974. },
  20975. enumerable: true,
  20976. configurable: true
  20977. });
  20978. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  20979. /**
  20980. * gets a boolean indicating if facetData is enabled
  20981. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20982. */
  20983. get: function () {
  20984. return this._facetData.facetDataEnabled;
  20985. },
  20986. enumerable: true,
  20987. configurable: true
  20988. });
  20989. /** @hidden */
  20990. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  20991. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  20992. return false;
  20993. }
  20994. this._markSubMeshesAsMiscDirty();
  20995. return true;
  20996. };
  20997. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  20998. /** Set a function to call when this mesh collides with another one */
  20999. set: function (callback) {
  21000. if (this._onCollideObserver) {
  21001. this.onCollideObservable.remove(this._onCollideObserver);
  21002. }
  21003. this._onCollideObserver = this.onCollideObservable.add(callback);
  21004. },
  21005. enumerable: true,
  21006. configurable: true
  21007. });
  21008. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  21009. /** Set a function to call when the collision's position changes */
  21010. set: function (callback) {
  21011. if (this._onCollisionPositionChangeObserver) {
  21012. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  21013. }
  21014. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  21015. },
  21016. enumerable: true,
  21017. configurable: true
  21018. });
  21019. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  21020. /**
  21021. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  21022. */
  21023. get: function () {
  21024. return this._visibility;
  21025. },
  21026. /**
  21027. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  21028. */
  21029. set: function (value) {
  21030. if (this._visibility === value) {
  21031. return;
  21032. }
  21033. this._visibility = value;
  21034. this._markSubMeshesAsMiscDirty();
  21035. },
  21036. enumerable: true,
  21037. configurable: true
  21038. });
  21039. Object.defineProperty(AbstractMesh.prototype, "material", {
  21040. /** Gets or sets current material */
  21041. get: function () {
  21042. return this._material;
  21043. },
  21044. set: function (value) {
  21045. if (this._material === value) {
  21046. return;
  21047. }
  21048. this._material = value;
  21049. if (this.onMaterialChangedObservable.hasObservers) {
  21050. this.onMaterialChangedObservable.notifyObservers(this);
  21051. }
  21052. if (!this.subMeshes) {
  21053. return;
  21054. }
  21055. this._unBindEffect();
  21056. },
  21057. enumerable: true,
  21058. configurable: true
  21059. });
  21060. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  21061. /**
  21062. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  21063. * @see http://doc.babylonjs.com/babylon101/shadows
  21064. */
  21065. get: function () {
  21066. return this._receiveShadows;
  21067. },
  21068. set: function (value) {
  21069. if (this._receiveShadows === value) {
  21070. return;
  21071. }
  21072. this._receiveShadows = value;
  21073. this._markSubMeshesAsLightDirty();
  21074. },
  21075. enumerable: true,
  21076. configurable: true
  21077. });
  21078. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  21079. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  21080. get: function () {
  21081. return this._hasVertexAlpha;
  21082. },
  21083. set: function (value) {
  21084. if (this._hasVertexAlpha === value) {
  21085. return;
  21086. }
  21087. this._hasVertexAlpha = value;
  21088. this._markSubMeshesAsAttributesDirty();
  21089. this._markSubMeshesAsMiscDirty();
  21090. },
  21091. enumerable: true,
  21092. configurable: true
  21093. });
  21094. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  21095. /** 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) */
  21096. get: function () {
  21097. return this._useVertexColors;
  21098. },
  21099. set: function (value) {
  21100. if (this._useVertexColors === value) {
  21101. return;
  21102. }
  21103. this._useVertexColors = value;
  21104. this._markSubMeshesAsAttributesDirty();
  21105. },
  21106. enumerable: true,
  21107. configurable: true
  21108. });
  21109. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  21110. /**
  21111. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  21112. */
  21113. get: function () {
  21114. return this._computeBonesUsingShaders;
  21115. },
  21116. set: function (value) {
  21117. if (this._computeBonesUsingShaders === value) {
  21118. return;
  21119. }
  21120. this._computeBonesUsingShaders = value;
  21121. this._markSubMeshesAsAttributesDirty();
  21122. },
  21123. enumerable: true,
  21124. configurable: true
  21125. });
  21126. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  21127. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  21128. get: function () {
  21129. return this._numBoneInfluencers;
  21130. },
  21131. set: function (value) {
  21132. if (this._numBoneInfluencers === value) {
  21133. return;
  21134. }
  21135. this._numBoneInfluencers = value;
  21136. this._markSubMeshesAsAttributesDirty();
  21137. },
  21138. enumerable: true,
  21139. configurable: true
  21140. });
  21141. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  21142. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  21143. get: function () {
  21144. return this._applyFog;
  21145. },
  21146. set: function (value) {
  21147. if (this._applyFog === value) {
  21148. return;
  21149. }
  21150. this._applyFog = value;
  21151. this._markSubMeshesAsMiscDirty();
  21152. },
  21153. enumerable: true,
  21154. configurable: true
  21155. });
  21156. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  21157. /**
  21158. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  21159. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  21160. */
  21161. get: function () {
  21162. return this._layerMask;
  21163. },
  21164. set: function (value) {
  21165. if (value === this._layerMask) {
  21166. return;
  21167. }
  21168. this._layerMask = value;
  21169. this._resyncLightSources();
  21170. },
  21171. enumerable: true,
  21172. configurable: true
  21173. });
  21174. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  21175. /**
  21176. * Gets or sets a collision mask used to mask collisions (default is -1).
  21177. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21178. */
  21179. get: function () {
  21180. return this._collisionMask;
  21181. },
  21182. set: function (mask) {
  21183. this._collisionMask = !isNaN(mask) ? mask : -1;
  21184. },
  21185. enumerable: true,
  21186. configurable: true
  21187. });
  21188. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  21189. /**
  21190. * Gets or sets the current collision group mask (-1 by default).
  21191. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21192. */
  21193. get: function () {
  21194. return this._collisionGroup;
  21195. },
  21196. set: function (mask) {
  21197. this._collisionGroup = !isNaN(mask) ? mask : -1;
  21198. },
  21199. enumerable: true,
  21200. configurable: true
  21201. });
  21202. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  21203. /** @hidden */
  21204. get: function () {
  21205. return null;
  21206. },
  21207. enumerable: true,
  21208. configurable: true
  21209. });
  21210. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  21211. get: function () {
  21212. return this._skeleton;
  21213. },
  21214. /**
  21215. * Gets or sets a skeleton to apply skining transformations
  21216. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  21217. */
  21218. set: function (value) {
  21219. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  21220. this._skeleton._unregisterMeshWithPoseMatrix(this);
  21221. }
  21222. if (value && value.needInitialSkinMatrix) {
  21223. value._registerMeshWithPoseMatrix(this);
  21224. }
  21225. this._skeleton = value;
  21226. if (!this._skeleton) {
  21227. this._bonesTransformMatrices = null;
  21228. }
  21229. this._markSubMeshesAsAttributesDirty();
  21230. },
  21231. enumerable: true,
  21232. configurable: true
  21233. });
  21234. /**
  21235. * Returns the string "AbstractMesh"
  21236. * @returns "AbstractMesh"
  21237. */
  21238. AbstractMesh.prototype.getClassName = function () {
  21239. return "AbstractMesh";
  21240. };
  21241. /**
  21242. * Gets a string representation of the current mesh
  21243. * @param fullDetails defines a boolean indicating if full details must be included
  21244. * @returns a string representation of the current mesh
  21245. */
  21246. AbstractMesh.prototype.toString = function (fullDetails) {
  21247. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  21248. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  21249. if (this._skeleton) {
  21250. ret += ", skeleton: " + this._skeleton.name;
  21251. }
  21252. if (fullDetails) {
  21253. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  21254. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  21255. }
  21256. return ret;
  21257. };
  21258. /** @hidden */
  21259. AbstractMesh.prototype._rebuild = function () {
  21260. this.onRebuildObservable.notifyObservers(this);
  21261. if (this._occlusionQuery) {
  21262. this._occlusionQuery = null;
  21263. }
  21264. if (!this.subMeshes) {
  21265. return;
  21266. }
  21267. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21268. var subMesh = _a[_i];
  21269. subMesh._rebuild();
  21270. }
  21271. };
  21272. /** @hidden */
  21273. AbstractMesh.prototype._resyncLightSources = function () {
  21274. this._lightSources.length = 0;
  21275. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  21276. var light = _a[_i];
  21277. if (!light.isEnabled()) {
  21278. continue;
  21279. }
  21280. if (light.canAffectMesh(this)) {
  21281. this._lightSources.push(light);
  21282. }
  21283. }
  21284. this._markSubMeshesAsLightDirty();
  21285. };
  21286. /** @hidden */
  21287. AbstractMesh.prototype._resyncLighSource = function (light) {
  21288. var isIn = light.isEnabled() && light.canAffectMesh(this);
  21289. var index = this._lightSources.indexOf(light);
  21290. if (index === -1) {
  21291. if (!isIn) {
  21292. return;
  21293. }
  21294. this._lightSources.push(light);
  21295. }
  21296. else {
  21297. if (isIn) {
  21298. return;
  21299. }
  21300. this._lightSources.splice(index, 1);
  21301. }
  21302. this._markSubMeshesAsLightDirty();
  21303. };
  21304. /** @hidden */
  21305. AbstractMesh.prototype._unBindEffect = function () {
  21306. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21307. var subMesh = _a[_i];
  21308. subMesh.setEffect(null);
  21309. }
  21310. };
  21311. /** @hidden */
  21312. AbstractMesh.prototype._removeLightSource = function (light) {
  21313. var index = this._lightSources.indexOf(light);
  21314. if (index === -1) {
  21315. return;
  21316. }
  21317. this._lightSources.splice(index, 1);
  21318. this._markSubMeshesAsLightDirty();
  21319. };
  21320. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  21321. if (!this.subMeshes) {
  21322. return;
  21323. }
  21324. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21325. var subMesh = _a[_i];
  21326. if (subMesh._materialDefines) {
  21327. func(subMesh._materialDefines);
  21328. }
  21329. }
  21330. };
  21331. /** @hidden */
  21332. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  21333. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  21334. };
  21335. /** @hidden */
  21336. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  21337. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  21338. };
  21339. /** @hidden */
  21340. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  21341. if (!this.subMeshes) {
  21342. return;
  21343. }
  21344. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21345. var subMesh = _a[_i];
  21346. var material = subMesh.getMaterial();
  21347. if (material) {
  21348. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  21349. }
  21350. }
  21351. };
  21352. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  21353. /**
  21354. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  21355. */
  21356. get: function () {
  21357. return this._scaling;
  21358. },
  21359. set: function (newScaling) {
  21360. this._scaling = newScaling;
  21361. if (this.physicsImpostor) {
  21362. this.physicsImpostor.forceUpdate();
  21363. }
  21364. },
  21365. enumerable: true,
  21366. configurable: true
  21367. });
  21368. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  21369. // Methods
  21370. /**
  21371. * Returns true if the mesh is blocked. Implemented by child classes
  21372. */
  21373. get: function () {
  21374. return false;
  21375. },
  21376. enumerable: true,
  21377. configurable: true
  21378. });
  21379. /**
  21380. * Returns the mesh itself by default. Implemented by child classes
  21381. * @param camera defines the camera to use to pick the right LOD level
  21382. * @returns the currentAbstractMesh
  21383. */
  21384. AbstractMesh.prototype.getLOD = function (camera) {
  21385. return this;
  21386. };
  21387. /**
  21388. * Returns 0 by default. Implemented by child classes
  21389. * @returns an integer
  21390. */
  21391. AbstractMesh.prototype.getTotalVertices = function () {
  21392. return 0;
  21393. };
  21394. /**
  21395. * Returns null by default. Implemented by child classes
  21396. * @returns null
  21397. */
  21398. AbstractMesh.prototype.getIndices = function () {
  21399. return null;
  21400. };
  21401. /**
  21402. * Returns the array of the requested vertex data kind. Implemented by child classes
  21403. * @param kind defines the vertex data kind to use
  21404. * @returns null
  21405. */
  21406. AbstractMesh.prototype.getVerticesData = function (kind) {
  21407. return null;
  21408. };
  21409. /**
  21410. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21411. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21412. * Note that a new underlying VertexBuffer object is created each call.
  21413. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21414. * @param kind defines vertex data kind:
  21415. * * BABYLON.VertexBuffer.PositionKind
  21416. * * BABYLON.VertexBuffer.UVKind
  21417. * * BABYLON.VertexBuffer.UV2Kind
  21418. * * BABYLON.VertexBuffer.UV3Kind
  21419. * * BABYLON.VertexBuffer.UV4Kind
  21420. * * BABYLON.VertexBuffer.UV5Kind
  21421. * * BABYLON.VertexBuffer.UV6Kind
  21422. * * BABYLON.VertexBuffer.ColorKind
  21423. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21424. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21425. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21426. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21427. * @param data defines the data source
  21428. * @param updatable defines if the data must be flagged as updatable (or static)
  21429. * @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
  21430. * @returns the current mesh
  21431. */
  21432. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21433. return this;
  21434. };
  21435. /**
  21436. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21437. * If the mesh has no geometry, it is simply returned as it is.
  21438. * @param kind defines vertex data kind:
  21439. * * BABYLON.VertexBuffer.PositionKind
  21440. * * BABYLON.VertexBuffer.UVKind
  21441. * * BABYLON.VertexBuffer.UV2Kind
  21442. * * BABYLON.VertexBuffer.UV3Kind
  21443. * * BABYLON.VertexBuffer.UV4Kind
  21444. * * BABYLON.VertexBuffer.UV5Kind
  21445. * * BABYLON.VertexBuffer.UV6Kind
  21446. * * BABYLON.VertexBuffer.ColorKind
  21447. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21448. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21449. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21450. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21451. * @param data defines the data source
  21452. * @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
  21453. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  21454. * @returns the current mesh
  21455. */
  21456. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21457. return this;
  21458. };
  21459. /**
  21460. * Sets the mesh indices,
  21461. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21462. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  21463. * @param totalVertices Defines the total number of vertices
  21464. * @returns the current mesh
  21465. */
  21466. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  21467. return this;
  21468. };
  21469. /**
  21470. * Gets a boolean indicating if specific vertex data is present
  21471. * @param kind defines the vertex data kind to use
  21472. * @returns true is data kind is present
  21473. */
  21474. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  21475. return false;
  21476. };
  21477. /**
  21478. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  21479. * @returns a BoundingInfo
  21480. */
  21481. AbstractMesh.prototype.getBoundingInfo = function () {
  21482. if (this._masterMesh) {
  21483. return this._masterMesh.getBoundingInfo();
  21484. }
  21485. if (!this._boundingInfo) {
  21486. // this._boundingInfo is being created here
  21487. this._updateBoundingInfo();
  21488. }
  21489. // cannot be null.
  21490. return this._boundingInfo;
  21491. };
  21492. /**
  21493. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  21494. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  21495. * @returns the current mesh
  21496. */
  21497. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  21498. if (includeDescendants === void 0) { includeDescendants = true; }
  21499. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  21500. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  21501. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  21502. if (maxDimension === 0) {
  21503. return this;
  21504. }
  21505. var scale = 1 / maxDimension;
  21506. this.scaling.scaleInPlace(scale);
  21507. return this;
  21508. };
  21509. /**
  21510. * Overwrite the current bounding info
  21511. * @param boundingInfo defines the new bounding info
  21512. * @returns the current mesh
  21513. */
  21514. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21515. this._boundingInfo = boundingInfo;
  21516. return this;
  21517. };
  21518. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  21519. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  21520. get: function () {
  21521. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  21522. },
  21523. enumerable: true,
  21524. configurable: true
  21525. });
  21526. /** @hidden */
  21527. AbstractMesh.prototype._preActivate = function () {
  21528. };
  21529. /** @hidden */
  21530. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21531. };
  21532. /** @hidden */
  21533. AbstractMesh.prototype._activate = function (renderId) {
  21534. this._renderId = renderId;
  21535. };
  21536. /**
  21537. * Gets the current world matrix
  21538. * @returns a Matrix
  21539. */
  21540. AbstractMesh.prototype.getWorldMatrix = function () {
  21541. if (this._masterMesh) {
  21542. return this._masterMesh.getWorldMatrix();
  21543. }
  21544. return _super.prototype.getWorldMatrix.call(this);
  21545. };
  21546. /** @hidden */
  21547. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  21548. if (this._masterMesh) {
  21549. return this._masterMesh._getWorldMatrixDeterminant();
  21550. }
  21551. return _super.prototype._getWorldMatrixDeterminant.call(this);
  21552. };
  21553. // ================================== Point of View Movement =================================
  21554. /**
  21555. * Perform relative position change from the point of view of behind the front of the mesh.
  21556. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21557. * Supports definition of mesh facing forward or backward
  21558. * @param amountRight defines the distance on the right axis
  21559. * @param amountUp defines the distance on the up axis
  21560. * @param amountForward defines the distance on the forward axis
  21561. * @returns the current mesh
  21562. */
  21563. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  21564. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  21565. return this;
  21566. };
  21567. /**
  21568. * Calculate relative position change from the point of view of behind the front of the mesh.
  21569. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21570. * Supports definition of mesh facing forward or backward
  21571. * @param amountRight defines the distance on the right axis
  21572. * @param amountUp defines the distance on the up axis
  21573. * @param amountForward defines the distance on the forward axis
  21574. * @returns the new displacement vector
  21575. */
  21576. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  21577. var rotMatrix = new BABYLON.Matrix();
  21578. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  21579. rotQuaternion.toRotationMatrix(rotMatrix);
  21580. var translationDelta = BABYLON.Vector3.Zero();
  21581. var defForwardMult = this.definedFacingForward ? -1 : 1;
  21582. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  21583. return translationDelta;
  21584. };
  21585. // ================================== Point of View Rotation =================================
  21586. /**
  21587. * Perform relative rotation change from the point of view of behind the front of the mesh.
  21588. * Supports definition of mesh facing forward or backward
  21589. * @param flipBack defines the flip
  21590. * @param twirlClockwise defines the twirl
  21591. * @param tiltRight defines the tilt
  21592. * @returns the current mesh
  21593. */
  21594. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21595. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  21596. return this;
  21597. };
  21598. /**
  21599. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  21600. * Supports definition of mesh facing forward or backward.
  21601. * @param flipBack defines the flip
  21602. * @param twirlClockwise defines the twirl
  21603. * @param tiltRight defines the tilt
  21604. * @returns the new rotation vector
  21605. */
  21606. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21607. var defForwardMult = this.definedFacingForward ? 1 : -1;
  21608. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  21609. };
  21610. /**
  21611. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  21612. * @param includeDescendants Include bounding info from descendants as well (true by default)
  21613. * @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
  21614. * @returns the new bounding vectors
  21615. */
  21616. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  21617. if (includeDescendants === void 0) { includeDescendants = true; }
  21618. if (predicate === void 0) { predicate = null; }
  21619. // Ensures that all world matrix will be recomputed.
  21620. this.getScene().incrementRenderId();
  21621. this.computeWorldMatrix(true);
  21622. var min;
  21623. var max;
  21624. var boundingInfo = this.getBoundingInfo();
  21625. if (!this.subMeshes) {
  21626. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21627. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21628. }
  21629. else {
  21630. min = boundingInfo.boundingBox.minimumWorld;
  21631. max = boundingInfo.boundingBox.maximumWorld;
  21632. }
  21633. if (includeDescendants) {
  21634. var descendants = this.getDescendants(false);
  21635. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  21636. var descendant = descendants_1[_i];
  21637. var childMesh = descendant;
  21638. childMesh.computeWorldMatrix(true);
  21639. // Filters meshes based on custom predicate function.
  21640. if (predicate && !predicate(childMesh)) {
  21641. continue;
  21642. }
  21643. //make sure we have the needed params to get mix and max
  21644. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  21645. continue;
  21646. }
  21647. var childBoundingInfo = childMesh.getBoundingInfo();
  21648. var boundingBox = childBoundingInfo.boundingBox;
  21649. var minBox = boundingBox.minimumWorld;
  21650. var maxBox = boundingBox.maximumWorld;
  21651. BABYLON.Tools.CheckExtends(minBox, min, max);
  21652. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21653. }
  21654. }
  21655. return {
  21656. min: min,
  21657. max: max
  21658. };
  21659. };
  21660. /** @hidden */
  21661. AbstractMesh.prototype._updateBoundingInfo = function () {
  21662. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  21663. this._boundingInfo.update(this.worldMatrixFromCache);
  21664. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21665. return this;
  21666. };
  21667. /** @hidden */
  21668. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  21669. if (!this.subMeshes) {
  21670. return this;
  21671. }
  21672. var count = this.subMeshes.length;
  21673. for (var subIndex = 0; subIndex < count; subIndex++) {
  21674. var subMesh = this.subMeshes[subIndex];
  21675. if (count > 1 || !subMesh.IsGlobal) {
  21676. subMesh.updateBoundingInfo(matrix);
  21677. }
  21678. }
  21679. return this;
  21680. };
  21681. /** @hidden */
  21682. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  21683. // Bounding info
  21684. this._updateBoundingInfo();
  21685. };
  21686. /**
  21687. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  21688. * A mesh is in the frustum if its bounding box intersects the frustum
  21689. * @param frustumPlanes defines the frustum to test
  21690. * @returns true if the mesh is in the frustum planes
  21691. */
  21692. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  21693. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  21694. };
  21695. /**
  21696. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  21697. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  21698. * @param frustumPlanes defines the frustum to test
  21699. * @returns true if the mesh is completely in the frustum planes
  21700. */
  21701. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21702. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  21703. };
  21704. /**
  21705. * True if the mesh intersects another mesh or a SolidParticle object
  21706. * @param mesh defines a target mesh or SolidParticle to test
  21707. * @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)
  21708. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  21709. * @returns true if there is an intersection
  21710. */
  21711. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  21712. if (precise === void 0) { precise = false; }
  21713. if (!this._boundingInfo || !mesh._boundingInfo) {
  21714. return false;
  21715. }
  21716. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  21717. return true;
  21718. }
  21719. if (includeDescendants) {
  21720. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  21721. var child = _a[_i];
  21722. if (child.intersectsMesh(mesh, precise, true)) {
  21723. return true;
  21724. }
  21725. }
  21726. }
  21727. return false;
  21728. };
  21729. /**
  21730. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  21731. * @param point defines the point to test
  21732. * @returns true if there is an intersection
  21733. */
  21734. AbstractMesh.prototype.intersectsPoint = function (point) {
  21735. if (!this._boundingInfo) {
  21736. return false;
  21737. }
  21738. return this._boundingInfo.intersectsPoint(point);
  21739. };
  21740. /**
  21741. * Gets the position of the current mesh in camera space
  21742. * @param camera defines the camera to use
  21743. * @returns a position
  21744. */
  21745. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  21746. if (camera === void 0) { camera = null; }
  21747. if (!camera) {
  21748. camera = this.getScene().activeCamera;
  21749. }
  21750. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  21751. };
  21752. /**
  21753. * Returns the distance from the mesh to the active camera
  21754. * @param camera defines the camera to use
  21755. * @returns the distance
  21756. */
  21757. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  21758. if (camera === void 0) { camera = null; }
  21759. if (!camera) {
  21760. camera = this.getScene().activeCamera;
  21761. }
  21762. return this.absolutePosition.subtract(camera.position).length();
  21763. };
  21764. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  21765. // Collisions
  21766. /**
  21767. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  21768. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21769. */
  21770. get: function () {
  21771. return this._checkCollisions;
  21772. },
  21773. set: function (collisionEnabled) {
  21774. this._checkCollisions = collisionEnabled;
  21775. if (this.getScene().workerCollisions) {
  21776. this.getScene().collisionCoordinator.onMeshUpdated(this);
  21777. }
  21778. },
  21779. enumerable: true,
  21780. configurable: true
  21781. });
  21782. Object.defineProperty(AbstractMesh.prototype, "collider", {
  21783. /**
  21784. * Gets Collider object used to compute collisions (not physics)
  21785. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21786. */
  21787. get: function () {
  21788. return this._collider;
  21789. },
  21790. enumerable: true,
  21791. configurable: true
  21792. });
  21793. /**
  21794. * Move the mesh using collision engine
  21795. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21796. * @param displacement defines the requested displacement vector
  21797. * @returns the current mesh
  21798. */
  21799. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  21800. var globalPosition = this.getAbsolutePosition();
  21801. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  21802. if (!this._collider) {
  21803. this._collider = new BABYLON.Collider();
  21804. }
  21805. this._collider._radius = this.ellipsoid;
  21806. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  21807. return this;
  21808. };
  21809. // Collisions
  21810. /** @hidden */
  21811. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  21812. this._generatePointsArray();
  21813. if (!this._positions) {
  21814. return this;
  21815. }
  21816. // Transformation
  21817. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  21818. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  21819. subMesh._lastColliderWorldVertices = [];
  21820. subMesh._trianglePlanes = [];
  21821. var start = subMesh.verticesStart;
  21822. var end = (subMesh.verticesStart + subMesh.verticesCount);
  21823. for (var i = start; i < end; i++) {
  21824. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  21825. }
  21826. }
  21827. // Collide
  21828. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  21829. if (collider.collisionFound) {
  21830. collider.collidedMesh = this;
  21831. }
  21832. return this;
  21833. };
  21834. /** @hidden */
  21835. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  21836. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  21837. var len = subMeshes.length;
  21838. for (var index = 0; index < len; index++) {
  21839. var subMesh = subMeshes.data[index];
  21840. // Bounding test
  21841. if (len > 1 && !subMesh._checkCollision(collider)) {
  21842. continue;
  21843. }
  21844. this._collideForSubMesh(subMesh, transformMatrix, collider);
  21845. }
  21846. return this;
  21847. };
  21848. /** @hidden */
  21849. AbstractMesh.prototype._checkCollision = function (collider) {
  21850. // Bounding box test
  21851. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider)) {
  21852. return this;
  21853. }
  21854. // Transformation matrix
  21855. var collisionsScalingMatrix = BABYLON.Tmp.Matrix[0];
  21856. var collisionsTransformMatrix = BABYLON.Tmp.Matrix[1];
  21857. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, collisionsScalingMatrix);
  21858. this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix);
  21859. this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix);
  21860. return this;
  21861. };
  21862. // Picking
  21863. /** @hidden */
  21864. AbstractMesh.prototype._generatePointsArray = function () {
  21865. return false;
  21866. };
  21867. /**
  21868. * Checks if the passed Ray intersects with the mesh
  21869. * @param ray defines the ray to use
  21870. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  21871. * @returns the picking info
  21872. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  21873. */
  21874. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  21875. var pickingInfo = new BABYLON.PickingInfo();
  21876. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  21877. return pickingInfo;
  21878. }
  21879. if (!this._generatePointsArray()) {
  21880. return pickingInfo;
  21881. }
  21882. var intersectInfo = null;
  21883. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  21884. var len = subMeshes.length;
  21885. for (var index = 0; index < len; index++) {
  21886. var subMesh = subMeshes.data[index];
  21887. // Bounding test
  21888. if (len > 1 && !subMesh.canIntersects(ray)) {
  21889. continue;
  21890. }
  21891. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  21892. if (currentIntersectInfo) {
  21893. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21894. intersectInfo = currentIntersectInfo;
  21895. intersectInfo.subMeshId = index;
  21896. if (fastCheck) {
  21897. break;
  21898. }
  21899. }
  21900. }
  21901. }
  21902. if (intersectInfo) {
  21903. // Get picked point
  21904. var world = this.getWorldMatrix();
  21905. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  21906. var direction = ray.direction.clone();
  21907. direction = direction.scale(intersectInfo.distance);
  21908. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  21909. var pickedPoint = worldOrigin.add(worldDirection);
  21910. // Return result
  21911. pickingInfo.hit = true;
  21912. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  21913. pickingInfo.pickedPoint = pickedPoint;
  21914. pickingInfo.pickedMesh = this;
  21915. pickingInfo.bu = intersectInfo.bu || 0;
  21916. pickingInfo.bv = intersectInfo.bv || 0;
  21917. pickingInfo.faceId = intersectInfo.faceId;
  21918. pickingInfo.subMeshId = intersectInfo.subMeshId;
  21919. return pickingInfo;
  21920. }
  21921. return pickingInfo;
  21922. };
  21923. /**
  21924. * Clones the current mesh
  21925. * @param name defines the mesh name
  21926. * @param newParent defines the new mesh parent
  21927. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21928. * @returns the new mesh
  21929. */
  21930. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21931. return null;
  21932. };
  21933. /**
  21934. * Disposes all the submeshes of the current meshnp
  21935. * @returns the current mesh
  21936. */
  21937. AbstractMesh.prototype.releaseSubMeshes = function () {
  21938. if (this.subMeshes) {
  21939. while (this.subMeshes.length) {
  21940. this.subMeshes[0].dispose();
  21941. }
  21942. }
  21943. else {
  21944. this.subMeshes = new Array();
  21945. }
  21946. return this;
  21947. };
  21948. /**
  21949. * Releases resources associated with this abstract mesh.
  21950. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21951. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21952. */
  21953. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21954. var _this = this;
  21955. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21956. var index;
  21957. // Smart Array Retainers.
  21958. this.getScene().freeActiveMeshes();
  21959. this.getScene().freeRenderingGroups();
  21960. // Action manager
  21961. if (this.actionManager !== undefined && this.actionManager !== null) {
  21962. this.actionManager.dispose();
  21963. this.actionManager = null;
  21964. }
  21965. // Skeleton
  21966. this._skeleton = null;
  21967. // Intersections in progress
  21968. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21969. var other = this._intersectionsInProgress[index];
  21970. var pos = other._intersectionsInProgress.indexOf(this);
  21971. other._intersectionsInProgress.splice(pos, 1);
  21972. }
  21973. this._intersectionsInProgress = [];
  21974. // Lights
  21975. var lights = this.getScene().lights;
  21976. lights.forEach(function (light) {
  21977. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21978. if (meshIndex !== -1) {
  21979. light.includedOnlyMeshes.splice(meshIndex, 1);
  21980. }
  21981. meshIndex = light.excludedMeshes.indexOf(_this);
  21982. if (meshIndex !== -1) {
  21983. light.excludedMeshes.splice(meshIndex, 1);
  21984. }
  21985. // Shadow generators
  21986. var generator = light.getShadowGenerator();
  21987. if (generator) {
  21988. var shadowMap = generator.getShadowMap();
  21989. if (shadowMap && shadowMap.renderList) {
  21990. meshIndex = shadowMap.renderList.indexOf(_this);
  21991. if (meshIndex !== -1) {
  21992. shadowMap.renderList.splice(meshIndex, 1);
  21993. }
  21994. }
  21995. }
  21996. });
  21997. // SubMeshes
  21998. if (this.getClassName() !== "InstancedMesh") {
  21999. this.releaseSubMeshes();
  22000. }
  22001. // Query
  22002. var engine = this.getScene().getEngine();
  22003. if (this._occlusionQuery) {
  22004. this.isOcclusionQueryInProgress = false;
  22005. engine.deleteQuery(this._occlusionQuery);
  22006. this._occlusionQuery = null;
  22007. }
  22008. // Engine
  22009. engine.wipeCaches();
  22010. // Remove from scene
  22011. this.getScene().removeMesh(this);
  22012. if (disposeMaterialAndTextures) {
  22013. if (this.material) {
  22014. this.material.dispose(false, true);
  22015. }
  22016. }
  22017. if (!doNotRecurse) {
  22018. // Particles
  22019. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  22020. if (this.getScene().particleSystems[index].emitter === this) {
  22021. this.getScene().particleSystems[index].dispose();
  22022. index--;
  22023. }
  22024. }
  22025. }
  22026. // facet data
  22027. if (this._facetData.facetDataEnabled) {
  22028. this.disableFacetData();
  22029. }
  22030. this.onAfterWorldMatrixUpdateObservable.clear();
  22031. this.onCollideObservable.clear();
  22032. this.onCollisionPositionChangeObservable.clear();
  22033. this.onRebuildObservable.clear();
  22034. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22035. };
  22036. /**
  22037. * Adds the passed mesh as a child to the current mesh
  22038. * @param mesh defines the child mesh
  22039. * @returns the current mesh
  22040. */
  22041. AbstractMesh.prototype.addChild = function (mesh) {
  22042. mesh.setParent(this);
  22043. return this;
  22044. };
  22045. /**
  22046. * Removes the passed mesh from the current mesh children list
  22047. * @param mesh defines the child mesh
  22048. * @returns the current mesh
  22049. */
  22050. AbstractMesh.prototype.removeChild = function (mesh) {
  22051. mesh.setParent(null);
  22052. return this;
  22053. };
  22054. // Facet data
  22055. /** @hidden */
  22056. AbstractMesh.prototype._initFacetData = function () {
  22057. var data = this._facetData;
  22058. if (!data.facetNormals) {
  22059. data.facetNormals = new Array();
  22060. }
  22061. if (!data.facetPositions) {
  22062. data.facetPositions = new Array();
  22063. }
  22064. if (!data.facetPartitioning) {
  22065. data.facetPartitioning = new Array();
  22066. }
  22067. data.facetNb = (this.getIndices().length / 3) | 0;
  22068. data.partitioningSubdivisions = (data.partitioningSubdivisions) ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  22069. data.partitioningBBoxRatio = (data.partitioningBBoxRatio) ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  22070. for (var f = 0; f < data.facetNb; f++) {
  22071. data.facetNormals[f] = BABYLON.Vector3.Zero();
  22072. data.facetPositions[f] = BABYLON.Vector3.Zero();
  22073. }
  22074. data.facetDataEnabled = true;
  22075. return this;
  22076. };
  22077. /**
  22078. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  22079. * This method can be called within the render loop.
  22080. * 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
  22081. * @returns the current mesh
  22082. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22083. */
  22084. AbstractMesh.prototype.updateFacetData = function () {
  22085. var data = this._facetData;
  22086. if (!data.facetDataEnabled) {
  22087. this._initFacetData();
  22088. }
  22089. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22090. var indices = this.getIndices();
  22091. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22092. var bInfo = this.getBoundingInfo();
  22093. if (data.facetDepthSort && !data.facetDepthSortEnabled) {
  22094. // init arrays, matrix and sort function on first call
  22095. data.facetDepthSortEnabled = true;
  22096. if (indices instanceof Uint16Array) {
  22097. data.depthSortedIndices = new Uint16Array(indices);
  22098. }
  22099. else if (indices instanceof Uint32Array) {
  22100. data.depthSortedIndices = new Uint32Array(indices);
  22101. }
  22102. else {
  22103. var needs32bits = false;
  22104. for (var i = 0; i < indices.length; i++) {
  22105. if (indices[i] > 65535) {
  22106. needs32bits = true;
  22107. break;
  22108. }
  22109. }
  22110. if (needs32bits) {
  22111. data.depthSortedIndices = new Uint32Array(indices);
  22112. }
  22113. else {
  22114. data.depthSortedIndices = new Uint16Array(indices);
  22115. }
  22116. }
  22117. data.facetDepthSortFunction = function (f1, f2) {
  22118. return (f2.sqDistance - f1.sqDistance);
  22119. };
  22120. if (!data.facetDepthSortFrom) {
  22121. var camera = this.getScene().activeCamera;
  22122. data.facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  22123. }
  22124. data.depthSortedFacets = [];
  22125. for (var f = 0; f < data.facetNb; f++) {
  22126. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  22127. data.depthSortedFacets.push(depthSortedFacet);
  22128. }
  22129. data.invertedMatrix = BABYLON.Matrix.Identity();
  22130. data.facetDepthSortOrigin = BABYLON.Vector3.Zero();
  22131. }
  22132. data.bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  22133. data.bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  22134. data.bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  22135. var bbSizeMax = (data.bbSize.x > data.bbSize.y) ? data.bbSize.x : data.bbSize.y;
  22136. bbSizeMax = (bbSizeMax > data.bbSize.z) ? bbSizeMax : data.bbSize.z;
  22137. data.subDiv.max = data.partitioningSubdivisions;
  22138. data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  22139. data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); // according to each bbox size per axis
  22140. data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
  22141. data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
  22142. data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
  22143. data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
  22144. // set the parameters for ComputeNormals()
  22145. data.facetParameters.facetNormals = this.getFacetLocalNormals();
  22146. data.facetParameters.facetPositions = this.getFacetLocalPositions();
  22147. data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  22148. data.facetParameters.bInfo = bInfo;
  22149. data.facetParameters.bbSize = data.bbSize;
  22150. data.facetParameters.subDiv = data.subDiv;
  22151. data.facetParameters.ratio = this.partitioningBBoxRatio;
  22152. data.facetParameters.depthSort = data.facetDepthSort;
  22153. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22154. this.computeWorldMatrix(true);
  22155. this._worldMatrix.invertToRef(data.invertedMatrix);
  22156. BABYLON.Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
  22157. data.facetParameters.distanceTo = data.facetDepthSortOrigin;
  22158. }
  22159. data.facetParameters.depthSortedFacets = data.depthSortedFacets;
  22160. BABYLON.VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
  22161. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22162. data.depthSortedFacets.sort(data.facetDepthSortFunction);
  22163. var l = (data.depthSortedIndices.length / 3) | 0;
  22164. for (var f = 0; f < l; f++) {
  22165. var sind = data.depthSortedFacets[f].ind;
  22166. data.depthSortedIndices[f * 3] = indices[sind];
  22167. data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  22168. data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  22169. }
  22170. this.updateIndices(data.depthSortedIndices);
  22171. }
  22172. return this;
  22173. };
  22174. /**
  22175. * Returns the facetLocalNormals array.
  22176. * The normals are expressed in the mesh local spac
  22177. * @returns an array of Vector3
  22178. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22179. */
  22180. AbstractMesh.prototype.getFacetLocalNormals = function () {
  22181. if (!this._facetData.facetNormals) {
  22182. this.updateFacetData();
  22183. }
  22184. return this._facetData.facetNormals;
  22185. };
  22186. /**
  22187. * Returns the facetLocalPositions array.
  22188. * The facet positions are expressed in the mesh local space
  22189. * @returns an array of Vector3
  22190. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22191. */
  22192. AbstractMesh.prototype.getFacetLocalPositions = function () {
  22193. if (!this._facetData.facetPositions) {
  22194. this.updateFacetData();
  22195. }
  22196. return this._facetData.facetPositions;
  22197. };
  22198. /**
  22199. * Returns the facetLocalPartioning array
  22200. * @returns an array of array of numbers
  22201. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22202. */
  22203. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  22204. if (!this._facetData.facetPartitioning) {
  22205. this.updateFacetData();
  22206. }
  22207. return this._facetData.facetPartitioning;
  22208. };
  22209. /**
  22210. * Returns the i-th facet position in the world system.
  22211. * This method allocates a new Vector3 per call
  22212. * @param i defines the facet index
  22213. * @returns a new Vector3
  22214. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22215. */
  22216. AbstractMesh.prototype.getFacetPosition = function (i) {
  22217. var pos = BABYLON.Vector3.Zero();
  22218. this.getFacetPositionToRef(i, pos);
  22219. return pos;
  22220. };
  22221. /**
  22222. * Sets the reference Vector3 with the i-th facet position in the world system
  22223. * @param i defines the facet index
  22224. * @param ref defines the target vector
  22225. * @returns the current mesh
  22226. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22227. */
  22228. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  22229. var localPos = (this.getFacetLocalPositions())[i];
  22230. var world = this.getWorldMatrix();
  22231. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  22232. return this;
  22233. };
  22234. /**
  22235. * Returns the i-th facet normal in the world system.
  22236. * This method allocates a new Vector3 per call
  22237. * @param i defines the facet index
  22238. * @returns a new Vector3
  22239. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22240. */
  22241. AbstractMesh.prototype.getFacetNormal = function (i) {
  22242. var norm = BABYLON.Vector3.Zero();
  22243. this.getFacetNormalToRef(i, norm);
  22244. return norm;
  22245. };
  22246. /**
  22247. * Sets the reference Vector3 with the i-th facet normal in the world system
  22248. * @param i defines the facet index
  22249. * @param ref defines the target vector
  22250. * @returns the current mesh
  22251. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22252. */
  22253. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  22254. var localNorm = (this.getFacetLocalNormals())[i];
  22255. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  22256. return this;
  22257. };
  22258. /**
  22259. * 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)
  22260. * @param x defines x coordinate
  22261. * @param y defines y coordinate
  22262. * @param z defines z coordinate
  22263. * @returns the array of facet indexes
  22264. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22265. */
  22266. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  22267. var bInfo = this.getBoundingInfo();
  22268. var data = this._facetData;
  22269. var ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
  22270. var oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
  22271. var oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
  22272. if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
  22273. return null;
  22274. }
  22275. return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
  22276. };
  22277. /**
  22278. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  22279. * @param projected sets as the (x,y,z) world projection on the facet
  22280. * @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
  22281. * @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
  22282. * @param x defines x coordinate
  22283. * @param y defines y coordinate
  22284. * @param z defines z coordinate
  22285. * @returns the face index if found (or null instead)
  22286. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22287. */
  22288. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  22289. if (checkFace === void 0) { checkFace = false; }
  22290. if (facing === void 0) { facing = true; }
  22291. var world = this.getWorldMatrix();
  22292. var invMat = BABYLON.Tmp.Matrix[5];
  22293. world.invertToRef(invMat);
  22294. var invVect = BABYLON.Tmp.Vector3[8];
  22295. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  22296. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  22297. if (projected) {
  22298. // tranform the local computed projected vector to world coordinates
  22299. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  22300. }
  22301. return closest;
  22302. };
  22303. /**
  22304. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  22305. * @param projected sets as the (x,y,z) local projection on the facet
  22306. * @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
  22307. * @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
  22308. * @param x defines x coordinate
  22309. * @param y defines y coordinate
  22310. * @param z defines z coordinate
  22311. * @returns the face index if found (or null instead)
  22312. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22313. */
  22314. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  22315. if (checkFace === void 0) { checkFace = false; }
  22316. if (facing === void 0) { facing = true; }
  22317. var closest = null;
  22318. var tmpx = 0.0;
  22319. var tmpy = 0.0;
  22320. var tmpz = 0.0;
  22321. var d = 0.0; // tmp dot facet normal * facet position
  22322. var t0 = 0.0;
  22323. var projx = 0.0;
  22324. var projy = 0.0;
  22325. var projz = 0.0;
  22326. // Get all the facets in the same partitioning block than (x, y, z)
  22327. var facetPositions = this.getFacetLocalPositions();
  22328. var facetNormals = this.getFacetLocalNormals();
  22329. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  22330. if (!facetsInBlock) {
  22331. return null;
  22332. }
  22333. // Get the closest facet to (x, y, z)
  22334. var shortest = Number.MAX_VALUE; // init distance vars
  22335. var tmpDistance = shortest;
  22336. var fib; // current facet in the block
  22337. var norm; // current facet normal
  22338. var p0; // current facet barycenter position
  22339. // loop on all the facets in the current partitioning block
  22340. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  22341. fib = facetsInBlock[idx];
  22342. norm = facetNormals[fib];
  22343. p0 = facetPositions[fib];
  22344. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  22345. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  22346. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  22347. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  22348. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  22349. projx = x + norm.x * t0;
  22350. projy = y + norm.y * t0;
  22351. projz = z + norm.z * t0;
  22352. tmpx = projx - x;
  22353. tmpy = projy - y;
  22354. tmpz = projz - z;
  22355. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  22356. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  22357. shortest = tmpDistance;
  22358. closest = fib;
  22359. if (projected) {
  22360. projected.x = projx;
  22361. projected.y = projy;
  22362. projected.z = projz;
  22363. }
  22364. }
  22365. }
  22366. }
  22367. return closest;
  22368. };
  22369. /**
  22370. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  22371. * @returns the parameters
  22372. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22373. */
  22374. AbstractMesh.prototype.getFacetDataParameters = function () {
  22375. return this._facetData.facetParameters;
  22376. };
  22377. /**
  22378. * Disables the feature FacetData and frees the related memory
  22379. * @returns the current mesh
  22380. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22381. */
  22382. AbstractMesh.prototype.disableFacetData = function () {
  22383. if (this._facetData.facetDataEnabled) {
  22384. this._facetData.facetDataEnabled = false;
  22385. this._facetData.facetPositions = new Array();
  22386. this._facetData.facetNormals = new Array();
  22387. this._facetData.facetPartitioning = new Array();
  22388. this._facetData.facetParameters = null;
  22389. this._facetData.depthSortedIndices = new Uint32Array(0);
  22390. }
  22391. return this;
  22392. };
  22393. /**
  22394. * Updates the AbstractMesh indices array
  22395. * @param indices defines the data source
  22396. * @returns the current mesh
  22397. */
  22398. AbstractMesh.prototype.updateIndices = function (indices) {
  22399. return this;
  22400. };
  22401. /**
  22402. * Creates new normals data for the mesh
  22403. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  22404. * @returns the current mesh
  22405. */
  22406. AbstractMesh.prototype.createNormals = function (updatable) {
  22407. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22408. var indices = this.getIndices();
  22409. var normals;
  22410. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22411. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22412. }
  22413. else {
  22414. normals = [];
  22415. }
  22416. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  22417. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  22418. return this;
  22419. };
  22420. /**
  22421. * Align the mesh with a normal
  22422. * @param normal defines the normal to use
  22423. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  22424. * @returns the current mesh
  22425. */
  22426. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  22427. if (!upDirection) {
  22428. upDirection = BABYLON.Axis.Y;
  22429. }
  22430. var axisX = BABYLON.Tmp.Vector3[0];
  22431. var axisZ = BABYLON.Tmp.Vector3[1];
  22432. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  22433. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  22434. if (this.rotationQuaternion) {
  22435. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  22436. }
  22437. else {
  22438. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  22439. }
  22440. return this;
  22441. };
  22442. /** @hidden */
  22443. AbstractMesh.prototype._checkOcclusionQuery = function () {
  22444. return false;
  22445. };
  22446. /** No occlusion */
  22447. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  22448. /** Occlusion set to optimisitic */
  22449. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  22450. /** Occlusion set to strict */
  22451. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  22452. /** Use an accurante occlusion algorithm */
  22453. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  22454. /** Use a conservative occlusion algorithm */
  22455. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  22456. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  22457. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  22458. /** Culling strategy with bounding sphere only and then frustum culling */
  22459. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  22460. return AbstractMesh;
  22461. }(BABYLON.TransformNode));
  22462. BABYLON.AbstractMesh = AbstractMesh;
  22463. })(BABYLON || (BABYLON = {}));
  22464. //# sourceMappingURL=babylon.abstractMesh.js.map
  22465. var BABYLON;
  22466. (function (BABYLON) {
  22467. /**
  22468. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  22469. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  22470. * 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.
  22471. */
  22472. var Light = /** @class */ (function (_super) {
  22473. __extends(Light, _super);
  22474. /**
  22475. * Creates a Light object in the scene.
  22476. * Documentation : http://doc.babylonjs.com/tutorials/lights
  22477. * @param name The firendly name of the light
  22478. * @param scene The scene the light belongs too
  22479. */
  22480. function Light(name, scene) {
  22481. var _this = _super.call(this, name, scene) || this;
  22482. /**
  22483. * Diffuse gives the basic color to an object.
  22484. */
  22485. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  22486. /**
  22487. * Specular produces a highlight color on an object.
  22488. * Note: This is note affecting PBR materials.
  22489. */
  22490. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  22491. /**
  22492. * Defines the falloff type for this light. This lets overrriding how punctual light are
  22493. * falling off base on range or angle.
  22494. * This can be set to any values in Light.FALLOFF_x.
  22495. *
  22496. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  22497. * other types of materials.
  22498. */
  22499. _this.falloffType = Light.FALLOFF_DEFAULT;
  22500. /**
  22501. * Strength of the light.
  22502. * Note: By default it is define in the framework own unit.
  22503. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  22504. */
  22505. _this.intensity = 1.0;
  22506. _this._range = Number.MAX_VALUE;
  22507. _this._inverseSquaredRange = 0;
  22508. /**
  22509. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  22510. * of light.
  22511. */
  22512. _this._photometricScale = 1.0;
  22513. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  22514. _this._radius = 0.00001;
  22515. /**
  22516. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  22517. * exceeding the number allowed of the materials.
  22518. */
  22519. _this.renderPriority = 0;
  22520. _this._shadowEnabled = true;
  22521. _this._excludeWithLayerMask = 0;
  22522. _this._includeOnlyWithLayerMask = 0;
  22523. _this._lightmapMode = 0;
  22524. /**
  22525. * @hidden Internal use only.
  22526. */
  22527. _this._excludedMeshesIds = new Array();
  22528. /**
  22529. * @hidden Internal use only.
  22530. */
  22531. _this._includedOnlyMeshesIds = new Array();
  22532. _this.getScene().addLight(_this);
  22533. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  22534. _this._buildUniformLayout();
  22535. _this.includedOnlyMeshes = new Array();
  22536. _this.excludedMeshes = new Array();
  22537. _this._resyncMeshes();
  22538. return _this;
  22539. }
  22540. Object.defineProperty(Light.prototype, "range", {
  22541. /**
  22542. * Defines how far from the source the light is impacting in scene units.
  22543. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22544. */
  22545. get: function () {
  22546. return this._range;
  22547. },
  22548. /**
  22549. * Defines how far from the source the light is impacting in scene units.
  22550. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22551. */
  22552. set: function (value) {
  22553. this._range = value;
  22554. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  22555. },
  22556. enumerable: true,
  22557. configurable: true
  22558. });
  22559. Object.defineProperty(Light.prototype, "intensityMode", {
  22560. /**
  22561. * Gets the photometric scale used to interpret the intensity.
  22562. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22563. */
  22564. get: function () {
  22565. return this._intensityMode;
  22566. },
  22567. /**
  22568. * Sets the photometric scale used to interpret the intensity.
  22569. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22570. */
  22571. set: function (value) {
  22572. this._intensityMode = value;
  22573. this._computePhotometricScale();
  22574. },
  22575. enumerable: true,
  22576. configurable: true
  22577. });
  22578. Object.defineProperty(Light.prototype, "radius", {
  22579. /**
  22580. * Gets the light radius used by PBR Materials to simulate soft area lights.
  22581. */
  22582. get: function () {
  22583. return this._radius;
  22584. },
  22585. /**
  22586. * sets the light radius used by PBR Materials to simulate soft area lights.
  22587. */
  22588. set: function (value) {
  22589. this._radius = value;
  22590. this._computePhotometricScale();
  22591. },
  22592. enumerable: true,
  22593. configurable: true
  22594. });
  22595. Object.defineProperty(Light.prototype, "shadowEnabled", {
  22596. /**
  22597. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22598. * the current shadow generator.
  22599. */
  22600. get: function () {
  22601. return this._shadowEnabled;
  22602. },
  22603. /**
  22604. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22605. * the current shadow generator.
  22606. */
  22607. set: function (value) {
  22608. if (this._shadowEnabled === value) {
  22609. return;
  22610. }
  22611. this._shadowEnabled = value;
  22612. this._markMeshesAsLightDirty();
  22613. },
  22614. enumerable: true,
  22615. configurable: true
  22616. });
  22617. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  22618. /**
  22619. * Gets the only meshes impacted by this light.
  22620. */
  22621. get: function () {
  22622. return this._includedOnlyMeshes;
  22623. },
  22624. /**
  22625. * Sets the only meshes impacted by this light.
  22626. */
  22627. set: function (value) {
  22628. this._includedOnlyMeshes = value;
  22629. this._hookArrayForIncludedOnly(value);
  22630. },
  22631. enumerable: true,
  22632. configurable: true
  22633. });
  22634. Object.defineProperty(Light.prototype, "excludedMeshes", {
  22635. /**
  22636. * Gets the meshes not impacted by this light.
  22637. */
  22638. get: function () {
  22639. return this._excludedMeshes;
  22640. },
  22641. /**
  22642. * Sets the meshes not impacted by this light.
  22643. */
  22644. set: function (value) {
  22645. this._excludedMeshes = value;
  22646. this._hookArrayForExcluded(value);
  22647. },
  22648. enumerable: true,
  22649. configurable: true
  22650. });
  22651. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  22652. /**
  22653. * Gets the layer id use to find what meshes are not impacted by the light.
  22654. * Inactive if 0
  22655. */
  22656. get: function () {
  22657. return this._excludeWithLayerMask;
  22658. },
  22659. /**
  22660. * Sets the layer id use to find what meshes are not impacted by the light.
  22661. * Inactive if 0
  22662. */
  22663. set: function (value) {
  22664. this._excludeWithLayerMask = value;
  22665. this._resyncMeshes();
  22666. },
  22667. enumerable: true,
  22668. configurable: true
  22669. });
  22670. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  22671. /**
  22672. * Gets the layer id use to find what meshes are impacted by the light.
  22673. * Inactive if 0
  22674. */
  22675. get: function () {
  22676. return this._includeOnlyWithLayerMask;
  22677. },
  22678. /**
  22679. * Sets the layer id use to find what meshes are impacted by the light.
  22680. * Inactive if 0
  22681. */
  22682. set: function (value) {
  22683. this._includeOnlyWithLayerMask = value;
  22684. this._resyncMeshes();
  22685. },
  22686. enumerable: true,
  22687. configurable: true
  22688. });
  22689. Object.defineProperty(Light.prototype, "lightmapMode", {
  22690. /**
  22691. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22692. */
  22693. get: function () {
  22694. return this._lightmapMode;
  22695. },
  22696. /**
  22697. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22698. */
  22699. set: function (value) {
  22700. if (this._lightmapMode === value) {
  22701. return;
  22702. }
  22703. this._lightmapMode = value;
  22704. this._markMeshesAsLightDirty();
  22705. },
  22706. enumerable: true,
  22707. configurable: true
  22708. });
  22709. /**
  22710. * Returns the string "Light".
  22711. * @returns the class name
  22712. */
  22713. Light.prototype.getClassName = function () {
  22714. return "Light";
  22715. };
  22716. /**
  22717. * Converts the light information to a readable string for debug purpose.
  22718. * @param fullDetails Supports for multiple levels of logging within scene loading
  22719. * @returns the human readable light info
  22720. */
  22721. Light.prototype.toString = function (fullDetails) {
  22722. var ret = "Name: " + this.name;
  22723. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  22724. if (this.animations) {
  22725. for (var i = 0; i < this.animations.length; i++) {
  22726. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22727. }
  22728. }
  22729. if (fullDetails) {
  22730. }
  22731. return ret;
  22732. };
  22733. /** @hidden */
  22734. Light.prototype._syncParentEnabledState = function () {
  22735. _super.prototype._syncParentEnabledState.call(this);
  22736. this._resyncMeshes();
  22737. };
  22738. /**
  22739. * Set the enabled state of this node.
  22740. * @param value - the new enabled state
  22741. */
  22742. Light.prototype.setEnabled = function (value) {
  22743. _super.prototype.setEnabled.call(this, value);
  22744. this._resyncMeshes();
  22745. };
  22746. /**
  22747. * Returns the Light associated shadow generator if any.
  22748. * @return the associated shadow generator.
  22749. */
  22750. Light.prototype.getShadowGenerator = function () {
  22751. return this._shadowGenerator;
  22752. };
  22753. /**
  22754. * Returns a Vector3, the absolute light position in the World.
  22755. * @returns the world space position of the light
  22756. */
  22757. Light.prototype.getAbsolutePosition = function () {
  22758. return BABYLON.Vector3.Zero();
  22759. };
  22760. /**
  22761. * Specifies if the light will affect the passed mesh.
  22762. * @param mesh The mesh to test against the light
  22763. * @return true the mesh is affected otherwise, false.
  22764. */
  22765. Light.prototype.canAffectMesh = function (mesh) {
  22766. if (!mesh) {
  22767. return true;
  22768. }
  22769. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22770. return false;
  22771. }
  22772. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22773. return false;
  22774. }
  22775. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22776. return false;
  22777. }
  22778. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22779. return false;
  22780. }
  22781. return true;
  22782. };
  22783. /**
  22784. * Sort function to order lights for rendering.
  22785. * @param a First Light object to compare to second.
  22786. * @param b Second Light object to compare first.
  22787. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22788. */
  22789. Light.CompareLightsPriority = function (a, b) {
  22790. //shadow-casting lights have priority over non-shadow-casting lights
  22791. //the renderPrioirty is a secondary sort criterion
  22792. if (a.shadowEnabled !== b.shadowEnabled) {
  22793. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22794. }
  22795. return b.renderPriority - a.renderPriority;
  22796. };
  22797. /**
  22798. * Releases resources associated with this node.
  22799. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22800. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22801. */
  22802. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22803. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22804. if (this._shadowGenerator) {
  22805. this._shadowGenerator.dispose();
  22806. this._shadowGenerator = null;
  22807. }
  22808. // Animations
  22809. this.getScene().stopAnimation(this);
  22810. // Remove from meshes
  22811. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22812. var mesh = _a[_i];
  22813. mesh._removeLightSource(this);
  22814. }
  22815. this._uniformBuffer.dispose();
  22816. // Remove from scene
  22817. this.getScene().removeLight(this);
  22818. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22819. };
  22820. /**
  22821. * Returns the light type ID (integer).
  22822. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22823. */
  22824. Light.prototype.getTypeID = function () {
  22825. return 0;
  22826. };
  22827. /**
  22828. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22829. * @returns the scaled intensity in intensity mode unit
  22830. */
  22831. Light.prototype.getScaledIntensity = function () {
  22832. return this._photometricScale * this.intensity;
  22833. };
  22834. /**
  22835. * Returns a new Light object, named "name", from the current one.
  22836. * @param name The name of the cloned light
  22837. * @returns the new created light
  22838. */
  22839. Light.prototype.clone = function (name) {
  22840. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22841. if (!constructor) {
  22842. return null;
  22843. }
  22844. return BABYLON.SerializationHelper.Clone(constructor, this);
  22845. };
  22846. /**
  22847. * Serializes the current light into a Serialization object.
  22848. * @returns the serialized object.
  22849. */
  22850. Light.prototype.serialize = function () {
  22851. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22852. // Type
  22853. serializationObject.type = this.getTypeID();
  22854. // Parent
  22855. if (this.parent) {
  22856. serializationObject.parentId = this.parent.id;
  22857. }
  22858. // Inclusion / exclusions
  22859. if (this.excludedMeshes.length > 0) {
  22860. serializationObject.excludedMeshesIds = [];
  22861. this.excludedMeshes.forEach(function (mesh) {
  22862. serializationObject.excludedMeshesIds.push(mesh.id);
  22863. });
  22864. }
  22865. if (this.includedOnlyMeshes.length > 0) {
  22866. serializationObject.includedOnlyMeshesIds = [];
  22867. this.includedOnlyMeshes.forEach(function (mesh) {
  22868. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22869. });
  22870. }
  22871. // Animations
  22872. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22873. serializationObject.ranges = this.serializeAnimationRanges();
  22874. return serializationObject;
  22875. };
  22876. /**
  22877. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22878. * This new light is named "name" and added to the passed scene.
  22879. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22880. * @param name The friendly name of the light
  22881. * @param scene The scene the new light will belong to
  22882. * @returns the constructor function
  22883. */
  22884. Light.GetConstructorFromName = function (type, name, scene) {
  22885. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  22886. if (constructorFunc) {
  22887. return constructorFunc;
  22888. }
  22889. // Default to no light for none present once.
  22890. return null;
  22891. };
  22892. /**
  22893. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22894. * @param parsedLight The JSON representation of the light
  22895. * @param scene The scene to create the parsed light in
  22896. * @returns the created light after parsing
  22897. */
  22898. Light.Parse = function (parsedLight, scene) {
  22899. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22900. if (!constructor) {
  22901. return null;
  22902. }
  22903. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22904. // Inclusion / exclusions
  22905. if (parsedLight.excludedMeshesIds) {
  22906. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22907. }
  22908. if (parsedLight.includedOnlyMeshesIds) {
  22909. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22910. }
  22911. // Parent
  22912. if (parsedLight.parentId) {
  22913. light._waitingParentId = parsedLight.parentId;
  22914. }
  22915. // Animations
  22916. if (parsedLight.animations) {
  22917. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22918. var parsedAnimation = parsedLight.animations[animationIndex];
  22919. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22920. }
  22921. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22922. }
  22923. if (parsedLight.autoAnimate) {
  22924. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22925. }
  22926. return light;
  22927. };
  22928. Light.prototype._hookArrayForExcluded = function (array) {
  22929. var _this = this;
  22930. var oldPush = array.push;
  22931. array.push = function () {
  22932. var items = [];
  22933. for (var _i = 0; _i < arguments.length; _i++) {
  22934. items[_i] = arguments[_i];
  22935. }
  22936. var result = oldPush.apply(array, items);
  22937. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22938. var item = items_1[_a];
  22939. item._resyncLighSource(_this);
  22940. }
  22941. return result;
  22942. };
  22943. var oldSplice = array.splice;
  22944. array.splice = function (index, deleteCount) {
  22945. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22946. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22947. var item = deleted_1[_i];
  22948. item._resyncLighSource(_this);
  22949. }
  22950. return deleted;
  22951. };
  22952. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22953. var item = array_1[_i];
  22954. item._resyncLighSource(this);
  22955. }
  22956. };
  22957. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22958. var _this = this;
  22959. var oldPush = array.push;
  22960. array.push = function () {
  22961. var items = [];
  22962. for (var _i = 0; _i < arguments.length; _i++) {
  22963. items[_i] = arguments[_i];
  22964. }
  22965. var result = oldPush.apply(array, items);
  22966. _this._resyncMeshes();
  22967. return result;
  22968. };
  22969. var oldSplice = array.splice;
  22970. array.splice = function (index, deleteCount) {
  22971. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22972. _this._resyncMeshes();
  22973. return deleted;
  22974. };
  22975. this._resyncMeshes();
  22976. };
  22977. Light.prototype._resyncMeshes = function () {
  22978. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22979. var mesh = _a[_i];
  22980. mesh._resyncLighSource(this);
  22981. }
  22982. };
  22983. /**
  22984. * Forces the meshes to update their light related information in their rendering used effects
  22985. * @hidden Internal Use Only
  22986. */
  22987. Light.prototype._markMeshesAsLightDirty = function () {
  22988. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22989. var mesh = _a[_i];
  22990. if (mesh._lightSources.indexOf(this) !== -1) {
  22991. mesh._markSubMeshesAsLightDirty();
  22992. }
  22993. }
  22994. };
  22995. /**
  22996. * Recomputes the cached photometric scale if needed.
  22997. */
  22998. Light.prototype._computePhotometricScale = function () {
  22999. this._photometricScale = this._getPhotometricScale();
  23000. this.getScene().resetCachedMaterial();
  23001. };
  23002. /**
  23003. * Returns the Photometric Scale according to the light type and intensity mode.
  23004. */
  23005. Light.prototype._getPhotometricScale = function () {
  23006. var photometricScale = 0.0;
  23007. var lightTypeID = this.getTypeID();
  23008. //get photometric mode
  23009. var photometricMode = this.intensityMode;
  23010. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  23011. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  23012. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  23013. }
  23014. else {
  23015. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  23016. }
  23017. }
  23018. //compute photometric scale
  23019. switch (lightTypeID) {
  23020. case Light.LIGHTTYPEID_POINTLIGHT:
  23021. case Light.LIGHTTYPEID_SPOTLIGHT:
  23022. switch (photometricMode) {
  23023. case Light.INTENSITYMODE_LUMINOUSPOWER:
  23024. photometricScale = 1.0 / (4.0 * Math.PI);
  23025. break;
  23026. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  23027. photometricScale = 1.0;
  23028. break;
  23029. case Light.INTENSITYMODE_LUMINANCE:
  23030. photometricScale = this.radius * this.radius;
  23031. break;
  23032. }
  23033. break;
  23034. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  23035. switch (photometricMode) {
  23036. case Light.INTENSITYMODE_ILLUMINANCE:
  23037. photometricScale = 1.0;
  23038. break;
  23039. case Light.INTENSITYMODE_LUMINANCE:
  23040. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  23041. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  23042. var apexAngleRadians = this.radius;
  23043. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  23044. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  23045. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  23046. photometricScale = solidAngle;
  23047. break;
  23048. }
  23049. break;
  23050. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  23051. // No fall off in hemisperic light.
  23052. photometricScale = 1.0;
  23053. break;
  23054. }
  23055. return photometricScale;
  23056. };
  23057. /**
  23058. * Reorder the light in the scene according to their defined priority.
  23059. * @hidden Internal Use Only
  23060. */
  23061. Light.prototype._reorderLightsInScene = function () {
  23062. var scene = this.getScene();
  23063. if (this._renderPriority != 0) {
  23064. scene.requireLightSorting = true;
  23065. }
  23066. this.getScene().sortLightsByPriority();
  23067. };
  23068. /**
  23069. * Falloff Default: light is falling off following the material specification:
  23070. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  23071. */
  23072. Light.FALLOFF_DEFAULT = 0;
  23073. /**
  23074. * Falloff Physical: light is falling off following the inverse squared distance law.
  23075. */
  23076. Light.FALLOFF_PHYSICAL = 1;
  23077. /**
  23078. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  23079. * to enhance interoperability with other engines.
  23080. */
  23081. Light.FALLOFF_GLTF = 2;
  23082. /**
  23083. * Falloff Standard: light is falling off like in the standard material
  23084. * to enhance interoperability with other materials.
  23085. */
  23086. Light.FALLOFF_STANDARD = 3;
  23087. //lightmapMode Consts
  23088. /**
  23089. * If every light affecting the material is in this lightmapMode,
  23090. * material.lightmapTexture adds or multiplies
  23091. * (depends on material.useLightmapAsShadowmap)
  23092. * after every other light calculations.
  23093. */
  23094. Light.LIGHTMAP_DEFAULT = 0;
  23095. /**
  23096. * material.lightmapTexture as only diffuse lighting from this light
  23097. * adds only specular lighting from this light
  23098. * adds dynamic shadows
  23099. */
  23100. Light.LIGHTMAP_SPECULAR = 1;
  23101. /**
  23102. * material.lightmapTexture as only lighting
  23103. * no light calculation from this light
  23104. * only adds dynamic shadows from this light
  23105. */
  23106. Light.LIGHTMAP_SHADOWSONLY = 2;
  23107. // Intensity Mode Consts
  23108. /**
  23109. * Each light type uses the default quantity according to its type:
  23110. * point/spot lights use luminous intensity
  23111. * directional lights use illuminance
  23112. */
  23113. Light.INTENSITYMODE_AUTOMATIC = 0;
  23114. /**
  23115. * lumen (lm)
  23116. */
  23117. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  23118. /**
  23119. * candela (lm/sr)
  23120. */
  23121. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  23122. /**
  23123. * lux (lm/m^2)
  23124. */
  23125. Light.INTENSITYMODE_ILLUMINANCE = 3;
  23126. /**
  23127. * nit (cd/m^2)
  23128. */
  23129. Light.INTENSITYMODE_LUMINANCE = 4;
  23130. // Light types ids const.
  23131. /**
  23132. * Light type const id of the point light.
  23133. */
  23134. Light.LIGHTTYPEID_POINTLIGHT = 0;
  23135. /**
  23136. * Light type const id of the directional light.
  23137. */
  23138. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  23139. /**
  23140. * Light type const id of the spot light.
  23141. */
  23142. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  23143. /**
  23144. * Light type const id of the hemispheric light.
  23145. */
  23146. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  23147. __decorate([
  23148. BABYLON.serializeAsColor3()
  23149. ], Light.prototype, "diffuse", void 0);
  23150. __decorate([
  23151. BABYLON.serializeAsColor3()
  23152. ], Light.prototype, "specular", void 0);
  23153. __decorate([
  23154. BABYLON.serialize()
  23155. ], Light.prototype, "falloffType", void 0);
  23156. __decorate([
  23157. BABYLON.serialize()
  23158. ], Light.prototype, "intensity", void 0);
  23159. __decorate([
  23160. BABYLON.serialize()
  23161. ], Light.prototype, "range", null);
  23162. __decorate([
  23163. BABYLON.serialize()
  23164. ], Light.prototype, "intensityMode", null);
  23165. __decorate([
  23166. BABYLON.serialize()
  23167. ], Light.prototype, "radius", null);
  23168. __decorate([
  23169. BABYLON.serialize()
  23170. ], Light.prototype, "_renderPriority", void 0);
  23171. __decorate([
  23172. BABYLON.expandToProperty("_reorderLightsInScene")
  23173. ], Light.prototype, "renderPriority", void 0);
  23174. __decorate([
  23175. BABYLON.serialize("shadowEnabled")
  23176. ], Light.prototype, "_shadowEnabled", void 0);
  23177. __decorate([
  23178. BABYLON.serialize("excludeWithLayerMask")
  23179. ], Light.prototype, "_excludeWithLayerMask", void 0);
  23180. __decorate([
  23181. BABYLON.serialize("includeOnlyWithLayerMask")
  23182. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  23183. __decorate([
  23184. BABYLON.serialize("lightmapMode")
  23185. ], Light.prototype, "_lightmapMode", void 0);
  23186. return Light;
  23187. }(BABYLON.Node));
  23188. BABYLON.Light = Light;
  23189. })(BABYLON || (BABYLON = {}));
  23190. //# sourceMappingURL=babylon.light.js.map
  23191. var BABYLON;
  23192. (function (BABYLON) {
  23193. /**
  23194. * This is the base class of all the camera used in the application.
  23195. * @see http://doc.babylonjs.com/features/cameras
  23196. */
  23197. var Camera = /** @class */ (function (_super) {
  23198. __extends(Camera, _super);
  23199. /**
  23200. * Instantiates a new camera object.
  23201. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  23202. * @see http://doc.babylonjs.com/features/cameras
  23203. * @param name Defines the name of the camera in the scene
  23204. * @param position Defines the position of the camera
  23205. * @param scene Defines the scene the camera belongs too
  23206. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  23207. */
  23208. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  23209. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  23210. var _this = _super.call(this, name, scene) || this;
  23211. /**
  23212. * The vector the camera should consider as up.
  23213. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  23214. */
  23215. _this.upVector = BABYLON.Vector3.Up();
  23216. /**
  23217. * Define the current limit on the left side for an orthographic camera
  23218. * In scene unit
  23219. */
  23220. _this.orthoLeft = null;
  23221. /**
  23222. * Define the current limit on the right side for an orthographic camera
  23223. * In scene unit
  23224. */
  23225. _this.orthoRight = null;
  23226. /**
  23227. * Define the current limit on the bottom side for an orthographic camera
  23228. * In scene unit
  23229. */
  23230. _this.orthoBottom = null;
  23231. /**
  23232. * Define the current limit on the top side for an orthographic camera
  23233. * In scene unit
  23234. */
  23235. _this.orthoTop = null;
  23236. /**
  23237. * Field Of View is set in Radians. (default is 0.8)
  23238. */
  23239. _this.fov = 0.8;
  23240. /**
  23241. * Define the minimum distance the camera can see from.
  23242. * This is important to note that the depth buffer are not infinite and the closer it starts
  23243. * the more your scene might encounter depth fighting issue.
  23244. */
  23245. _this.minZ = 1;
  23246. /**
  23247. * Define the maximum distance the camera can see to.
  23248. * This is important to note that the depth buffer are not infinite and the further it end
  23249. * the more your scene might encounter depth fighting issue.
  23250. */
  23251. _this.maxZ = 10000.0;
  23252. /**
  23253. * Define the default inertia of the camera.
  23254. * This helps giving a smooth feeling to the camera movement.
  23255. */
  23256. _this.inertia = 0.9;
  23257. /**
  23258. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  23259. */
  23260. _this.mode = Camera.PERSPECTIVE_CAMERA;
  23261. /**
  23262. * Define wether the camera is intermediate.
  23263. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  23264. */
  23265. _this.isIntermediate = false;
  23266. /**
  23267. * Define the viewport of the camera.
  23268. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  23269. */
  23270. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  23271. /**
  23272. * Restricts the camera to viewing objects with the same layerMask.
  23273. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  23274. */
  23275. _this.layerMask = 0x0FFFFFFF;
  23276. /**
  23277. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  23278. */
  23279. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  23280. /**
  23281. * Rig mode of the camera.
  23282. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  23283. * This is normally controlled byt the camera themselves as internal use.
  23284. */
  23285. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  23286. /**
  23287. * Defines the list of custom render target the camera should render to.
  23288. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  23289. * else in the scene.
  23290. */
  23291. _this.customRenderTargets = new Array();
  23292. /**
  23293. * Observable triggered when the camera view matrix has changed.
  23294. */
  23295. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  23296. /**
  23297. * Observable triggered when the camera Projection matrix has changed.
  23298. */
  23299. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  23300. /**
  23301. * Observable triggered when the inputs have been processed.
  23302. */
  23303. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  23304. /**
  23305. * Observable triggered when reset has been called and applied to the camera.
  23306. */
  23307. _this.onRestoreStateObservable = new BABYLON.Observable();
  23308. /** @hidden */
  23309. _this._rigCameras = new Array();
  23310. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  23311. /** @hidden */
  23312. _this._skipRendering = false;
  23313. /** @hidden */
  23314. _this._projectionMatrix = new BABYLON.Matrix();
  23315. /** @hidden */
  23316. _this._postProcesses = new Array();
  23317. /** @hidden */
  23318. _this._activeMeshes = new BABYLON.SmartArray(256);
  23319. _this._globalPosition = BABYLON.Vector3.Zero();
  23320. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  23321. _this._doNotComputeProjectionMatrix = false;
  23322. _this._transformMatrix = BABYLON.Matrix.Zero();
  23323. _this._refreshFrustumPlanes = true;
  23324. _this.getScene().addCamera(_this);
  23325. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  23326. _this.getScene().activeCamera = _this;
  23327. }
  23328. _this.position = position;
  23329. return _this;
  23330. }
  23331. /**
  23332. * Store current camera state (fov, position, etc..)
  23333. * @returns the camera
  23334. */
  23335. Camera.prototype.storeState = function () {
  23336. this._stateStored = true;
  23337. this._storedFov = this.fov;
  23338. return this;
  23339. };
  23340. /**
  23341. * Restores the camera state values if it has been stored. You must call storeState() first
  23342. */
  23343. Camera.prototype._restoreStateValues = function () {
  23344. if (!this._stateStored) {
  23345. return false;
  23346. }
  23347. this.fov = this._storedFov;
  23348. return true;
  23349. };
  23350. /**
  23351. * Restored camera state. You must call storeState() first.
  23352. * @returns true if restored and false otherwise
  23353. */
  23354. Camera.prototype.restoreState = function () {
  23355. if (this._restoreStateValues()) {
  23356. this.onRestoreStateObservable.notifyObservers(this);
  23357. return true;
  23358. }
  23359. return false;
  23360. };
  23361. /**
  23362. * Gets the class name of the camera.
  23363. * @returns the class name
  23364. */
  23365. Camera.prototype.getClassName = function () {
  23366. return "Camera";
  23367. };
  23368. /**
  23369. * Gets a string representation of the camera usefull for debug purpose.
  23370. * @param fullDetails Defines that a more verboe level of logging is required
  23371. * @returns the string representation
  23372. */
  23373. Camera.prototype.toString = function (fullDetails) {
  23374. var ret = "Name: " + this.name;
  23375. ret += ", type: " + this.getClassName();
  23376. if (this.animations) {
  23377. for (var i = 0; i < this.animations.length; i++) {
  23378. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23379. }
  23380. }
  23381. if (fullDetails) {
  23382. }
  23383. return ret;
  23384. };
  23385. Object.defineProperty(Camera.prototype, "globalPosition", {
  23386. /**
  23387. * Gets the current world space position of the camera.
  23388. */
  23389. get: function () {
  23390. return this._globalPosition;
  23391. },
  23392. enumerable: true,
  23393. configurable: true
  23394. });
  23395. /**
  23396. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  23397. * @returns the active meshe list
  23398. */
  23399. Camera.prototype.getActiveMeshes = function () {
  23400. return this._activeMeshes;
  23401. };
  23402. /**
  23403. * Check wether a mesh is part of the current active mesh list of the camera
  23404. * @param mesh Defines the mesh to check
  23405. * @returns true if active, false otherwise
  23406. */
  23407. Camera.prototype.isActiveMesh = function (mesh) {
  23408. return (this._activeMeshes.indexOf(mesh) !== -1);
  23409. };
  23410. /**
  23411. * Is this camera ready to be used/rendered
  23412. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  23413. * @return true if the camera is ready
  23414. */
  23415. Camera.prototype.isReady = function (completeCheck) {
  23416. if (completeCheck === void 0) { completeCheck = false; }
  23417. if (completeCheck) {
  23418. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  23419. var pp = _a[_i];
  23420. if (pp && !pp.isReady()) {
  23421. return false;
  23422. }
  23423. }
  23424. }
  23425. return _super.prototype.isReady.call(this, completeCheck);
  23426. };
  23427. /** @hidden */
  23428. Camera.prototype._initCache = function () {
  23429. _super.prototype._initCache.call(this);
  23430. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23431. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23432. this._cache.mode = undefined;
  23433. this._cache.minZ = undefined;
  23434. this._cache.maxZ = undefined;
  23435. this._cache.fov = undefined;
  23436. this._cache.fovMode = undefined;
  23437. this._cache.aspectRatio = undefined;
  23438. this._cache.orthoLeft = undefined;
  23439. this._cache.orthoRight = undefined;
  23440. this._cache.orthoBottom = undefined;
  23441. this._cache.orthoTop = undefined;
  23442. this._cache.renderWidth = undefined;
  23443. this._cache.renderHeight = undefined;
  23444. };
  23445. /** @hidden */
  23446. Camera.prototype._updateCache = function (ignoreParentClass) {
  23447. if (!ignoreParentClass) {
  23448. _super.prototype._updateCache.call(this);
  23449. }
  23450. this._cache.position.copyFrom(this.position);
  23451. this._cache.upVector.copyFrom(this.upVector);
  23452. };
  23453. /** @hidden */
  23454. Camera.prototype._isSynchronized = function () {
  23455. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  23456. };
  23457. /** @hidden */
  23458. Camera.prototype._isSynchronizedViewMatrix = function () {
  23459. if (!_super.prototype._isSynchronized.call(this)) {
  23460. return false;
  23461. }
  23462. return this._cache.position.equals(this.position)
  23463. && this._cache.upVector.equals(this.upVector)
  23464. && this.isSynchronizedWithParent();
  23465. };
  23466. /** @hidden */
  23467. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  23468. var check = this._cache.mode === this.mode
  23469. && this._cache.minZ === this.minZ
  23470. && this._cache.maxZ === this.maxZ;
  23471. if (!check) {
  23472. return false;
  23473. }
  23474. var engine = this.getEngine();
  23475. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23476. check = this._cache.fov === this.fov
  23477. && this._cache.fovMode === this.fovMode
  23478. && this._cache.aspectRatio === engine.getAspectRatio(this);
  23479. }
  23480. else {
  23481. check = this._cache.orthoLeft === this.orthoLeft
  23482. && this._cache.orthoRight === this.orthoRight
  23483. && this._cache.orthoBottom === this.orthoBottom
  23484. && this._cache.orthoTop === this.orthoTop
  23485. && this._cache.renderWidth === engine.getRenderWidth()
  23486. && this._cache.renderHeight === engine.getRenderHeight();
  23487. }
  23488. return check;
  23489. };
  23490. /**
  23491. * Attach the input controls to a specific dom element to get the input from.
  23492. * @param element Defines the element the controls should be listened from
  23493. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  23494. */
  23495. Camera.prototype.attachControl = function (element, noPreventDefault) {
  23496. };
  23497. /**
  23498. * Detach the current controls from the specified dom element.
  23499. * @param element Defines the element to stop listening the inputs from
  23500. */
  23501. Camera.prototype.detachControl = function (element) {
  23502. };
  23503. /**
  23504. * Update the camera state according to the different inputs gathered during the frame.
  23505. */
  23506. Camera.prototype.update = function () {
  23507. this._checkInputs();
  23508. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23509. this._updateRigCameras();
  23510. }
  23511. };
  23512. /** @hidden */
  23513. Camera.prototype._checkInputs = function () {
  23514. this.onAfterCheckInputsObservable.notifyObservers(this);
  23515. };
  23516. Object.defineProperty(Camera.prototype, "rigCameras", {
  23517. /** @hidden */
  23518. get: function () {
  23519. return this._rigCameras;
  23520. },
  23521. enumerable: true,
  23522. configurable: true
  23523. });
  23524. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  23525. /**
  23526. * Gets the post process used by the rig cameras
  23527. */
  23528. get: function () {
  23529. return this._rigPostProcess;
  23530. },
  23531. enumerable: true,
  23532. configurable: true
  23533. });
  23534. /**
  23535. * Internal, gets the first post proces.
  23536. * @returns the first post process to be run on this camera.
  23537. */
  23538. Camera.prototype._getFirstPostProcess = function () {
  23539. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  23540. if (this._postProcesses[ppIndex] !== null) {
  23541. return this._postProcesses[ppIndex];
  23542. }
  23543. }
  23544. return null;
  23545. };
  23546. Camera.prototype._cascadePostProcessesToRigCams = function () {
  23547. // invalidate framebuffer
  23548. var firstPostProcess = this._getFirstPostProcess();
  23549. if (firstPostProcess) {
  23550. firstPostProcess.markTextureDirty();
  23551. }
  23552. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  23553. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  23554. var cam = this._rigCameras[i];
  23555. var rigPostProcess = cam._rigPostProcess;
  23556. // for VR rig, there does not have to be a post process
  23557. if (rigPostProcess) {
  23558. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  23559. if (isPass) {
  23560. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  23561. cam.isIntermediate = this._postProcesses.length === 0;
  23562. }
  23563. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  23564. rigPostProcess.markTextureDirty();
  23565. }
  23566. else {
  23567. cam._postProcesses = this._postProcesses.slice(0);
  23568. }
  23569. }
  23570. };
  23571. /**
  23572. * Attach a post process to the camera.
  23573. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23574. * @param postProcess The post process to attach to the camera
  23575. * @param insertAt The position of the post process in case several of them are in use in the scene
  23576. * @returns the position the post process has been inserted at
  23577. */
  23578. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  23579. if (insertAt === void 0) { insertAt = null; }
  23580. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  23581. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  23582. return 0;
  23583. }
  23584. if (insertAt == null || insertAt < 0) {
  23585. this._postProcesses.push(postProcess);
  23586. }
  23587. else if (this._postProcesses[insertAt] === null) {
  23588. this._postProcesses[insertAt] = postProcess;
  23589. }
  23590. else {
  23591. this._postProcesses.splice(insertAt, 0, postProcess);
  23592. }
  23593. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23594. return this._postProcesses.indexOf(postProcess);
  23595. };
  23596. /**
  23597. * Detach a post process to the camera.
  23598. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23599. * @param postProcess The post process to detach from the camera
  23600. */
  23601. Camera.prototype.detachPostProcess = function (postProcess) {
  23602. var idx = this._postProcesses.indexOf(postProcess);
  23603. if (idx !== -1) {
  23604. this._postProcesses[idx] = null;
  23605. }
  23606. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23607. };
  23608. /**
  23609. * Gets the current world matrix of the camera
  23610. */
  23611. Camera.prototype.getWorldMatrix = function () {
  23612. if (this._isSynchronizedViewMatrix()) {
  23613. return this._worldMatrix;
  23614. }
  23615. // Getting the the view matrix will also compute the world matrix.
  23616. this.getViewMatrix();
  23617. return this._worldMatrix;
  23618. };
  23619. /** @hidden */
  23620. Camera.prototype._getViewMatrix = function () {
  23621. return BABYLON.Matrix.Identity();
  23622. };
  23623. /**
  23624. * Gets the current view matrix of the camera.
  23625. * @param force forces the camera to recompute the matrix without looking at the cached state
  23626. * @returns the view matrix
  23627. */
  23628. Camera.prototype.getViewMatrix = function (force) {
  23629. if (!force && this._isSynchronizedViewMatrix()) {
  23630. return this._computedViewMatrix;
  23631. }
  23632. this.updateCache();
  23633. this._computedViewMatrix = this._getViewMatrix();
  23634. this._currentRenderId = this.getScene().getRenderId();
  23635. this._childRenderId = this._currentRenderId;
  23636. this._refreshFrustumPlanes = true;
  23637. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  23638. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  23639. }
  23640. this.onViewMatrixChangedObservable.notifyObservers(this);
  23641. this._computedViewMatrix.invertToRef(this._worldMatrix);
  23642. return this._computedViewMatrix;
  23643. };
  23644. /**
  23645. * Freeze the projection matrix.
  23646. * It will prevent the cache check of the camera projection compute and can speed up perf
  23647. * if no parameter of the camera are meant to change
  23648. * @param projection Defines manually a projection if necessary
  23649. */
  23650. Camera.prototype.freezeProjectionMatrix = function (projection) {
  23651. this._doNotComputeProjectionMatrix = true;
  23652. if (projection !== undefined) {
  23653. this._projectionMatrix = projection;
  23654. }
  23655. };
  23656. /**
  23657. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  23658. */
  23659. Camera.prototype.unfreezeProjectionMatrix = function () {
  23660. this._doNotComputeProjectionMatrix = false;
  23661. };
  23662. /**
  23663. * Gets the current projection matrix of the camera.
  23664. * @param force forces the camera to recompute the matrix without looking at the cached state
  23665. * @returns the projection matrix
  23666. */
  23667. Camera.prototype.getProjectionMatrix = function (force) {
  23668. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  23669. return this._projectionMatrix;
  23670. }
  23671. // Cache
  23672. this._cache.mode = this.mode;
  23673. this._cache.minZ = this.minZ;
  23674. this._cache.maxZ = this.maxZ;
  23675. // Matrix
  23676. this._refreshFrustumPlanes = true;
  23677. var engine = this.getEngine();
  23678. var scene = this.getScene();
  23679. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23680. this._cache.fov = this.fov;
  23681. this._cache.fovMode = this.fovMode;
  23682. this._cache.aspectRatio = engine.getAspectRatio(this);
  23683. if (this.minZ <= 0) {
  23684. this.minZ = 0.1;
  23685. }
  23686. if (scene.useRightHandedSystem) {
  23687. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23688. }
  23689. else {
  23690. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23691. }
  23692. }
  23693. else {
  23694. var halfWidth = engine.getRenderWidth() / 2.0;
  23695. var halfHeight = engine.getRenderHeight() / 2.0;
  23696. if (scene.useRightHandedSystem) {
  23697. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23698. }
  23699. else {
  23700. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23701. }
  23702. this._cache.orthoLeft = this.orthoLeft;
  23703. this._cache.orthoRight = this.orthoRight;
  23704. this._cache.orthoBottom = this.orthoBottom;
  23705. this._cache.orthoTop = this.orthoTop;
  23706. this._cache.renderWidth = engine.getRenderWidth();
  23707. this._cache.renderHeight = engine.getRenderHeight();
  23708. }
  23709. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  23710. return this._projectionMatrix;
  23711. };
  23712. /**
  23713. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  23714. * @returns a Matrix
  23715. */
  23716. Camera.prototype.getTransformationMatrix = function () {
  23717. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23718. return this._transformMatrix;
  23719. };
  23720. Camera.prototype._updateFrustumPlanes = function () {
  23721. if (!this._refreshFrustumPlanes) {
  23722. return;
  23723. }
  23724. this.getTransformationMatrix();
  23725. if (!this._frustumPlanes) {
  23726. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23727. }
  23728. else {
  23729. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23730. }
  23731. this._refreshFrustumPlanes = false;
  23732. };
  23733. /**
  23734. * Checks if a cullable object (mesh...) is in the camera frustum
  23735. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  23736. * @param target The object to check
  23737. * @returns true if the object is in frustum otherwise false
  23738. */
  23739. Camera.prototype.isInFrustum = function (target) {
  23740. this._updateFrustumPlanes();
  23741. return target.isInFrustum(this._frustumPlanes);
  23742. };
  23743. /**
  23744. * Checks if a cullable object (mesh...) is in the camera frustum
  23745. * Unlike isInFrustum this cheks the full bounding box
  23746. * @param target The object to check
  23747. * @returns true if the object is in frustum otherwise false
  23748. */
  23749. Camera.prototype.isCompletelyInFrustum = function (target) {
  23750. this._updateFrustumPlanes();
  23751. return target.isCompletelyInFrustum(this._frustumPlanes);
  23752. };
  23753. /**
  23754. * Gets a ray in the forward direction from the camera.
  23755. * @param length Defines the length of the ray to create
  23756. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  23757. * @param origin Defines the start point of the ray which defaults to the camera position
  23758. * @returns the forward ray
  23759. */
  23760. Camera.prototype.getForwardRay = function (length, transform, origin) {
  23761. if (length === void 0) { length = 100; }
  23762. if (!transform) {
  23763. transform = this.getWorldMatrix();
  23764. }
  23765. if (!origin) {
  23766. origin = this.position;
  23767. }
  23768. var forward = this._scene.useRightHandedSystem ? new BABYLON.Vector3(0, 0, -1) : new BABYLON.Vector3(0, 0, 1);
  23769. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  23770. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  23771. return new BABYLON.Ray(origin, direction, length);
  23772. };
  23773. /**
  23774. * Releases resources associated with this node.
  23775. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  23776. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  23777. */
  23778. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  23779. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  23780. // Observables
  23781. this.onViewMatrixChangedObservable.clear();
  23782. this.onProjectionMatrixChangedObservable.clear();
  23783. this.onAfterCheckInputsObservable.clear();
  23784. this.onRestoreStateObservable.clear();
  23785. // Inputs
  23786. if (this.inputs) {
  23787. this.inputs.clear();
  23788. }
  23789. // Animations
  23790. this.getScene().stopAnimation(this);
  23791. // Remove from scene
  23792. this.getScene().removeCamera(this);
  23793. while (this._rigCameras.length > 0) {
  23794. var camera = this._rigCameras.pop();
  23795. if (camera) {
  23796. camera.dispose();
  23797. }
  23798. }
  23799. // Postprocesses
  23800. if (this._rigPostProcess) {
  23801. this._rigPostProcess.dispose(this);
  23802. this._rigPostProcess = null;
  23803. this._postProcesses = [];
  23804. }
  23805. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23806. this._rigPostProcess = null;
  23807. this._postProcesses = [];
  23808. }
  23809. else {
  23810. var i = this._postProcesses.length;
  23811. while (--i >= 0) {
  23812. var postProcess = this._postProcesses[i];
  23813. if (postProcess) {
  23814. postProcess.dispose(this);
  23815. }
  23816. }
  23817. }
  23818. // Render targets
  23819. var i = this.customRenderTargets.length;
  23820. while (--i >= 0) {
  23821. this.customRenderTargets[i].dispose();
  23822. }
  23823. this.customRenderTargets = [];
  23824. // Active Meshes
  23825. this._activeMeshes.dispose();
  23826. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  23827. };
  23828. Object.defineProperty(Camera.prototype, "leftCamera", {
  23829. /**
  23830. * Gets the left camera of a rig setup in case of Rigged Camera
  23831. */
  23832. get: function () {
  23833. if (this._rigCameras.length < 1) {
  23834. return null;
  23835. }
  23836. return this._rigCameras[0];
  23837. },
  23838. enumerable: true,
  23839. configurable: true
  23840. });
  23841. Object.defineProperty(Camera.prototype, "rightCamera", {
  23842. /**
  23843. * Gets the right camera of a rig setup in case of Rigged Camera
  23844. */
  23845. get: function () {
  23846. if (this._rigCameras.length < 2) {
  23847. return null;
  23848. }
  23849. return this._rigCameras[1];
  23850. },
  23851. enumerable: true,
  23852. configurable: true
  23853. });
  23854. /**
  23855. * Gets the left camera target of a rig setup in case of Rigged Camera
  23856. * @returns the target position
  23857. */
  23858. Camera.prototype.getLeftTarget = function () {
  23859. if (this._rigCameras.length < 1) {
  23860. return null;
  23861. }
  23862. return this._rigCameras[0].getTarget();
  23863. };
  23864. /**
  23865. * Gets the right camera target of a rig setup in case of Rigged Camera
  23866. * @returns the target position
  23867. */
  23868. Camera.prototype.getRightTarget = function () {
  23869. if (this._rigCameras.length < 2) {
  23870. return null;
  23871. }
  23872. return this._rigCameras[1].getTarget();
  23873. };
  23874. /**
  23875. * @hidden
  23876. */
  23877. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  23878. if (this.cameraRigMode === mode) {
  23879. return;
  23880. }
  23881. while (this._rigCameras.length > 0) {
  23882. var camera = this._rigCameras.pop();
  23883. if (camera) {
  23884. camera.dispose();
  23885. }
  23886. }
  23887. this.cameraRigMode = mode;
  23888. this._cameraRigParams = {};
  23889. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  23890. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  23891. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  23892. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  23893. // create the rig cameras, unless none
  23894. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23895. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23896. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23897. if (leftCamera && rightCamera) {
  23898. this._rigCameras.push(leftCamera);
  23899. this._rigCameras.push(rightCamera);
  23900. }
  23901. }
  23902. switch (this.cameraRigMode) {
  23903. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  23904. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23905. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  23906. break;
  23907. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  23908. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  23909. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  23910. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  23911. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23912. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  23913. break;
  23914. case Camera.RIG_MODE_VR:
  23915. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  23916. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  23917. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23918. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23919. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  23920. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  23921. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23922. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23923. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23924. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23925. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23926. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23927. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23928. if (metrics.compensateDistortion) {
  23929. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23930. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23931. }
  23932. break;
  23933. case Camera.RIG_MODE_WEBVR:
  23934. if (rigParams.vrDisplay) {
  23935. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23936. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23937. //Left eye
  23938. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23939. this._rigCameras[0].setCameraRigParameter("left", true);
  23940. //leaving this for future reference
  23941. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23942. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23943. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23944. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23945. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23946. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23947. this._rigCameras[0].parent = this;
  23948. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23949. //Right eye
  23950. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23951. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23952. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23953. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23954. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23955. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23956. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23957. this._rigCameras[1].parent = this;
  23958. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23959. if (Camera.UseAlternateWebVRRendering) {
  23960. this._rigCameras[1]._skipRendering = true;
  23961. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23962. }
  23963. }
  23964. break;
  23965. }
  23966. this._cascadePostProcessesToRigCams();
  23967. this.update();
  23968. };
  23969. Camera.prototype._getVRProjectionMatrix = function () {
  23970. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23971. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23972. return this._projectionMatrix;
  23973. };
  23974. Camera.prototype._updateCameraRotationMatrix = function () {
  23975. //Here for WebVR
  23976. };
  23977. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23978. //Here for WebVR
  23979. };
  23980. /**
  23981. * This function MUST be overwritten by the different WebVR cameras available.
  23982. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23983. */
  23984. Camera.prototype._getWebVRProjectionMatrix = function () {
  23985. return BABYLON.Matrix.Identity();
  23986. };
  23987. /**
  23988. * This function MUST be overwritten by the different WebVR cameras available.
  23989. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23990. */
  23991. Camera.prototype._getWebVRViewMatrix = function () {
  23992. return BABYLON.Matrix.Identity();
  23993. };
  23994. /** @hidden */
  23995. Camera.prototype.setCameraRigParameter = function (name, value) {
  23996. if (!this._cameraRigParams) {
  23997. this._cameraRigParams = {};
  23998. }
  23999. this._cameraRigParams[name] = value;
  24000. //provisionnally:
  24001. if (name === "interaxialDistance") {
  24002. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  24003. }
  24004. };
  24005. /**
  24006. * needs to be overridden by children so sub has required properties to be copied
  24007. * @hidden
  24008. */
  24009. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  24010. return null;
  24011. };
  24012. /**
  24013. * May need to be overridden by children
  24014. * @hidden
  24015. */
  24016. Camera.prototype._updateRigCameras = function () {
  24017. for (var i = 0; i < this._rigCameras.length; i++) {
  24018. this._rigCameras[i].minZ = this.minZ;
  24019. this._rigCameras[i].maxZ = this.maxZ;
  24020. this._rigCameras[i].fov = this.fov;
  24021. }
  24022. // only update viewport when ANAGLYPH
  24023. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  24024. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  24025. }
  24026. };
  24027. /** @hidden */
  24028. Camera.prototype._setupInputs = function () {
  24029. };
  24030. /**
  24031. * Serialiaze the camera setup to a json represention
  24032. * @returns the JSON representation
  24033. */
  24034. Camera.prototype.serialize = function () {
  24035. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24036. // Type
  24037. serializationObject.type = this.getClassName();
  24038. // Parent
  24039. if (this.parent) {
  24040. serializationObject.parentId = this.parent.id;
  24041. }
  24042. if (this.inputs) {
  24043. this.inputs.serialize(serializationObject);
  24044. }
  24045. // Animations
  24046. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24047. serializationObject.ranges = this.serializeAnimationRanges();
  24048. return serializationObject;
  24049. };
  24050. /**
  24051. * Clones the current camera.
  24052. * @param name The cloned camera name
  24053. * @returns the cloned camera
  24054. */
  24055. Camera.prototype.clone = function (name) {
  24056. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  24057. };
  24058. /**
  24059. * Gets the direction of the camera relative to a given local axis.
  24060. * @param localAxis Defines the reference axis to provide a relative direction.
  24061. * @return the direction
  24062. */
  24063. Camera.prototype.getDirection = function (localAxis) {
  24064. var result = BABYLON.Vector3.Zero();
  24065. this.getDirectionToRef(localAxis, result);
  24066. return result;
  24067. };
  24068. /**
  24069. * Gets the direction of the camera relative to a given local axis into a passed vector.
  24070. * @param localAxis Defines the reference axis to provide a relative direction.
  24071. * @param result Defines the vector to store the result in
  24072. */
  24073. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  24074. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  24075. };
  24076. /**
  24077. * Gets a camera constructor for a given camera type
  24078. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  24079. * @param name The name of the camera the result will be able to instantiate
  24080. * @param scene The scene the result will construct the camera in
  24081. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  24082. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  24083. * @returns a factory method to construc the camera
  24084. */
  24085. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  24086. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  24087. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  24088. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  24089. interaxial_distance: interaxial_distance,
  24090. isStereoscopicSideBySide: isStereoscopicSideBySide
  24091. });
  24092. if (constructorFunc) {
  24093. return constructorFunc;
  24094. }
  24095. // Default to universal camera
  24096. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  24097. };
  24098. /**
  24099. * Compute the world matrix of the camera.
  24100. * @returns the camera workd matrix
  24101. */
  24102. Camera.prototype.computeWorldMatrix = function () {
  24103. return this.getWorldMatrix();
  24104. };
  24105. /**
  24106. * Parse a JSON and creates the camera from the parsed information
  24107. * @param parsedCamera The JSON to parse
  24108. * @param scene The scene to instantiate the camera in
  24109. * @returns the newly constructed camera
  24110. */
  24111. Camera.Parse = function (parsedCamera, scene) {
  24112. var type = parsedCamera.type;
  24113. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  24114. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  24115. // Parent
  24116. if (parsedCamera.parentId) {
  24117. camera._waitingParentId = parsedCamera.parentId;
  24118. }
  24119. //If camera has an input manager, let it parse inputs settings
  24120. if (camera.inputs) {
  24121. camera.inputs.parse(parsedCamera);
  24122. camera._setupInputs();
  24123. }
  24124. if (camera.setPosition) { // need to force position
  24125. camera.position.copyFromFloats(0, 0, 0);
  24126. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  24127. }
  24128. // Target
  24129. if (parsedCamera.target) {
  24130. if (camera.setTarget) {
  24131. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  24132. }
  24133. }
  24134. // Apply 3d rig, when found
  24135. if (parsedCamera.cameraRigMode) {
  24136. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  24137. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  24138. }
  24139. // Animations
  24140. if (parsedCamera.animations) {
  24141. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  24142. var parsedAnimation = parsedCamera.animations[animationIndex];
  24143. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24144. }
  24145. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  24146. }
  24147. if (parsedCamera.autoAnimate) {
  24148. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  24149. }
  24150. return camera;
  24151. };
  24152. /**
  24153. * This is the default projection mode used by the cameras.
  24154. * It helps recreating a feeling of perspective and better appreciate depth.
  24155. * This is the best way to simulate real life cameras.
  24156. */
  24157. Camera.PERSPECTIVE_CAMERA = 0;
  24158. /**
  24159. * This helps creating camera with an orthographic mode.
  24160. * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object.
  24161. */
  24162. Camera.ORTHOGRAPHIC_CAMERA = 1;
  24163. /**
  24164. * This is the default FOV mode for perspective cameras.
  24165. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  24166. */
  24167. Camera.FOVMODE_VERTICAL_FIXED = 0;
  24168. /**
  24169. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  24170. */
  24171. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  24172. /**
  24173. * This specifies ther is no need for a camera rig.
  24174. * Basically only one eye is rendered corresponding to the camera.
  24175. */
  24176. Camera.RIG_MODE_NONE = 0;
  24177. /**
  24178. * Simulates a camera Rig with one blue eye and one red eye.
  24179. * This can be use with 3d blue and red glasses.
  24180. */
  24181. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  24182. /**
  24183. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  24184. */
  24185. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  24186. /**
  24187. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  24188. */
  24189. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  24190. /**
  24191. * Defines that both eyes of the camera will be rendered over under each other.
  24192. */
  24193. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  24194. /**
  24195. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  24196. */
  24197. Camera.RIG_MODE_VR = 20;
  24198. /**
  24199. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  24200. */
  24201. Camera.RIG_MODE_WEBVR = 21;
  24202. /**
  24203. * Defines if by default attaching controls should prevent the default javascript event to continue.
  24204. */
  24205. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  24206. /**
  24207. * @hidden
  24208. * Might be removed once multiview will be a thing
  24209. */
  24210. Camera.UseAlternateWebVRRendering = false;
  24211. __decorate([
  24212. BABYLON.serializeAsVector3()
  24213. ], Camera.prototype, "position", void 0);
  24214. __decorate([
  24215. BABYLON.serializeAsVector3()
  24216. ], Camera.prototype, "upVector", void 0);
  24217. __decorate([
  24218. BABYLON.serialize()
  24219. ], Camera.prototype, "orthoLeft", void 0);
  24220. __decorate([
  24221. BABYLON.serialize()
  24222. ], Camera.prototype, "orthoRight", void 0);
  24223. __decorate([
  24224. BABYLON.serialize()
  24225. ], Camera.prototype, "orthoBottom", void 0);
  24226. __decorate([
  24227. BABYLON.serialize()
  24228. ], Camera.prototype, "orthoTop", void 0);
  24229. __decorate([
  24230. BABYLON.serialize()
  24231. ], Camera.prototype, "fov", void 0);
  24232. __decorate([
  24233. BABYLON.serialize()
  24234. ], Camera.prototype, "minZ", void 0);
  24235. __decorate([
  24236. BABYLON.serialize()
  24237. ], Camera.prototype, "maxZ", void 0);
  24238. __decorate([
  24239. BABYLON.serialize()
  24240. ], Camera.prototype, "inertia", void 0);
  24241. __decorate([
  24242. BABYLON.serialize()
  24243. ], Camera.prototype, "mode", void 0);
  24244. __decorate([
  24245. BABYLON.serialize()
  24246. ], Camera.prototype, "layerMask", void 0);
  24247. __decorate([
  24248. BABYLON.serialize()
  24249. ], Camera.prototype, "fovMode", void 0);
  24250. __decorate([
  24251. BABYLON.serialize()
  24252. ], Camera.prototype, "cameraRigMode", void 0);
  24253. __decorate([
  24254. BABYLON.serialize()
  24255. ], Camera.prototype, "interaxialDistance", void 0);
  24256. __decorate([
  24257. BABYLON.serialize()
  24258. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  24259. return Camera;
  24260. }(BABYLON.Node));
  24261. BABYLON.Camera = Camera;
  24262. })(BABYLON || (BABYLON = {}));
  24263. //# sourceMappingURL=babylon.camera.js.map
  24264. var BABYLON;
  24265. (function (BABYLON) {
  24266. /**
  24267. * This is the manager responsible of all the rendering for meshes sprites and particles.
  24268. * It is enable to manage the different groups as well as the different necessary sort functions.
  24269. * This should not be used directly aside of the few static configurations
  24270. */
  24271. var RenderingManager = /** @class */ (function () {
  24272. /**
  24273. * Instantiates a new rendering group for a particular scene
  24274. * @param scene Defines the scene the groups belongs to
  24275. */
  24276. function RenderingManager(scene) {
  24277. /**
  24278. * @hidden
  24279. */
  24280. this._useSceneAutoClearSetup = false;
  24281. this._renderingGroups = new Array();
  24282. this._autoClearDepthStencil = {};
  24283. this._customOpaqueSortCompareFn = {};
  24284. this._customAlphaTestSortCompareFn = {};
  24285. this._customTransparentSortCompareFn = {};
  24286. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  24287. this._scene = scene;
  24288. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  24289. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  24290. }
  24291. }
  24292. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  24293. if (depth === void 0) { depth = true; }
  24294. if (stencil === void 0) { stencil = true; }
  24295. if (this._depthStencilBufferAlreadyCleaned) {
  24296. return;
  24297. }
  24298. this._scene.getEngine().clear(null, false, depth, stencil);
  24299. this._depthStencilBufferAlreadyCleaned = true;
  24300. };
  24301. /**
  24302. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  24303. * @hidden
  24304. */
  24305. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  24306. // Update the observable context (not null as it only goes away on dispose)
  24307. var info = this._renderingGroupInfo;
  24308. info.scene = this._scene;
  24309. info.camera = this._scene.activeCamera;
  24310. // Dispatch sprites
  24311. if (this._scene.spriteManagers && renderSprites) {
  24312. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  24313. var manager = this._scene.spriteManagers[index];
  24314. this.dispatchSprites(manager);
  24315. }
  24316. }
  24317. // Render
  24318. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24319. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  24320. var renderingGroup = this._renderingGroups[index];
  24321. if (!renderingGroup) {
  24322. continue;
  24323. }
  24324. var renderingGroupMask = Math.pow(2, index);
  24325. info.renderingGroupId = index;
  24326. // Before Observable
  24327. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24328. // Clear depth/stencil if needed
  24329. if (RenderingManager.AUTOCLEAR) {
  24330. var autoClear = this._useSceneAutoClearSetup ?
  24331. this._scene.getAutoClearDepthStencilSetup(index) :
  24332. this._autoClearDepthStencil[index];
  24333. if (autoClear && autoClear.autoClear) {
  24334. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  24335. }
  24336. }
  24337. // Render
  24338. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  24339. var step = _a[_i];
  24340. step.action(index);
  24341. }
  24342. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  24343. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  24344. var step = _c[_b];
  24345. step.action(index);
  24346. }
  24347. // After Observable
  24348. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24349. }
  24350. };
  24351. /**
  24352. * Resets the different information of the group to prepare a new frame
  24353. * @hidden
  24354. */
  24355. RenderingManager.prototype.reset = function () {
  24356. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24357. var renderingGroup = this._renderingGroups[index];
  24358. if (renderingGroup) {
  24359. renderingGroup.prepare();
  24360. }
  24361. }
  24362. };
  24363. /**
  24364. * Dispose and release the group and its associated resources.
  24365. * @hidden
  24366. */
  24367. RenderingManager.prototype.dispose = function () {
  24368. this.freeRenderingGroups();
  24369. this._renderingGroups.length = 0;
  24370. this._renderingGroupInfo = null;
  24371. };
  24372. /**
  24373. * Clear the info related to rendering groups preventing retention points during dispose.
  24374. */
  24375. RenderingManager.prototype.freeRenderingGroups = function () {
  24376. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24377. var renderingGroup = this._renderingGroups[index];
  24378. if (renderingGroup) {
  24379. renderingGroup.dispose();
  24380. }
  24381. }
  24382. };
  24383. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  24384. if (this._renderingGroups[renderingGroupId] === undefined) {
  24385. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  24386. }
  24387. };
  24388. /**
  24389. * Add a sprite manager to the rendering manager in order to render it this frame.
  24390. * @param spriteManager Define the sprite manager to render
  24391. */
  24392. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  24393. var renderingGroupId = spriteManager.renderingGroupId || 0;
  24394. this._prepareRenderingGroup(renderingGroupId);
  24395. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  24396. };
  24397. /**
  24398. * Add a particle system to the rendering manager in order to render it this frame.
  24399. * @param particleSystem Define the particle system to render
  24400. */
  24401. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  24402. var renderingGroupId = particleSystem.renderingGroupId || 0;
  24403. this._prepareRenderingGroup(renderingGroupId);
  24404. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  24405. };
  24406. /**
  24407. * Add a submesh to the manager in order to render it this frame
  24408. * @param subMesh The submesh to dispatch
  24409. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24410. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24411. */
  24412. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  24413. if (mesh === undefined) {
  24414. mesh = subMesh.getMesh();
  24415. }
  24416. var renderingGroupId = mesh.renderingGroupId || 0;
  24417. this._prepareRenderingGroup(renderingGroupId);
  24418. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  24419. };
  24420. /**
  24421. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24422. * This allowed control for front to back rendering or reversly depending of the special needs.
  24423. *
  24424. * @param renderingGroupId The rendering group id corresponding to its index
  24425. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24426. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24427. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24428. */
  24429. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24430. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24431. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24432. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24433. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  24434. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  24435. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  24436. if (this._renderingGroups[renderingGroupId]) {
  24437. var group = this._renderingGroups[renderingGroupId];
  24438. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  24439. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  24440. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  24441. }
  24442. };
  24443. /**
  24444. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24445. *
  24446. * @param renderingGroupId The rendering group id corresponding to its index
  24447. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24448. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24449. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24450. */
  24451. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24452. if (depth === void 0) { depth = true; }
  24453. if (stencil === void 0) { stencil = true; }
  24454. this._autoClearDepthStencil[renderingGroupId] = {
  24455. autoClear: autoClearDepthStencil,
  24456. depth: depth,
  24457. stencil: stencil
  24458. };
  24459. };
  24460. /**
  24461. * Gets the current auto clear configuration for one rendering group of the rendering
  24462. * manager.
  24463. * @param index the rendering group index to get the information for
  24464. * @returns The auto clear setup for the requested rendering group
  24465. */
  24466. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  24467. return this._autoClearDepthStencil[index];
  24468. };
  24469. /**
  24470. * The max id used for rendering groups (not included)
  24471. */
  24472. RenderingManager.MAX_RENDERINGGROUPS = 4;
  24473. /**
  24474. * The min id used for rendering groups (included)
  24475. */
  24476. RenderingManager.MIN_RENDERINGGROUPS = 0;
  24477. /**
  24478. * Used to globally prevent autoclearing scenes.
  24479. */
  24480. RenderingManager.AUTOCLEAR = true;
  24481. return RenderingManager;
  24482. }());
  24483. BABYLON.RenderingManager = RenderingManager;
  24484. })(BABYLON || (BABYLON = {}));
  24485. //# sourceMappingURL=babylon.renderingManager.js.map
  24486. var BABYLON;
  24487. (function (BABYLON) {
  24488. /**
  24489. * This represents the object necessary to create a rendering group.
  24490. * This is exclusively used and created by the rendering manager.
  24491. * To modify the behavior, you use the available helpers in your scene or meshes.
  24492. * @hidden
  24493. */
  24494. var RenderingGroup = /** @class */ (function () {
  24495. /**
  24496. * Creates a new rendering group.
  24497. * @param index The rendering group index
  24498. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  24499. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  24500. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  24501. */
  24502. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24503. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24504. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24505. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24506. this.index = index;
  24507. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  24508. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  24509. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  24510. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  24511. this._particleSystems = new BABYLON.SmartArray(256);
  24512. this._spriteManagers = new BABYLON.SmartArray(256);
  24513. this._edgesRenderers = new BABYLON.SmartArray(16);
  24514. this._scene = scene;
  24515. this.opaqueSortCompareFn = opaqueSortCompareFn;
  24516. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  24517. this.transparentSortCompareFn = transparentSortCompareFn;
  24518. }
  24519. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  24520. /**
  24521. * Set the opaque sort comparison function.
  24522. * If null the sub meshes will be render in the order they were created
  24523. */
  24524. set: function (value) {
  24525. this._opaqueSortCompareFn = value;
  24526. if (value) {
  24527. this._renderOpaque = this.renderOpaqueSorted;
  24528. }
  24529. else {
  24530. this._renderOpaque = RenderingGroup.renderUnsorted;
  24531. }
  24532. },
  24533. enumerable: true,
  24534. configurable: true
  24535. });
  24536. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  24537. /**
  24538. * Set the alpha test sort comparison function.
  24539. * If null the sub meshes will be render in the order they were created
  24540. */
  24541. set: function (value) {
  24542. this._alphaTestSortCompareFn = value;
  24543. if (value) {
  24544. this._renderAlphaTest = this.renderAlphaTestSorted;
  24545. }
  24546. else {
  24547. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  24548. }
  24549. },
  24550. enumerable: true,
  24551. configurable: true
  24552. });
  24553. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  24554. /**
  24555. * Set the transparent sort comparison function.
  24556. * If null the sub meshes will be render in the order they were created
  24557. */
  24558. set: function (value) {
  24559. if (value) {
  24560. this._transparentSortCompareFn = value;
  24561. }
  24562. else {
  24563. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  24564. }
  24565. this._renderTransparent = this.renderTransparentSorted;
  24566. },
  24567. enumerable: true,
  24568. configurable: true
  24569. });
  24570. /**
  24571. * Render all the sub meshes contained in the group.
  24572. * @param customRenderFunction Used to override the default render behaviour of the group.
  24573. * @returns true if rendered some submeshes.
  24574. */
  24575. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  24576. if (customRenderFunction) {
  24577. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  24578. return;
  24579. }
  24580. var engine = this._scene.getEngine();
  24581. // Depth only
  24582. if (this._depthOnlySubMeshes.length !== 0) {
  24583. engine.setColorWrite(false);
  24584. this._renderAlphaTest(this._depthOnlySubMeshes);
  24585. engine.setColorWrite(true);
  24586. }
  24587. // Opaque
  24588. if (this._opaqueSubMeshes.length !== 0) {
  24589. this._renderOpaque(this._opaqueSubMeshes);
  24590. }
  24591. // Alpha test
  24592. if (this._alphaTestSubMeshes.length !== 0) {
  24593. this._renderAlphaTest(this._alphaTestSubMeshes);
  24594. }
  24595. var stencilState = engine.getStencilBuffer();
  24596. engine.setStencilBuffer(false);
  24597. // Sprites
  24598. if (renderSprites) {
  24599. this._renderSprites();
  24600. }
  24601. // Particles
  24602. if (renderParticles) {
  24603. this._renderParticles(activeMeshes);
  24604. }
  24605. if (this.onBeforeTransparentRendering) {
  24606. this.onBeforeTransparentRendering();
  24607. }
  24608. // Transparent
  24609. if (this._transparentSubMeshes.length !== 0) {
  24610. this._renderTransparent(this._transparentSubMeshes);
  24611. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24612. }
  24613. // Set back stencil to false in case it changes before the edge renderer.
  24614. engine.setStencilBuffer(false);
  24615. // Edges
  24616. if (this._edgesRenderers.length) {
  24617. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  24618. this._edgesRenderers.data[edgesRendererIndex].render();
  24619. }
  24620. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24621. }
  24622. // Restore Stencil state.
  24623. engine.setStencilBuffer(stencilState);
  24624. };
  24625. /**
  24626. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  24627. * @param subMeshes The submeshes to render
  24628. */
  24629. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  24630. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  24631. };
  24632. /**
  24633. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  24634. * @param subMeshes The submeshes to render
  24635. */
  24636. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  24637. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  24638. };
  24639. /**
  24640. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  24641. * @param subMeshes The submeshes to render
  24642. */
  24643. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  24644. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  24645. };
  24646. /**
  24647. * Renders the submeshes in a specified order.
  24648. * @param subMeshes The submeshes to sort before render
  24649. * @param sortCompareFn The comparison function use to sort
  24650. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  24651. * @param transparent Specifies to activate blending if true
  24652. */
  24653. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  24654. var subIndex = 0;
  24655. var subMesh;
  24656. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  24657. for (; subIndex < subMeshes.length; subIndex++) {
  24658. subMesh = subMeshes.data[subIndex];
  24659. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  24660. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  24661. }
  24662. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  24663. if (sortCompareFn) {
  24664. sortedArray.sort(sortCompareFn);
  24665. }
  24666. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  24667. subMesh = sortedArray[subIndex];
  24668. if (transparent) {
  24669. var material = subMesh.getMaterial();
  24670. if (material && material.needDepthPrePass) {
  24671. var engine = material.getScene().getEngine();
  24672. engine.setColorWrite(false);
  24673. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24674. subMesh.render(false);
  24675. engine.setColorWrite(true);
  24676. }
  24677. }
  24678. subMesh.render(transparent);
  24679. }
  24680. };
  24681. /**
  24682. * Renders the submeshes in the order they were dispatched (no sort applied).
  24683. * @param subMeshes The submeshes to render
  24684. */
  24685. RenderingGroup.renderUnsorted = function (subMeshes) {
  24686. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  24687. var submesh = subMeshes.data[subIndex];
  24688. submesh.render(false);
  24689. }
  24690. };
  24691. /**
  24692. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24693. * are rendered back to front if in the same alpha index.
  24694. *
  24695. * @param a The first submesh
  24696. * @param b The second submesh
  24697. * @returns The result of the comparison
  24698. */
  24699. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  24700. // Alpha index first
  24701. if (a._alphaIndex > b._alphaIndex) {
  24702. return 1;
  24703. }
  24704. if (a._alphaIndex < b._alphaIndex) {
  24705. return -1;
  24706. }
  24707. // Then distance to camera
  24708. return RenderingGroup.backToFrontSortCompare(a, b);
  24709. };
  24710. /**
  24711. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24712. * are rendered back to front.
  24713. *
  24714. * @param a The first submesh
  24715. * @param b The second submesh
  24716. * @returns The result of the comparison
  24717. */
  24718. RenderingGroup.backToFrontSortCompare = function (a, b) {
  24719. // Then distance to camera
  24720. if (a._distanceToCamera < b._distanceToCamera) {
  24721. return 1;
  24722. }
  24723. if (a._distanceToCamera > b._distanceToCamera) {
  24724. return -1;
  24725. }
  24726. return 0;
  24727. };
  24728. /**
  24729. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24730. * are rendered front to back (prevent overdraw).
  24731. *
  24732. * @param a The first submesh
  24733. * @param b The second submesh
  24734. * @returns The result of the comparison
  24735. */
  24736. RenderingGroup.frontToBackSortCompare = function (a, b) {
  24737. // Then distance to camera
  24738. if (a._distanceToCamera < b._distanceToCamera) {
  24739. return -1;
  24740. }
  24741. if (a._distanceToCamera > b._distanceToCamera) {
  24742. return 1;
  24743. }
  24744. return 0;
  24745. };
  24746. /**
  24747. * Resets the different lists of submeshes to prepare a new frame.
  24748. */
  24749. RenderingGroup.prototype.prepare = function () {
  24750. this._opaqueSubMeshes.reset();
  24751. this._transparentSubMeshes.reset();
  24752. this._alphaTestSubMeshes.reset();
  24753. this._depthOnlySubMeshes.reset();
  24754. this._particleSystems.reset();
  24755. this._spriteManagers.reset();
  24756. this._edgesRenderers.reset();
  24757. };
  24758. RenderingGroup.prototype.dispose = function () {
  24759. this._opaqueSubMeshes.dispose();
  24760. this._transparentSubMeshes.dispose();
  24761. this._alphaTestSubMeshes.dispose();
  24762. this._depthOnlySubMeshes.dispose();
  24763. this._particleSystems.dispose();
  24764. this._spriteManagers.dispose();
  24765. this._edgesRenderers.dispose();
  24766. };
  24767. /**
  24768. * Inserts the submesh in its correct queue depending on its material.
  24769. * @param subMesh The submesh to dispatch
  24770. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24771. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24772. */
  24773. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  24774. // Get mesh and materials if not provided
  24775. if (mesh === undefined) {
  24776. mesh = subMesh.getMesh();
  24777. }
  24778. if (material === undefined) {
  24779. material = subMesh.getMaterial();
  24780. }
  24781. if (material === null || material === undefined) {
  24782. return;
  24783. }
  24784. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  24785. this._transparentSubMeshes.push(subMesh);
  24786. }
  24787. else if (material.needAlphaTesting()) { // Alpha test
  24788. if (material.needDepthPrePass) {
  24789. this._depthOnlySubMeshes.push(subMesh);
  24790. }
  24791. this._alphaTestSubMeshes.push(subMesh);
  24792. }
  24793. else {
  24794. if (material.needDepthPrePass) {
  24795. this._depthOnlySubMeshes.push(subMesh);
  24796. }
  24797. this._opaqueSubMeshes.push(subMesh); // Opaque
  24798. }
  24799. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  24800. this._edgesRenderers.push(mesh._edgesRenderer);
  24801. }
  24802. };
  24803. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  24804. this._spriteManagers.push(spriteManager);
  24805. };
  24806. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  24807. this._particleSystems.push(particleSystem);
  24808. };
  24809. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  24810. if (this._particleSystems.length === 0) {
  24811. return;
  24812. }
  24813. // Particles
  24814. var activeCamera = this._scene.activeCamera;
  24815. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  24816. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  24817. var particleSystem = this._particleSystems.data[particleIndex];
  24818. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  24819. continue;
  24820. }
  24821. var emitter = particleSystem.emitter;
  24822. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  24823. this._scene._activeParticles.addCount(particleSystem.render(), false);
  24824. }
  24825. }
  24826. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  24827. };
  24828. RenderingGroup.prototype._renderSprites = function () {
  24829. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  24830. return;
  24831. }
  24832. // Sprites
  24833. var activeCamera = this._scene.activeCamera;
  24834. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  24835. for (var id = 0; id < this._spriteManagers.length; id++) {
  24836. var spriteManager = this._spriteManagers.data[id];
  24837. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  24838. spriteManager.render();
  24839. }
  24840. }
  24841. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  24842. };
  24843. return RenderingGroup;
  24844. }());
  24845. BABYLON.RenderingGroup = RenderingGroup;
  24846. })(BABYLON || (BABYLON = {}));
  24847. //# sourceMappingURL=babylon.renderingGroup.js.map
  24848. var BABYLON;
  24849. (function (BABYLON) {
  24850. /**
  24851. * Groups all the scene component constants in one place to ease maintenance.
  24852. * @hidden
  24853. */
  24854. var SceneComponentConstants = /** @class */ (function () {
  24855. function SceneComponentConstants() {
  24856. }
  24857. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  24858. SceneComponentConstants.NAME_LAYER = "Layer";
  24859. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  24860. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  24861. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  24862. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  24863. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  24864. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  24865. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  24866. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  24867. SceneComponentConstants.NAME_SPRITE = "Sprite";
  24868. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  24869. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  24870. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  24871. SceneComponentConstants.NAME_OCTREE = "Octree";
  24872. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  24873. SceneComponentConstants.NAME_AUDIO = "Audio";
  24874. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  24875. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24876. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  24877. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24878. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  24879. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  24880. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  24881. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  24882. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  24883. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  24884. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  24885. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  24886. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  24887. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  24888. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  24889. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  24890. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  24891. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  24892. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  24893. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  24894. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  24895. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  24896. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  24897. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  24898. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  24899. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  24900. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  24901. return SceneComponentConstants;
  24902. }());
  24903. BABYLON.SceneComponentConstants = SceneComponentConstants;
  24904. /**
  24905. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  24906. * @hidden
  24907. */
  24908. var Stage = /** @class */ (function (_super) {
  24909. __extends(Stage, _super);
  24910. /**
  24911. * Hide ctor from the rest of the world.
  24912. * @param items The items to add.
  24913. */
  24914. function Stage(items) {
  24915. return _super.apply(this, items) || this;
  24916. }
  24917. /**
  24918. * Creates a new Stage.
  24919. * @returns A new instance of a Stage
  24920. */
  24921. Stage.Create = function () {
  24922. return Object.create(Stage.prototype);
  24923. };
  24924. /**
  24925. * Registers a step in an ordered way in the targeted stage.
  24926. * @param index Defines the position to register the step in
  24927. * @param component Defines the component attached to the step
  24928. * @param action Defines the action to launch during the step
  24929. */
  24930. Stage.prototype.registerStep = function (index, component, action) {
  24931. var i = 0;
  24932. var maxIndex = Number.MAX_VALUE;
  24933. for (; i < this.length; i++) {
  24934. var step = this[i];
  24935. maxIndex = step.index;
  24936. if (index < maxIndex) {
  24937. break;
  24938. }
  24939. }
  24940. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  24941. };
  24942. /**
  24943. * Clears all the steps from the stage.
  24944. */
  24945. Stage.prototype.clear = function () {
  24946. this.length = 0;
  24947. };
  24948. return Stage;
  24949. }(Array));
  24950. BABYLON.Stage = Stage;
  24951. })(BABYLON || (BABYLON = {}));
  24952. //# sourceMappingURL=babylon.sceneComponent.js.map
  24953. var BABYLON;
  24954. (function (BABYLON) {
  24955. /**
  24956. * Base class of the scene acting as a container for the different elements composing a scene.
  24957. * This class is dynamically extended by the different components of the scene increasing
  24958. * flexibility and reducing coupling
  24959. */
  24960. var AbstractScene = /** @class */ (function () {
  24961. function AbstractScene() {
  24962. /**
  24963. * Gets the list of root nodes (ie. nodes with no parent)
  24964. */
  24965. this.rootNodes = new Array();
  24966. /** All of the cameras added to this scene
  24967. * @see http://doc.babylonjs.com/babylon101/cameras
  24968. */
  24969. this.cameras = new Array();
  24970. /**
  24971. * All of the lights added to this scene
  24972. * @see http://doc.babylonjs.com/babylon101/lights
  24973. */
  24974. this.lights = new Array();
  24975. /**
  24976. * All of the (abstract) meshes added to this scene
  24977. */
  24978. this.meshes = new Array();
  24979. /**
  24980. * The list of skeletons added to the scene
  24981. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24982. */
  24983. this.skeletons = new Array();
  24984. /**
  24985. * All of the particle systems added to this scene
  24986. * @see http://doc.babylonjs.com/babylon101/particles
  24987. */
  24988. this.particleSystems = new Array();
  24989. /**
  24990. * Gets a list of Animations associated with the scene
  24991. */
  24992. this.animations = [];
  24993. /**
  24994. * All of the animation groups added to this scene
  24995. * @see http://doc.babylonjs.com/how_to/group
  24996. */
  24997. this.animationGroups = new Array();
  24998. /**
  24999. * All of the multi-materials added to this scene
  25000. * @see http://doc.babylonjs.com/how_to/multi_materials
  25001. */
  25002. this.multiMaterials = new Array();
  25003. /**
  25004. * All of the materials added to this scene
  25005. * @see http://doc.babylonjs.com/babylon101/materials
  25006. */
  25007. this.materials = new Array();
  25008. /**
  25009. * The list of morph target managers added to the scene
  25010. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  25011. */
  25012. this.morphTargetManagers = new Array();
  25013. /**
  25014. * The list of geometries used in the scene.
  25015. */
  25016. this.geometries = new Array();
  25017. /**
  25018. * All of the tranform nodes added to this scene
  25019. * @see http://doc.babylonjs.com/how_to/transformnode
  25020. */
  25021. this.transformNodes = new Array();
  25022. /**
  25023. * ActionManagers available on the scene.
  25024. */
  25025. this.actionManagers = new Array();
  25026. /**
  25027. * Textures to keep.
  25028. */
  25029. this.textures = new Array();
  25030. }
  25031. /**
  25032. * Adds a parser in the list of available ones
  25033. * @param name Defines the name of the parser
  25034. * @param parser Defines the parser to add
  25035. */
  25036. AbstractScene.AddParser = function (name, parser) {
  25037. this._BabylonFileParsers[name] = parser;
  25038. };
  25039. /**
  25040. * Gets a general parser from the list of avaialble ones
  25041. * @param name Defines the name of the parser
  25042. * @returns the requested parser or null
  25043. */
  25044. AbstractScene.GetParser = function (name) {
  25045. if (this._BabylonFileParsers[name]) {
  25046. return this._BabylonFileParsers[name];
  25047. }
  25048. return null;
  25049. };
  25050. /**
  25051. * Adds n individual parser in the list of available ones
  25052. * @param name Defines the name of the parser
  25053. * @param parser Defines the parser to add
  25054. */
  25055. AbstractScene.AddIndividualParser = function (name, parser) {
  25056. this._IndividualBabylonFileParsers[name] = parser;
  25057. };
  25058. /**
  25059. * Gets an individual parser from the list of avaialble ones
  25060. * @param name Defines the name of the parser
  25061. * @returns the requested parser or null
  25062. */
  25063. AbstractScene.GetIndividualParser = function (name) {
  25064. if (this._IndividualBabylonFileParsers[name]) {
  25065. return this._IndividualBabylonFileParsers[name];
  25066. }
  25067. return null;
  25068. };
  25069. /**
  25070. * Parser json data and populate both a scene and its associated container object
  25071. * @param jsonData Defines the data to parse
  25072. * @param scene Defines the scene to parse the data for
  25073. * @param container Defines the container attached to the parsing sequence
  25074. * @param rootUrl Defines the root url of the data
  25075. */
  25076. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  25077. for (var parserName in this._BabylonFileParsers) {
  25078. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  25079. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  25080. }
  25081. }
  25082. };
  25083. /**
  25084. * Stores the list of available parsers in the application.
  25085. */
  25086. AbstractScene._BabylonFileParsers = {};
  25087. /**
  25088. * Stores the list of available individual parsers in the application.
  25089. */
  25090. AbstractScene._IndividualBabylonFileParsers = {};
  25091. return AbstractScene;
  25092. }());
  25093. BABYLON.AbstractScene = AbstractScene;
  25094. })(BABYLON || (BABYLON = {}));
  25095. //# sourceMappingURL=babylon.abstractScene.js.map
  25096. var BABYLON;
  25097. (function (BABYLON) {
  25098. /** @hidden */
  25099. var ClickInfo = /** @class */ (function () {
  25100. function ClickInfo() {
  25101. this._singleClick = false;
  25102. this._doubleClick = false;
  25103. this._hasSwiped = false;
  25104. this._ignore = false;
  25105. }
  25106. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  25107. get: function () {
  25108. return this._singleClick;
  25109. },
  25110. set: function (b) {
  25111. this._singleClick = b;
  25112. },
  25113. enumerable: true,
  25114. configurable: true
  25115. });
  25116. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  25117. get: function () {
  25118. return this._doubleClick;
  25119. },
  25120. set: function (b) {
  25121. this._doubleClick = b;
  25122. },
  25123. enumerable: true,
  25124. configurable: true
  25125. });
  25126. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  25127. get: function () {
  25128. return this._hasSwiped;
  25129. },
  25130. set: function (b) {
  25131. this._hasSwiped = b;
  25132. },
  25133. enumerable: true,
  25134. configurable: true
  25135. });
  25136. Object.defineProperty(ClickInfo.prototype, "ignore", {
  25137. get: function () {
  25138. return this._ignore;
  25139. },
  25140. set: function (b) {
  25141. this._ignore = b;
  25142. },
  25143. enumerable: true,
  25144. configurable: true
  25145. });
  25146. return ClickInfo;
  25147. }());
  25148. /**
  25149. * This class is used by the onRenderingGroupObservable
  25150. */
  25151. var RenderingGroupInfo = /** @class */ (function () {
  25152. function RenderingGroupInfo() {
  25153. }
  25154. return RenderingGroupInfo;
  25155. }());
  25156. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  25157. /**
  25158. * Represents a scene to be rendered by the engine.
  25159. * @see http://doc.babylonjs.com/features/scene
  25160. */
  25161. var Scene = /** @class */ (function (_super) {
  25162. __extends(Scene, _super);
  25163. /**
  25164. * Creates a new Scene
  25165. * @param engine defines the engine to use to render this scene
  25166. */
  25167. function Scene(engine) {
  25168. var _this = _super.call(this) || this;
  25169. // Members
  25170. /**
  25171. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  25172. */
  25173. _this.autoClear = true;
  25174. /**
  25175. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  25176. */
  25177. _this.autoClearDepthAndStencil = true;
  25178. /**
  25179. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  25180. */
  25181. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  25182. /**
  25183. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  25184. */
  25185. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  25186. _this._forceWireframe = false;
  25187. _this._forcePointsCloud = false;
  25188. /**
  25189. * Gets or sets a boolean indicating if animations are enabled
  25190. */
  25191. _this.animationsEnabled = true;
  25192. _this._animationPropertiesOverride = null;
  25193. /**
  25194. * Gets or sets a boolean indicating if a constant deltatime has to be used
  25195. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  25196. */
  25197. _this.useConstantAnimationDeltaTime = false;
  25198. /**
  25199. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  25200. * Please note that it requires to run a ray cast through the scene on every frame
  25201. */
  25202. _this.constantlyUpdateMeshUnderPointer = false;
  25203. /**
  25204. * Defines the HTML cursor to use when hovering over interactive elements
  25205. */
  25206. _this.hoverCursor = "pointer";
  25207. /**
  25208. * Defines the HTML default cursor to use (empty by default)
  25209. */
  25210. _this.defaultCursor = "";
  25211. /**
  25212. * This is used to call preventDefault() on pointer down
  25213. * in order to block unwanted artifacts like system double clicks
  25214. */
  25215. _this.preventDefaultOnPointerDown = true;
  25216. // Metadata
  25217. /**
  25218. * Gets or sets user defined metadata
  25219. */
  25220. _this.metadata = null;
  25221. /**
  25222. * Use this array to add regular expressions used to disable offline support for specific urls
  25223. */
  25224. _this.disableOfflineSupportExceptionRules = new Array();
  25225. /**
  25226. * An event triggered when the scene is disposed.
  25227. */
  25228. _this.onDisposeObservable = new BABYLON.Observable();
  25229. _this._onDisposeObserver = null;
  25230. /**
  25231. * An event triggered before rendering the scene (right after animations and physics)
  25232. */
  25233. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25234. _this._onBeforeRenderObserver = null;
  25235. /**
  25236. * An event triggered after rendering the scene
  25237. */
  25238. _this.onAfterRenderObservable = new BABYLON.Observable();
  25239. _this._onAfterRenderObserver = null;
  25240. /**
  25241. * An event triggered before animating the scene
  25242. */
  25243. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  25244. /**
  25245. * An event triggered after animations processing
  25246. */
  25247. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  25248. /**
  25249. * An event triggered before draw calls are ready to be sent
  25250. */
  25251. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  25252. /**
  25253. * An event triggered after draw calls have been sent
  25254. */
  25255. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  25256. /**
  25257. * An event triggered when the scene is ready
  25258. */
  25259. _this.onReadyObservable = new BABYLON.Observable();
  25260. /**
  25261. * An event triggered before rendering a camera
  25262. */
  25263. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  25264. _this._onBeforeCameraRenderObserver = null;
  25265. /**
  25266. * An event triggered after rendering a camera
  25267. */
  25268. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  25269. _this._onAfterCameraRenderObserver = null;
  25270. /**
  25271. * An event triggered when active meshes evaluation is about to start
  25272. */
  25273. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25274. /**
  25275. * An event triggered when active meshes evaluation is done
  25276. */
  25277. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25278. /**
  25279. * An event triggered when particles rendering is about to start
  25280. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25281. */
  25282. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  25283. /**
  25284. * An event triggered when particles rendering is done
  25285. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25286. */
  25287. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  25288. /**
  25289. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  25290. */
  25291. _this.onDataLoadedObservable = new BABYLON.Observable();
  25292. /**
  25293. * An event triggered when a camera is created
  25294. */
  25295. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  25296. /**
  25297. * An event triggered when a camera is removed
  25298. */
  25299. _this.onCameraRemovedObservable = new BABYLON.Observable();
  25300. /**
  25301. * An event triggered when a light is created
  25302. */
  25303. _this.onNewLightAddedObservable = new BABYLON.Observable();
  25304. /**
  25305. * An event triggered when a light is removed
  25306. */
  25307. _this.onLightRemovedObservable = new BABYLON.Observable();
  25308. /**
  25309. * An event triggered when a geometry is created
  25310. */
  25311. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  25312. /**
  25313. * An event triggered when a geometry is removed
  25314. */
  25315. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  25316. /**
  25317. * An event triggered when a transform node is created
  25318. */
  25319. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  25320. /**
  25321. * An event triggered when a transform node is removed
  25322. */
  25323. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  25324. /**
  25325. * An event triggered when a mesh is created
  25326. */
  25327. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  25328. /**
  25329. * An event triggered when a mesh is removed
  25330. */
  25331. _this.onMeshRemovedObservable = new BABYLON.Observable();
  25332. /**
  25333. * An event triggered when a material is created
  25334. */
  25335. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  25336. /**
  25337. * An event triggered when a material is removed
  25338. */
  25339. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  25340. /**
  25341. * An event triggered when a texture is created
  25342. */
  25343. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  25344. /**
  25345. * An event triggered when a texture is removed
  25346. */
  25347. _this.onTextureRemovedObservable = new BABYLON.Observable();
  25348. /**
  25349. * An event triggered when render targets are about to be rendered
  25350. * Can happen multiple times per frame.
  25351. */
  25352. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  25353. /**
  25354. * An event triggered when render targets were rendered.
  25355. * Can happen multiple times per frame.
  25356. */
  25357. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  25358. /**
  25359. * An event triggered before calculating deterministic simulation step
  25360. */
  25361. _this.onBeforeStepObservable = new BABYLON.Observable();
  25362. /**
  25363. * An event triggered after calculating deterministic simulation step
  25364. */
  25365. _this.onAfterStepObservable = new BABYLON.Observable();
  25366. /**
  25367. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  25368. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25369. * 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)
  25370. */
  25371. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  25372. /**
  25373. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  25374. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25375. * 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)
  25376. */
  25377. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  25378. /**
  25379. * This Observable will when a mesh has been imported into the scene.
  25380. */
  25381. _this.onMeshImportedObservable = new BABYLON.Observable();
  25382. // Animations
  25383. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  25384. /**
  25385. * 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).
  25386. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  25387. */
  25388. _this.onPrePointerObservable = new BABYLON.Observable();
  25389. /**
  25390. * Observable event triggered each time an input event is received from the rendering canvas
  25391. */
  25392. _this.onPointerObservable = new BABYLON.Observable();
  25393. _this._meshPickProceed = false;
  25394. _this._currentPickResult = null;
  25395. _this._previousPickResult = null;
  25396. _this._totalPointersPressed = 0;
  25397. _this._doubleClickOccured = false;
  25398. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  25399. _this.cameraToUseForPointers = null;
  25400. _this._pointerX = 0;
  25401. _this._pointerY = 0;
  25402. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  25403. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  25404. _this._startingPointerTime = 0;
  25405. _this._previousStartingPointerTime = 0;
  25406. _this._pointerCaptures = {};
  25407. // Deterministic lockstep
  25408. _this._timeAccumulator = 0;
  25409. _this._currentStepId = 0;
  25410. _this._currentInternalStep = 0;
  25411. // Keyboard
  25412. /**
  25413. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  25414. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  25415. */
  25416. _this.onPreKeyboardObservable = new BABYLON.Observable();
  25417. /**
  25418. * Observable event triggered each time an keyboard event is received from the hosting window
  25419. */
  25420. _this.onKeyboardObservable = new BABYLON.Observable();
  25421. // Coordinates system
  25422. _this._useRightHandedSystem = false;
  25423. // Fog
  25424. _this._fogEnabled = true;
  25425. _this._fogMode = Scene.FOGMODE_NONE;
  25426. /**
  25427. * Gets or sets the fog color to use
  25428. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25429. * (Default is Color3(0.2, 0.2, 0.3))
  25430. */
  25431. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  25432. /**
  25433. * Gets or sets the fog density to use
  25434. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25435. * (Default is 0.1)
  25436. */
  25437. _this.fogDensity = 0.1;
  25438. /**
  25439. * Gets or sets the fog start distance to use
  25440. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25441. * (Default is 0)
  25442. */
  25443. _this.fogStart = 0;
  25444. /**
  25445. * Gets or sets the fog end distance to use
  25446. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25447. * (Default is 1000)
  25448. */
  25449. _this.fogEnd = 1000.0;
  25450. // Lights
  25451. _this._shadowsEnabled = true;
  25452. _this._lightsEnabled = true;
  25453. /** All of the active cameras added to this scene. */
  25454. _this.activeCameras = new Array();
  25455. // Textures
  25456. _this._texturesEnabled = true;
  25457. // Particles
  25458. /**
  25459. * Gets or sets a boolean indicating if particles are enabled on this scene
  25460. */
  25461. _this.particlesEnabled = true;
  25462. // Sprites
  25463. /**
  25464. * Gets or sets a boolean indicating if sprites are enabled on this scene
  25465. */
  25466. _this.spritesEnabled = true;
  25467. // Skeletons
  25468. _this._skeletonsEnabled = true;
  25469. // Lens flares
  25470. /**
  25471. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  25472. */
  25473. _this.lensFlaresEnabled = true;
  25474. // Collisions
  25475. /**
  25476. * Gets or sets a boolean indicating if collisions are enabled on this scene
  25477. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25478. */
  25479. _this.collisionsEnabled = true;
  25480. /**
  25481. * Defines the gravity applied to this scene (used only for collisions)
  25482. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25483. */
  25484. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  25485. // Postprocesses
  25486. /**
  25487. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  25488. */
  25489. _this.postProcessesEnabled = true;
  25490. /**
  25491. * The list of postprocesses added to the scene
  25492. */
  25493. _this.postProcesses = new Array();
  25494. // Customs render targets
  25495. /**
  25496. * Gets or sets a boolean indicating if render targets are enabled on this scene
  25497. */
  25498. _this.renderTargetsEnabled = true;
  25499. /**
  25500. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  25501. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  25502. */
  25503. _this.dumpNextRenderTargets = false;
  25504. /**
  25505. * The list of user defined render targets added to the scene
  25506. */
  25507. _this.customRenderTargets = new Array();
  25508. /**
  25509. * Gets the list of meshes imported to the scene through SceneLoader
  25510. */
  25511. _this.importedMeshesFiles = new Array();
  25512. // Probes
  25513. /**
  25514. * Gets or sets a boolean indicating if probes are enabled on this scene
  25515. */
  25516. _this.probesEnabled = true;
  25517. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  25518. // Procedural textures
  25519. /**
  25520. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  25521. */
  25522. _this.proceduralTexturesEnabled = true;
  25523. // Performance counters
  25524. _this._totalVertices = new BABYLON.PerfCounter();
  25525. /** @hidden */
  25526. _this._activeIndices = new BABYLON.PerfCounter();
  25527. /** @hidden */
  25528. _this._activeParticles = new BABYLON.PerfCounter();
  25529. /** @hidden */
  25530. _this._activeBones = new BABYLON.PerfCounter();
  25531. _this._animationTime = 0;
  25532. /**
  25533. * Gets or sets a general scale for animation speed
  25534. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  25535. */
  25536. _this.animationTimeScale = 1;
  25537. _this._renderId = 0;
  25538. _this._frameId = 0;
  25539. _this._executeWhenReadyTimeoutId = -1;
  25540. _this._intermediateRendering = false;
  25541. _this._viewUpdateFlag = -1;
  25542. _this._projectionUpdateFlag = -1;
  25543. _this._alternateViewUpdateFlag = -1;
  25544. _this._alternateProjectionUpdateFlag = -1;
  25545. /** @hidden */
  25546. _this._toBeDisposed = new Array(256);
  25547. _this._activeRequests = new Array();
  25548. _this._pendingData = new Array();
  25549. _this._isDisposed = false;
  25550. /**
  25551. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  25552. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  25553. */
  25554. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  25555. _this._activeMeshes = new BABYLON.SmartArray(256);
  25556. _this._processedMaterials = new BABYLON.SmartArray(256);
  25557. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  25558. /** @hidden */
  25559. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  25560. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  25561. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  25562. /** @hidden */
  25563. _this._activeAnimatables = new Array();
  25564. _this._transformMatrix = BABYLON.Matrix.Zero();
  25565. _this._useAlternateCameraConfiguration = false;
  25566. _this._alternateRendering = false;
  25567. /**
  25568. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  25569. * This is useful if there are more lights that the maximum simulteanous authorized
  25570. */
  25571. _this.requireLightSorting = false;
  25572. /**
  25573. * @hidden
  25574. * Backing store of defined scene components.
  25575. */
  25576. _this._components = [];
  25577. /**
  25578. * @hidden
  25579. * Backing store of defined scene components.
  25580. */
  25581. _this._serializableComponents = [];
  25582. /**
  25583. * List of components to register on the next registration step.
  25584. */
  25585. _this._transientComponents = [];
  25586. /**
  25587. * @hidden
  25588. * Defines the actions happening before camera updates.
  25589. */
  25590. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  25591. /**
  25592. * @hidden
  25593. * Defines the actions happening before clear the canvas.
  25594. */
  25595. _this._beforeClearStage = BABYLON.Stage.Create();
  25596. /**
  25597. * @hidden
  25598. * Defines the actions when collecting render targets for the frame.
  25599. */
  25600. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  25601. /**
  25602. * @hidden
  25603. * Defines the actions happening for one camera in the frame.
  25604. */
  25605. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  25606. /**
  25607. * @hidden
  25608. * Defines the actions happening during the per mesh ready checks.
  25609. */
  25610. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  25611. /**
  25612. * @hidden
  25613. * Defines the actions happening before evaluate active mesh checks.
  25614. */
  25615. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  25616. /**
  25617. * @hidden
  25618. * Defines the actions happening during the evaluate sub mesh checks.
  25619. */
  25620. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  25621. /**
  25622. * @hidden
  25623. * Defines the actions happening during the active mesh stage.
  25624. */
  25625. _this._activeMeshStage = BABYLON.Stage.Create();
  25626. /**
  25627. * @hidden
  25628. * Defines the actions happening during the per camera render target step.
  25629. */
  25630. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  25631. /**
  25632. * @hidden
  25633. * Defines the actions happening just before the active camera is drawing.
  25634. */
  25635. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  25636. /**
  25637. * @hidden
  25638. * Defines the actions happening just before a rendering group is drawing.
  25639. */
  25640. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  25641. /**
  25642. * @hidden
  25643. * Defines the actions happening just before a mesh is drawing.
  25644. */
  25645. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  25646. /**
  25647. * @hidden
  25648. * Defines the actions happening just after a mesh has been drawn.
  25649. */
  25650. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  25651. /**
  25652. * @hidden
  25653. * Defines the actions happening just after a rendering group has been drawn.
  25654. */
  25655. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  25656. /**
  25657. * @hidden
  25658. * Defines the actions happening just after the active camera has been drawn.
  25659. */
  25660. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  25661. /**
  25662. * @hidden
  25663. * Defines the actions happening just after rendering all cameras and computing intersections.
  25664. */
  25665. _this._afterRenderStage = BABYLON.Stage.Create();
  25666. /**
  25667. * @hidden
  25668. * Defines the actions happening when a pointer move event happens.
  25669. */
  25670. _this._pointerMoveStage = BABYLON.Stage.Create();
  25671. /**
  25672. * @hidden
  25673. * Defines the actions happening when a pointer down event happens.
  25674. */
  25675. _this._pointerDownStage = BABYLON.Stage.Create();
  25676. /**
  25677. * @hidden
  25678. * Defines the actions happening when a pointer up event happens.
  25679. */
  25680. _this._pointerUpStage = BABYLON.Stage.Create();
  25681. _this._defaultMeshCandidates = {
  25682. data: [],
  25683. length: 0
  25684. };
  25685. _this._defaultSubMeshCandidates = {
  25686. data: [],
  25687. length: 0
  25688. };
  25689. _this._activeMeshesFrozen = false;
  25690. /** @hidden */
  25691. _this._allowPostProcessClearColor = true;
  25692. /**
  25693. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  25694. */
  25695. _this.getDeterministicFrameTime = function () {
  25696. return 1000.0 / 60.0; // frame time in ms
  25697. };
  25698. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  25699. _this._blockMaterialDirtyMechanism = false;
  25700. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  25701. _this._engine.scenes.push(_this);
  25702. _this._uid = null;
  25703. _this._renderingManager = new BABYLON.RenderingManager(_this);
  25704. if (BABYLON.PostProcessManager) {
  25705. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  25706. }
  25707. if (BABYLON.Tools.IsWindowObjectExist()) {
  25708. _this.attachControl();
  25709. }
  25710. //collision coordinator initialization. For now legacy per default.
  25711. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  25712. // Uniform Buffer
  25713. _this._createUbo();
  25714. // Default Image processing definition
  25715. if (BABYLON.ImageProcessingConfiguration) {
  25716. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  25717. }
  25718. _this.setDefaultCandidateProviders();
  25719. return _this;
  25720. }
  25721. Object.defineProperty(Scene.prototype, "environmentTexture", {
  25722. /**
  25723. * Texture used in all pbr material as the reflection texture.
  25724. * As in the majority of the scene they are the same (exception for multi room and so on),
  25725. * this is easier to reference from here than from all the materials.
  25726. */
  25727. get: function () {
  25728. return this._environmentTexture;
  25729. },
  25730. /**
  25731. * Texture used in all pbr material as the reflection texture.
  25732. * As in the majority of the scene they are the same (exception for multi room and so on),
  25733. * this is easier to set here than in all the materials.
  25734. */
  25735. set: function (value) {
  25736. if (this._environmentTexture === value) {
  25737. return;
  25738. }
  25739. this._environmentTexture = value;
  25740. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25741. },
  25742. enumerable: true,
  25743. configurable: true
  25744. });
  25745. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  25746. /**
  25747. * Default image processing configuration used either in the rendering
  25748. * Forward main pass or through the imageProcessingPostProcess if present.
  25749. * As in the majority of the scene they are the same (exception for multi camera),
  25750. * this is easier to reference from here than from all the materials and post process.
  25751. *
  25752. * No setter as we it is a shared configuration, you can set the values instead.
  25753. */
  25754. get: function () {
  25755. return this._imageProcessingConfiguration;
  25756. },
  25757. enumerable: true,
  25758. configurable: true
  25759. });
  25760. Object.defineProperty(Scene.prototype, "forceWireframe", {
  25761. get: function () {
  25762. return this._forceWireframe;
  25763. },
  25764. /**
  25765. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  25766. */
  25767. set: function (value) {
  25768. if (this._forceWireframe === value) {
  25769. return;
  25770. }
  25771. this._forceWireframe = value;
  25772. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25773. },
  25774. enumerable: true,
  25775. configurable: true
  25776. });
  25777. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  25778. get: function () {
  25779. return this._forcePointsCloud;
  25780. },
  25781. /**
  25782. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  25783. */
  25784. set: function (value) {
  25785. if (this._forcePointsCloud === value) {
  25786. return;
  25787. }
  25788. this._forcePointsCloud = value;
  25789. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25790. },
  25791. enumerable: true,
  25792. configurable: true
  25793. });
  25794. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  25795. /**
  25796. * Gets or sets the animation properties override
  25797. */
  25798. get: function () {
  25799. return this._animationPropertiesOverride;
  25800. },
  25801. set: function (value) {
  25802. this._animationPropertiesOverride = value;
  25803. },
  25804. enumerable: true,
  25805. configurable: true
  25806. });
  25807. Object.defineProperty(Scene.prototype, "onDispose", {
  25808. /** Sets a function to be executed when this scene is disposed. */
  25809. set: function (callback) {
  25810. if (this._onDisposeObserver) {
  25811. this.onDisposeObservable.remove(this._onDisposeObserver);
  25812. }
  25813. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25814. },
  25815. enumerable: true,
  25816. configurable: true
  25817. });
  25818. Object.defineProperty(Scene.prototype, "beforeRender", {
  25819. /** Sets a function to be executed before rendering this scene */
  25820. set: function (callback) {
  25821. if (this._onBeforeRenderObserver) {
  25822. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  25823. }
  25824. if (callback) {
  25825. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  25826. }
  25827. },
  25828. enumerable: true,
  25829. configurable: true
  25830. });
  25831. Object.defineProperty(Scene.prototype, "afterRender", {
  25832. /** Sets a function to be executed after rendering this scene */
  25833. set: function (callback) {
  25834. if (this._onAfterRenderObserver) {
  25835. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  25836. }
  25837. if (callback) {
  25838. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  25839. }
  25840. },
  25841. enumerable: true,
  25842. configurable: true
  25843. });
  25844. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  25845. /** Sets a function to be executed before rendering a camera*/
  25846. set: function (callback) {
  25847. if (this._onBeforeCameraRenderObserver) {
  25848. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  25849. }
  25850. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  25851. },
  25852. enumerable: true,
  25853. configurable: true
  25854. });
  25855. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  25856. /** Sets a function to be executed after rendering a camera*/
  25857. set: function (callback) {
  25858. if (this._onAfterCameraRenderObserver) {
  25859. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  25860. }
  25861. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  25862. },
  25863. enumerable: true,
  25864. configurable: true
  25865. });
  25866. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  25867. /**
  25868. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  25869. */
  25870. get: function () {
  25871. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  25872. },
  25873. enumerable: true,
  25874. configurable: true
  25875. });
  25876. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  25877. get: function () {
  25878. return this._useRightHandedSystem;
  25879. },
  25880. /**
  25881. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  25882. */
  25883. set: function (value) {
  25884. if (this._useRightHandedSystem === value) {
  25885. return;
  25886. }
  25887. this._useRightHandedSystem = value;
  25888. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25889. },
  25890. enumerable: true,
  25891. configurable: true
  25892. });
  25893. /**
  25894. * Sets the step Id used by deterministic lock step
  25895. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25896. * @param newStepId defines the step Id
  25897. */
  25898. Scene.prototype.setStepId = function (newStepId) {
  25899. this._currentStepId = newStepId;
  25900. };
  25901. /**
  25902. * Gets the step Id used by deterministic lock step
  25903. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25904. * @returns the step Id
  25905. */
  25906. Scene.prototype.getStepId = function () {
  25907. return this._currentStepId;
  25908. };
  25909. /**
  25910. * Gets the internal step used by deterministic lock step
  25911. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25912. * @returns the internal step
  25913. */
  25914. Scene.prototype.getInternalStep = function () {
  25915. return this._currentInternalStep;
  25916. };
  25917. Object.defineProperty(Scene.prototype, "fogEnabled", {
  25918. get: function () {
  25919. return this._fogEnabled;
  25920. },
  25921. /**
  25922. * Gets or sets a boolean indicating if fog is enabled on this scene
  25923. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25924. * (Default is true)
  25925. */
  25926. set: function (value) {
  25927. if (this._fogEnabled === value) {
  25928. return;
  25929. }
  25930. this._fogEnabled = value;
  25931. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25932. },
  25933. enumerable: true,
  25934. configurable: true
  25935. });
  25936. Object.defineProperty(Scene.prototype, "fogMode", {
  25937. get: function () {
  25938. return this._fogMode;
  25939. },
  25940. /**
  25941. * Gets or sets the fog mode to use
  25942. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25943. * | mode | value |
  25944. * | --- | --- |
  25945. * | FOGMODE_NONE | 0 |
  25946. * | FOGMODE_EXP | 1 |
  25947. * | FOGMODE_EXP2 | 2 |
  25948. * | FOGMODE_LINEAR | 3 |
  25949. */
  25950. set: function (value) {
  25951. if (this._fogMode === value) {
  25952. return;
  25953. }
  25954. this._fogMode = value;
  25955. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25956. },
  25957. enumerable: true,
  25958. configurable: true
  25959. });
  25960. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  25961. get: function () {
  25962. return this._shadowsEnabled;
  25963. },
  25964. /**
  25965. * Gets or sets a boolean indicating if shadows are enabled on this scene
  25966. */
  25967. set: function (value) {
  25968. if (this._shadowsEnabled === value) {
  25969. return;
  25970. }
  25971. this._shadowsEnabled = value;
  25972. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25973. },
  25974. enumerable: true,
  25975. configurable: true
  25976. });
  25977. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  25978. get: function () {
  25979. return this._lightsEnabled;
  25980. },
  25981. /**
  25982. * Gets or sets a boolean indicating if lights are enabled on this scene
  25983. */
  25984. set: function (value) {
  25985. if (this._lightsEnabled === value) {
  25986. return;
  25987. }
  25988. this._lightsEnabled = value;
  25989. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25990. },
  25991. enumerable: true,
  25992. configurable: true
  25993. });
  25994. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  25995. /** The default material used on meshes when no material is affected */
  25996. get: function () {
  25997. if (!this._defaultMaterial) {
  25998. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  25999. }
  26000. return this._defaultMaterial;
  26001. },
  26002. /** The default material used on meshes when no material is affected */
  26003. set: function (value) {
  26004. this._defaultMaterial = value;
  26005. },
  26006. enumerable: true,
  26007. configurable: true
  26008. });
  26009. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  26010. get: function () {
  26011. return this._texturesEnabled;
  26012. },
  26013. /**
  26014. * Gets or sets a boolean indicating if textures are enabled on this scene
  26015. */
  26016. set: function (value) {
  26017. if (this._texturesEnabled === value) {
  26018. return;
  26019. }
  26020. this._texturesEnabled = value;
  26021. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26022. },
  26023. enumerable: true,
  26024. configurable: true
  26025. });
  26026. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  26027. get: function () {
  26028. return this._skeletonsEnabled;
  26029. },
  26030. /**
  26031. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  26032. */
  26033. set: function (value) {
  26034. if (this._skeletonsEnabled === value) {
  26035. return;
  26036. }
  26037. this._skeletonsEnabled = value;
  26038. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  26039. },
  26040. enumerable: true,
  26041. configurable: true
  26042. });
  26043. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  26044. /** @hidden */
  26045. get: function () {
  26046. return this._alternateRendering;
  26047. },
  26048. enumerable: true,
  26049. configurable: true
  26050. });
  26051. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  26052. /**
  26053. * Gets the list of frustum planes (built from the active camera)
  26054. */
  26055. get: function () {
  26056. return this._frustumPlanes;
  26057. },
  26058. enumerable: true,
  26059. configurable: true
  26060. });
  26061. /**
  26062. * Registers the transient components if needed.
  26063. */
  26064. Scene.prototype._registerTransientComponents = function () {
  26065. // Register components that have been associated lately to the scene.
  26066. if (this._transientComponents.length > 0) {
  26067. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  26068. var component = _a[_i];
  26069. component.register();
  26070. }
  26071. this._transientComponents = [];
  26072. }
  26073. };
  26074. /**
  26075. * @hidden
  26076. * Add a component to the scene.
  26077. * Note that the ccomponent could be registered on th next frame if this is called after
  26078. * the register component stage.
  26079. * @param component Defines the component to add to the scene
  26080. */
  26081. Scene.prototype._addComponent = function (component) {
  26082. this._components.push(component);
  26083. this._transientComponents.push(component);
  26084. var serializableComponent = component;
  26085. if (serializableComponent.addFromContainer) {
  26086. this._serializableComponents.push(serializableComponent);
  26087. }
  26088. };
  26089. /**
  26090. * @hidden
  26091. * Gets a component from the scene.
  26092. * @param name defines the name of the component to retrieve
  26093. * @returns the component or null if not present
  26094. */
  26095. Scene.prototype._getComponent = function (name) {
  26096. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  26097. var component = _a[_i];
  26098. if (component.name === name) {
  26099. return component;
  26100. }
  26101. }
  26102. return null;
  26103. };
  26104. /**
  26105. * @hidden
  26106. */
  26107. Scene.prototype._getDefaultMeshCandidates = function () {
  26108. this._defaultMeshCandidates.data = this.meshes;
  26109. this._defaultMeshCandidates.length = this.meshes.length;
  26110. return this._defaultMeshCandidates;
  26111. };
  26112. /**
  26113. * @hidden
  26114. */
  26115. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  26116. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  26117. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  26118. return this._defaultSubMeshCandidates;
  26119. };
  26120. /**
  26121. * Sets the default candidate providers for the scene.
  26122. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  26123. * and getCollidingSubMeshCandidates to their default function
  26124. */
  26125. Scene.prototype.setDefaultCandidateProviders = function () {
  26126. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  26127. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26128. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26129. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26130. };
  26131. Object.defineProperty(Scene.prototype, "workerCollisions", {
  26132. /**
  26133. * Gets a boolean indicating if collisions are processed on a web worker
  26134. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  26135. */
  26136. get: function () {
  26137. return this._workerCollisions;
  26138. },
  26139. set: function (enabled) {
  26140. if (!BABYLON.CollisionCoordinatorLegacy) {
  26141. return;
  26142. }
  26143. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  26144. this._workerCollisions = enabled;
  26145. if (this.collisionCoordinator) {
  26146. this.collisionCoordinator.destroy();
  26147. }
  26148. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  26149. this.collisionCoordinator.init(this);
  26150. },
  26151. enumerable: true,
  26152. configurable: true
  26153. });
  26154. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  26155. /**
  26156. * Gets the mesh that is currently under the pointer
  26157. */
  26158. get: function () {
  26159. return this._pointerOverMesh;
  26160. },
  26161. enumerable: true,
  26162. configurable: true
  26163. });
  26164. Object.defineProperty(Scene.prototype, "pointerX", {
  26165. /**
  26166. * Gets the current on-screen X position of the pointer
  26167. */
  26168. get: function () {
  26169. return this._pointerX;
  26170. },
  26171. enumerable: true,
  26172. configurable: true
  26173. });
  26174. Object.defineProperty(Scene.prototype, "pointerY", {
  26175. /**
  26176. * Gets the current on-screen Y position of the pointer
  26177. */
  26178. get: function () {
  26179. return this._pointerY;
  26180. },
  26181. enumerable: true,
  26182. configurable: true
  26183. });
  26184. /**
  26185. * Gets the cached material (ie. the latest rendered one)
  26186. * @returns the cached material
  26187. */
  26188. Scene.prototype.getCachedMaterial = function () {
  26189. return this._cachedMaterial;
  26190. };
  26191. /**
  26192. * Gets the cached effect (ie. the latest rendered one)
  26193. * @returns the cached effect
  26194. */
  26195. Scene.prototype.getCachedEffect = function () {
  26196. return this._cachedEffect;
  26197. };
  26198. /**
  26199. * Gets the cached visibility state (ie. the latest rendered one)
  26200. * @returns the cached visibility state
  26201. */
  26202. Scene.prototype.getCachedVisibility = function () {
  26203. return this._cachedVisibility;
  26204. };
  26205. /**
  26206. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  26207. * @param material defines the current material
  26208. * @param effect defines the current effect
  26209. * @param visibility defines the current visibility state
  26210. * @returns true if one parameter is not cached
  26211. */
  26212. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  26213. if (visibility === void 0) { visibility = 1; }
  26214. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  26215. };
  26216. /**
  26217. * Gets the engine associated with the scene
  26218. * @returns an Engine
  26219. */
  26220. Scene.prototype.getEngine = function () {
  26221. return this._engine;
  26222. };
  26223. /**
  26224. * Gets the total number of vertices rendered per frame
  26225. * @returns the total number of vertices rendered per frame
  26226. */
  26227. Scene.prototype.getTotalVertices = function () {
  26228. return this._totalVertices.current;
  26229. };
  26230. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  26231. /**
  26232. * Gets the performance counter for total vertices
  26233. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26234. */
  26235. get: function () {
  26236. return this._totalVertices;
  26237. },
  26238. enumerable: true,
  26239. configurable: true
  26240. });
  26241. /**
  26242. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  26243. * @returns the total number of active indices rendered per frame
  26244. */
  26245. Scene.prototype.getActiveIndices = function () {
  26246. return this._activeIndices.current;
  26247. };
  26248. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  26249. /**
  26250. * Gets the performance counter for active indices
  26251. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26252. */
  26253. get: function () {
  26254. return this._activeIndices;
  26255. },
  26256. enumerable: true,
  26257. configurable: true
  26258. });
  26259. /**
  26260. * Gets the total number of active particles rendered per frame
  26261. * @returns the total number of active particles rendered per frame
  26262. */
  26263. Scene.prototype.getActiveParticles = function () {
  26264. return this._activeParticles.current;
  26265. };
  26266. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  26267. /**
  26268. * Gets the performance counter for active particles
  26269. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26270. */
  26271. get: function () {
  26272. return this._activeParticles;
  26273. },
  26274. enumerable: true,
  26275. configurable: true
  26276. });
  26277. /**
  26278. * Gets the total number of active bones rendered per frame
  26279. * @returns the total number of active bones rendered per frame
  26280. */
  26281. Scene.prototype.getActiveBones = function () {
  26282. return this._activeBones.current;
  26283. };
  26284. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  26285. /**
  26286. * Gets the performance counter for active bones
  26287. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26288. */
  26289. get: function () {
  26290. return this._activeBones;
  26291. },
  26292. enumerable: true,
  26293. configurable: true
  26294. });
  26295. /** @hidden */
  26296. Scene.prototype.getInterFramePerfCounter = function () {
  26297. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26298. return 0;
  26299. };
  26300. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  26301. /** @hidden */
  26302. get: function () {
  26303. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26304. return null;
  26305. },
  26306. enumerable: true,
  26307. configurable: true
  26308. });
  26309. /** @hidden */
  26310. Scene.prototype.getLastFrameDuration = function () {
  26311. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  26312. return 0;
  26313. };
  26314. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  26315. /** @hidden */
  26316. get: function () {
  26317. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26318. return null;
  26319. },
  26320. enumerable: true,
  26321. configurable: true
  26322. });
  26323. /** @hidden */
  26324. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  26325. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  26326. return 0;
  26327. };
  26328. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  26329. /** @hidden */
  26330. get: function () {
  26331. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26332. return null;
  26333. },
  26334. enumerable: true,
  26335. configurable: true
  26336. });
  26337. /**
  26338. * Gets the array of active meshes
  26339. * @returns an array of AbstractMesh
  26340. */
  26341. Scene.prototype.getActiveMeshes = function () {
  26342. return this._activeMeshes;
  26343. };
  26344. /** @hidden */
  26345. Scene.prototype.getRenderTargetsDuration = function () {
  26346. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  26347. return 0;
  26348. };
  26349. /** @hidden */
  26350. Scene.prototype.getRenderDuration = function () {
  26351. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  26352. return 0;
  26353. };
  26354. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  26355. /** @hidden */
  26356. get: function () {
  26357. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26358. return null;
  26359. },
  26360. enumerable: true,
  26361. configurable: true
  26362. });
  26363. /** @hidden */
  26364. Scene.prototype.getParticlesDuration = function () {
  26365. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  26366. return 0;
  26367. };
  26368. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  26369. /** @hidden */
  26370. get: function () {
  26371. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26372. return null;
  26373. },
  26374. enumerable: true,
  26375. configurable: true
  26376. });
  26377. /** @hidden */
  26378. Scene.prototype.getSpritesDuration = function () {
  26379. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  26380. return 0;
  26381. };
  26382. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  26383. /** @hidden */
  26384. get: function () {
  26385. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  26386. return null;
  26387. },
  26388. enumerable: true,
  26389. configurable: true
  26390. });
  26391. /**
  26392. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  26393. * @returns a number
  26394. */
  26395. Scene.prototype.getAnimationRatio = function () {
  26396. return this._animationRatio !== undefined ? this._animationRatio : 1;
  26397. };
  26398. /**
  26399. * Gets an unique Id for the current render phase
  26400. * @returns a number
  26401. */
  26402. Scene.prototype.getRenderId = function () {
  26403. return this._renderId;
  26404. };
  26405. /**
  26406. * Gets an unique Id for the current frame
  26407. * @returns a number
  26408. */
  26409. Scene.prototype.getFrameId = function () {
  26410. return this._frameId;
  26411. };
  26412. /** Call this function if you want to manually increment the render Id*/
  26413. Scene.prototype.incrementRenderId = function () {
  26414. this._renderId++;
  26415. };
  26416. Scene.prototype._updatePointerPosition = function (evt) {
  26417. var canvasRect = this._engine.getRenderingCanvasClientRect();
  26418. if (!canvasRect) {
  26419. return;
  26420. }
  26421. this._pointerX = evt.clientX - canvasRect.left;
  26422. this._pointerY = evt.clientY - canvasRect.top;
  26423. this._unTranslatedPointerX = this._pointerX;
  26424. this._unTranslatedPointerY = this._pointerY;
  26425. };
  26426. Scene.prototype._createUbo = function () {
  26427. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26428. this._sceneUbo.addUniform("viewProjection", 16);
  26429. this._sceneUbo.addUniform("view", 16);
  26430. };
  26431. Scene.prototype._createAlternateUbo = function () {
  26432. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26433. this._alternateSceneUbo.addUniform("viewProjection", 16);
  26434. this._alternateSceneUbo.addUniform("view", 16);
  26435. };
  26436. // Pointers handling
  26437. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  26438. if (pointerInfo.pickInfo) {
  26439. if (!pointerInfo.pickInfo.ray) {
  26440. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  26441. }
  26442. }
  26443. };
  26444. /**
  26445. * Use this method to simulate a pointer move on a mesh
  26446. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26447. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26448. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26449. * @returns the current scene
  26450. */
  26451. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  26452. var evt = new PointerEvent("pointermove", pointerEventInit);
  26453. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  26454. return this;
  26455. }
  26456. return this._processPointerMove(pickResult, evt);
  26457. };
  26458. Scene.prototype._processPointerMove = function (pickResult, evt) {
  26459. var canvas = this._engine.getRenderingCanvas();
  26460. if (!canvas) {
  26461. return this;
  26462. }
  26463. // Restore pointer
  26464. canvas.style.cursor = this.defaultCursor;
  26465. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  26466. if (isMeshPicked) {
  26467. this.setPointerOverMesh(pickResult.pickedMesh);
  26468. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  26469. if (this._pointerOverMesh.actionManager.hoverCursor) {
  26470. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  26471. }
  26472. else {
  26473. canvas.style.cursor = this.hoverCursor;
  26474. }
  26475. }
  26476. }
  26477. else {
  26478. this.setPointerOverMesh(null);
  26479. }
  26480. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  26481. var step = _a[_i];
  26482. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  26483. }
  26484. if (pickResult) {
  26485. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  26486. if (this.onPointerMove) {
  26487. this.onPointerMove(evt, pickResult, type);
  26488. }
  26489. if (this.onPointerObservable.hasObservers()) {
  26490. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26491. this._setRayOnPointerInfo(pi);
  26492. this.onPointerObservable.notifyObservers(pi, type);
  26493. }
  26494. }
  26495. return this;
  26496. };
  26497. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  26498. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  26499. if (pickResult) {
  26500. pi.ray = pickResult.ray;
  26501. }
  26502. this.onPrePointerObservable.notifyObservers(pi, type);
  26503. if (pi.skipOnPointerObservable) {
  26504. return true;
  26505. }
  26506. else {
  26507. return false;
  26508. }
  26509. };
  26510. /**
  26511. * Use this method to simulate a pointer down on a mesh
  26512. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26513. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26514. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26515. * @returns the current scene
  26516. */
  26517. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  26518. var evt = new PointerEvent("pointerdown", pointerEventInit);
  26519. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26520. return this;
  26521. }
  26522. return this._processPointerDown(pickResult, evt);
  26523. };
  26524. Scene.prototype._processPointerDown = function (pickResult, evt) {
  26525. var _this = this;
  26526. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  26527. this._pickedDownMesh = pickResult.pickedMesh;
  26528. var actionManager = pickResult.pickedMesh.actionManager;
  26529. if (actionManager) {
  26530. if (actionManager.hasPickTriggers) {
  26531. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26532. switch (evt.button) {
  26533. case 0:
  26534. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26535. break;
  26536. case 1:
  26537. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26538. break;
  26539. case 2:
  26540. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26541. break;
  26542. }
  26543. }
  26544. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  26545. window.setTimeout(function () {
  26546. 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);
  26547. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  26548. if (_this._totalPointersPressed !== 0 &&
  26549. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  26550. !_this._isPointerSwiping()) {
  26551. _this._startingPointerTime = 0;
  26552. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26553. }
  26554. }
  26555. }, Scene.LongPressDelay);
  26556. }
  26557. }
  26558. }
  26559. else {
  26560. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  26561. var step = _a[_i];
  26562. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26563. }
  26564. }
  26565. if (pickResult) {
  26566. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  26567. if (this.onPointerDown) {
  26568. this.onPointerDown(evt, pickResult, type);
  26569. }
  26570. if (this.onPointerObservable.hasObservers()) {
  26571. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26572. this._setRayOnPointerInfo(pi);
  26573. this.onPointerObservable.notifyObservers(pi, type);
  26574. }
  26575. }
  26576. return this;
  26577. };
  26578. /**
  26579. * Use this method to simulate a pointer up on a mesh
  26580. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26581. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26582. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26583. * @returns the current scene
  26584. */
  26585. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  26586. var evt = new PointerEvent("pointerup", pointerEventInit);
  26587. var clickInfo = new ClickInfo();
  26588. clickInfo.singleClick = true;
  26589. clickInfo.ignore = true;
  26590. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26591. return this;
  26592. }
  26593. return this._processPointerUp(pickResult, evt, clickInfo);
  26594. };
  26595. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  26596. if (pickResult && pickResult && pickResult.pickedMesh) {
  26597. this._pickedUpMesh = pickResult.pickedMesh;
  26598. if (this._pickedDownMesh === this._pickedUpMesh) {
  26599. if (this.onPointerPick) {
  26600. this.onPointerPick(evt, pickResult);
  26601. }
  26602. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  26603. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  26604. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  26605. this._setRayOnPointerInfo(pi);
  26606. this.onPointerObservable.notifyObservers(pi, type_1);
  26607. }
  26608. }
  26609. if (pickResult.pickedMesh.actionManager) {
  26610. if (clickInfo.ignore) {
  26611. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26612. }
  26613. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  26614. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26615. }
  26616. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26617. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26618. }
  26619. }
  26620. }
  26621. else {
  26622. if (!clickInfo.ignore) {
  26623. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  26624. var step = _a[_i];
  26625. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26626. }
  26627. }
  26628. }
  26629. if (this._pickedDownMesh &&
  26630. this._pickedDownMesh.actionManager &&
  26631. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  26632. this._pickedDownMesh !== this._pickedUpMesh) {
  26633. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  26634. }
  26635. var type = BABYLON.PointerEventTypes.POINTERUP;
  26636. if (this.onPointerObservable.hasObservers()) {
  26637. if (!clickInfo.ignore) {
  26638. if (!clickInfo.hasSwiped) {
  26639. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26640. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  26641. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  26642. this._setRayOnPointerInfo(pi);
  26643. this.onPointerObservable.notifyObservers(pi, type_2);
  26644. }
  26645. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26646. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  26647. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  26648. this._setRayOnPointerInfo(pi);
  26649. this.onPointerObservable.notifyObservers(pi, type_3);
  26650. }
  26651. }
  26652. }
  26653. else {
  26654. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26655. this._setRayOnPointerInfo(pi);
  26656. this.onPointerObservable.notifyObservers(pi, type);
  26657. }
  26658. }
  26659. if (this.onPointerUp) {
  26660. this.onPointerUp(evt, pickResult, type);
  26661. }
  26662. return this;
  26663. };
  26664. /**
  26665. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  26666. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  26667. * @returns true if the pointer was captured
  26668. */
  26669. Scene.prototype.isPointerCaptured = function (pointerId) {
  26670. if (pointerId === void 0) { pointerId = 0; }
  26671. return this._pointerCaptures[pointerId];
  26672. };
  26673. /** @hidden */
  26674. Scene.prototype._isPointerSwiping = function () {
  26675. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  26676. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  26677. };
  26678. /**
  26679. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  26680. * @param attachUp defines if you want to attach events to pointerup
  26681. * @param attachDown defines if you want to attach events to pointerdown
  26682. * @param attachMove defines if you want to attach events to pointermove
  26683. */
  26684. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  26685. var _this = this;
  26686. if (attachUp === void 0) { attachUp = true; }
  26687. if (attachDown === void 0) { attachDown = true; }
  26688. if (attachMove === void 0) { attachMove = true; }
  26689. this._initActionManager = function (act, clickInfo) {
  26690. if (!_this._meshPickProceed) {
  26691. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26692. _this._currentPickResult = pickResult;
  26693. if (pickResult) {
  26694. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  26695. }
  26696. _this._meshPickProceed = true;
  26697. }
  26698. return act;
  26699. };
  26700. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  26701. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  26702. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  26703. btn !== _this._previousButtonPressed) {
  26704. _this._doubleClickOccured = false;
  26705. clickInfo.singleClick = true;
  26706. clickInfo.ignore = false;
  26707. cb(clickInfo, _this._currentPickResult);
  26708. }
  26709. };
  26710. this._initClickEvent = function (obs1, obs2, evt, cb) {
  26711. var clickInfo = new ClickInfo();
  26712. _this._currentPickResult = null;
  26713. var act = null;
  26714. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  26715. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  26716. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26717. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  26718. act = _this._initActionManager(act, clickInfo);
  26719. if (act) {
  26720. checkPicking = act.hasPickTriggers;
  26721. }
  26722. }
  26723. if (checkPicking) {
  26724. var btn = evt.button;
  26725. clickInfo.hasSwiped = _this._isPointerSwiping();
  26726. if (!clickInfo.hasSwiped) {
  26727. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  26728. if (!checkSingleClickImmediately) {
  26729. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  26730. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26731. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26732. act = _this._initActionManager(act, clickInfo);
  26733. if (act) {
  26734. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26735. }
  26736. }
  26737. }
  26738. if (checkSingleClickImmediately) {
  26739. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  26740. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  26741. btn !== _this._previousButtonPressed) {
  26742. clickInfo.singleClick = true;
  26743. cb(clickInfo, _this._currentPickResult);
  26744. }
  26745. }
  26746. // at least one double click is required to be check and exclusive double click is enabled
  26747. else {
  26748. // wait that no double click has been raised during the double click delay
  26749. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26750. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  26751. }
  26752. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  26753. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26754. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26755. act = _this._initActionManager(act, clickInfo);
  26756. if (act) {
  26757. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26758. }
  26759. }
  26760. if (checkDoubleClick) {
  26761. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  26762. if (btn === _this._previousButtonPressed &&
  26763. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  26764. !_this._doubleClickOccured) {
  26765. // pointer has not moved for 2 clicks, it's a double click
  26766. if (!clickInfo.hasSwiped &&
  26767. !_this._isPointerSwiping()) {
  26768. _this._previousStartingPointerTime = 0;
  26769. _this._doubleClickOccured = true;
  26770. clickInfo.doubleClick = true;
  26771. clickInfo.ignore = false;
  26772. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  26773. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26774. }
  26775. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26776. cb(clickInfo, _this._currentPickResult);
  26777. }
  26778. // if the two successive clicks are too far, it's just two simple clicks
  26779. else {
  26780. _this._doubleClickOccured = false;
  26781. _this._previousStartingPointerTime = _this._startingPointerTime;
  26782. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26783. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26784. _this._previousButtonPressed = btn;
  26785. if (Scene.ExclusiveDoubleClickMode) {
  26786. if (_this._previousDelayedSimpleClickTimeout) {
  26787. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26788. }
  26789. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26790. cb(clickInfo, _this._previousPickResult);
  26791. }
  26792. else {
  26793. cb(clickInfo, _this._currentPickResult);
  26794. }
  26795. }
  26796. }
  26797. // just the first click of the double has been raised
  26798. else {
  26799. _this._doubleClickOccured = false;
  26800. _this._previousStartingPointerTime = _this._startingPointerTime;
  26801. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26802. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26803. _this._previousButtonPressed = btn;
  26804. }
  26805. }
  26806. }
  26807. }
  26808. clickInfo.ignore = true;
  26809. cb(clickInfo, _this._currentPickResult);
  26810. };
  26811. this._onPointerMove = function (evt) {
  26812. _this._updatePointerPosition(evt);
  26813. // PreObservable support
  26814. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  26815. return;
  26816. }
  26817. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26818. return;
  26819. }
  26820. if (!_this.pointerMovePredicate) {
  26821. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  26822. }
  26823. // Meshes
  26824. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  26825. _this._processPointerMove(pickResult, evt);
  26826. };
  26827. this._onPointerDown = function (evt) {
  26828. _this._totalPointersPressed++;
  26829. _this._pickedDownMesh = null;
  26830. _this._meshPickProceed = false;
  26831. _this._updatePointerPosition(evt);
  26832. if (_this.preventDefaultOnPointerDown && canvas) {
  26833. evt.preventDefault();
  26834. canvas.focus();
  26835. }
  26836. // PreObservable support
  26837. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26838. return;
  26839. }
  26840. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26841. return;
  26842. }
  26843. _this._pointerCaptures[evt.pointerId] = true;
  26844. _this._startingPointerPosition.x = _this._pointerX;
  26845. _this._startingPointerPosition.y = _this._pointerY;
  26846. _this._startingPointerTime = Date.now();
  26847. if (!_this.pointerDownPredicate) {
  26848. _this.pointerDownPredicate = function (mesh) {
  26849. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26850. };
  26851. }
  26852. // Meshes
  26853. _this._pickedDownMesh = null;
  26854. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26855. _this._processPointerDown(pickResult, evt);
  26856. };
  26857. this._onPointerUp = function (evt) {
  26858. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  26859. return; // So we need to test it the pointer down was pressed before.
  26860. }
  26861. _this._totalPointersPressed--;
  26862. _this._pickedUpMesh = null;
  26863. _this._meshPickProceed = false;
  26864. _this._updatePointerPosition(evt);
  26865. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  26866. // PreObservable support
  26867. if (_this.onPrePointerObservable.hasObservers()) {
  26868. if (!clickInfo.ignore) {
  26869. if (!clickInfo.hasSwiped) {
  26870. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26871. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  26872. return;
  26873. }
  26874. }
  26875. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26876. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26877. return;
  26878. }
  26879. }
  26880. }
  26881. }
  26882. else {
  26883. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26884. return;
  26885. }
  26886. }
  26887. }
  26888. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26889. return;
  26890. }
  26891. _this._pointerCaptures[evt.pointerId] = false;
  26892. if (!_this.pointerUpPredicate) {
  26893. _this.pointerUpPredicate = function (mesh) {
  26894. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26895. };
  26896. }
  26897. // Meshes
  26898. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  26899. _this._initActionManager(null, clickInfo);
  26900. }
  26901. if (!pickResult) {
  26902. pickResult = _this._currentPickResult;
  26903. }
  26904. _this._processPointerUp(pickResult, evt, clickInfo);
  26905. _this._previousPickResult = _this._currentPickResult;
  26906. });
  26907. };
  26908. this._onKeyDown = function (evt) {
  26909. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  26910. if (_this.onPreKeyboardObservable.hasObservers()) {
  26911. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26912. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26913. if (pi.skipOnPointerObservable) {
  26914. return;
  26915. }
  26916. }
  26917. if (_this.onKeyboardObservable.hasObservers()) {
  26918. var pi = new BABYLON.KeyboardInfo(type, evt);
  26919. _this.onKeyboardObservable.notifyObservers(pi, type);
  26920. }
  26921. if (_this.actionManager) {
  26922. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26923. }
  26924. };
  26925. this._onKeyUp = function (evt) {
  26926. var type = BABYLON.KeyboardEventTypes.KEYUP;
  26927. if (_this.onPreKeyboardObservable.hasObservers()) {
  26928. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26929. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26930. if (pi.skipOnPointerObservable) {
  26931. return;
  26932. }
  26933. }
  26934. if (_this.onKeyboardObservable.hasObservers()) {
  26935. var pi = new BABYLON.KeyboardInfo(type, evt);
  26936. _this.onKeyboardObservable.notifyObservers(pi, type);
  26937. }
  26938. if (_this.actionManager) {
  26939. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26940. }
  26941. };
  26942. var engine = this.getEngine();
  26943. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  26944. if (!canvas) {
  26945. return;
  26946. }
  26947. canvas.addEventListener("keydown", _this._onKeyDown, false);
  26948. canvas.addEventListener("keyup", _this._onKeyUp, false);
  26949. });
  26950. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  26951. if (!canvas) {
  26952. return;
  26953. }
  26954. canvas.removeEventListener("keydown", _this._onKeyDown);
  26955. canvas.removeEventListener("keyup", _this._onKeyUp);
  26956. });
  26957. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26958. var canvas = this._engine.getRenderingCanvas();
  26959. if (!canvas) {
  26960. return;
  26961. }
  26962. if (attachMove) {
  26963. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  26964. // Wheel
  26965. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  26966. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  26967. }
  26968. if (attachDown) {
  26969. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  26970. }
  26971. if (attachUp) {
  26972. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  26973. }
  26974. canvas.tabIndex = 1;
  26975. };
  26976. /** Detaches all event handlers*/
  26977. Scene.prototype.detachControl = function () {
  26978. var engine = this.getEngine();
  26979. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26980. var canvas = engine.getRenderingCanvas();
  26981. if (!canvas) {
  26982. return;
  26983. }
  26984. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  26985. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  26986. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  26987. if (this._onCanvasBlurObserver) {
  26988. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  26989. }
  26990. if (this._onCanvasFocusObserver) {
  26991. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  26992. }
  26993. // Wheel
  26994. canvas.removeEventListener('mousewheel', this._onPointerMove);
  26995. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  26996. // Keyboard
  26997. canvas.removeEventListener("keydown", this._onKeyDown);
  26998. canvas.removeEventListener("keyup", this._onKeyUp);
  26999. // Observables
  27000. this.onKeyboardObservable.clear();
  27001. this.onPreKeyboardObservable.clear();
  27002. this.onPointerObservable.clear();
  27003. this.onPrePointerObservable.clear();
  27004. };
  27005. /**
  27006. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  27007. * Delay loaded resources are not taking in account
  27008. * @return true if all required resources are ready
  27009. */
  27010. Scene.prototype.isReady = function () {
  27011. if (this._isDisposed) {
  27012. return false;
  27013. }
  27014. if (this._pendingData.length > 0) {
  27015. return false;
  27016. }
  27017. var index;
  27018. var engine = this.getEngine();
  27019. // Geometries
  27020. for (index = 0; index < this.geometries.length; index++) {
  27021. var geometry = this.geometries[index];
  27022. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27023. return false;
  27024. }
  27025. }
  27026. // Meshes
  27027. for (index = 0; index < this.meshes.length; index++) {
  27028. var mesh = this.meshes[index];
  27029. if (!mesh.isEnabled()) {
  27030. continue;
  27031. }
  27032. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  27033. continue;
  27034. }
  27035. if (!mesh.isReady(true)) {
  27036. return false;
  27037. }
  27038. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  27039. // Is Ready For Mesh
  27040. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  27041. var step = _a[_i];
  27042. if (!step.action(mesh, hardwareInstancedRendering)) {
  27043. return false;
  27044. }
  27045. }
  27046. }
  27047. // Post-processes
  27048. if (this.activeCameras && this.activeCameras.length > 0) {
  27049. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  27050. var camera = _c[_b];
  27051. if (!camera.isReady(true)) {
  27052. return false;
  27053. }
  27054. }
  27055. }
  27056. else if (this.activeCamera) {
  27057. if (!this.activeCamera.isReady(true)) {
  27058. return false;
  27059. }
  27060. }
  27061. // Particles
  27062. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  27063. var particleSystem = _e[_d];
  27064. if (!particleSystem.isReady()) {
  27065. return false;
  27066. }
  27067. }
  27068. return true;
  27069. };
  27070. /** Resets all cached information relative to material (including effect and visibility) */
  27071. Scene.prototype.resetCachedMaterial = function () {
  27072. this._cachedMaterial = null;
  27073. this._cachedEffect = null;
  27074. this._cachedVisibility = null;
  27075. };
  27076. /**
  27077. * Registers a function to be called before every frame render
  27078. * @param func defines the function to register
  27079. */
  27080. Scene.prototype.registerBeforeRender = function (func) {
  27081. this.onBeforeRenderObservable.add(func);
  27082. };
  27083. /**
  27084. * Unregisters a function called before every frame render
  27085. * @param func defines the function to unregister
  27086. */
  27087. Scene.prototype.unregisterBeforeRender = function (func) {
  27088. this.onBeforeRenderObservable.removeCallback(func);
  27089. };
  27090. /**
  27091. * Registers a function to be called after every frame render
  27092. * @param func defines the function to register
  27093. */
  27094. Scene.prototype.registerAfterRender = function (func) {
  27095. this.onAfterRenderObservable.add(func);
  27096. };
  27097. /**
  27098. * Unregisters a function called after every frame render
  27099. * @param func defines the function to unregister
  27100. */
  27101. Scene.prototype.unregisterAfterRender = function (func) {
  27102. this.onAfterRenderObservable.removeCallback(func);
  27103. };
  27104. Scene.prototype._executeOnceBeforeRender = function (func) {
  27105. var _this = this;
  27106. var execFunc = function () {
  27107. func();
  27108. setTimeout(function () {
  27109. _this.unregisterBeforeRender(execFunc);
  27110. });
  27111. };
  27112. this.registerBeforeRender(execFunc);
  27113. };
  27114. /**
  27115. * The provided function will run before render once and will be disposed afterwards.
  27116. * A timeout delay can be provided so that the function will be executed in N ms.
  27117. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  27118. * @param func The function to be executed.
  27119. * @param timeout optional delay in ms
  27120. */
  27121. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  27122. var _this = this;
  27123. if (timeout !== undefined) {
  27124. setTimeout(function () {
  27125. _this._executeOnceBeforeRender(func);
  27126. }, timeout);
  27127. }
  27128. else {
  27129. this._executeOnceBeforeRender(func);
  27130. }
  27131. };
  27132. /** @hidden */
  27133. Scene.prototype._addPendingData = function (data) {
  27134. this._pendingData.push(data);
  27135. };
  27136. /** @hidden */
  27137. Scene.prototype._removePendingData = function (data) {
  27138. var wasLoading = this.isLoading;
  27139. var index = this._pendingData.indexOf(data);
  27140. if (index !== -1) {
  27141. this._pendingData.splice(index, 1);
  27142. }
  27143. if (wasLoading && !this.isLoading) {
  27144. this.onDataLoadedObservable.notifyObservers(this);
  27145. }
  27146. };
  27147. /**
  27148. * Returns the number of items waiting to be loaded
  27149. * @returns the number of items waiting to be loaded
  27150. */
  27151. Scene.prototype.getWaitingItemsCount = function () {
  27152. return this._pendingData.length;
  27153. };
  27154. Object.defineProperty(Scene.prototype, "isLoading", {
  27155. /**
  27156. * Returns a boolean indicating if the scene is still loading data
  27157. */
  27158. get: function () {
  27159. return this._pendingData.length > 0;
  27160. },
  27161. enumerable: true,
  27162. configurable: true
  27163. });
  27164. /**
  27165. * Registers a function to be executed when the scene is ready
  27166. * @param {Function} func - the function to be executed
  27167. */
  27168. Scene.prototype.executeWhenReady = function (func) {
  27169. var _this = this;
  27170. this.onReadyObservable.add(func);
  27171. if (this._executeWhenReadyTimeoutId !== -1) {
  27172. return;
  27173. }
  27174. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27175. _this._checkIsReady();
  27176. }, 150);
  27177. };
  27178. /**
  27179. * Returns a promise that resolves when the scene is ready
  27180. * @returns A promise that resolves when the scene is ready
  27181. */
  27182. Scene.prototype.whenReadyAsync = function () {
  27183. var _this = this;
  27184. return new Promise(function (resolve) {
  27185. _this.executeWhenReady(function () {
  27186. resolve();
  27187. });
  27188. });
  27189. };
  27190. /** @hidden */
  27191. Scene.prototype._checkIsReady = function () {
  27192. var _this = this;
  27193. this._registerTransientComponents();
  27194. if (this.isReady()) {
  27195. this.onReadyObservable.notifyObservers(this);
  27196. this.onReadyObservable.clear();
  27197. this._executeWhenReadyTimeoutId = -1;
  27198. return;
  27199. }
  27200. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27201. _this._checkIsReady();
  27202. }, 150);
  27203. };
  27204. // Animations
  27205. /**
  27206. * Will start the animation sequence of a given target
  27207. * @param target defines the target
  27208. * @param from defines from which frame should animation start
  27209. * @param to defines until which frame should animation run.
  27210. * @param weight defines the weight to apply to the animation (1.0 by default)
  27211. * @param loop defines if the animation loops
  27212. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27213. * @param onAnimationEnd defines the function to be executed when the animation ends
  27214. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27215. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27216. * @returns the animatable object created for this animation
  27217. */
  27218. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  27219. if (weight === void 0) { weight = 1.0; }
  27220. if (speedRatio === void 0) { speedRatio = 1.0; }
  27221. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  27222. returnedAnimatable.weight = weight;
  27223. return returnedAnimatable;
  27224. };
  27225. /**
  27226. * Will start the animation sequence of a given target
  27227. * @param target defines the target
  27228. * @param from defines from which frame should animation start
  27229. * @param to defines until which frame should animation run.
  27230. * @param loop defines if the animation loops
  27231. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27232. * @param onAnimationEnd defines the function to be executed when the animation ends
  27233. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27234. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  27235. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27236. * @returns the animatable object created for this animation
  27237. */
  27238. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  27239. if (speedRatio === void 0) { speedRatio = 1.0; }
  27240. if (stopCurrent === void 0) { stopCurrent = true; }
  27241. if (from > to && speedRatio > 0) {
  27242. speedRatio *= -1;
  27243. }
  27244. if (stopCurrent) {
  27245. this.stopAnimation(target, undefined, targetMask);
  27246. }
  27247. if (!animatable) {
  27248. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  27249. }
  27250. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  27251. // Local animations
  27252. if (target.animations && shouldRunTargetAnimations) {
  27253. animatable.appendAnimations(target, target.animations);
  27254. }
  27255. // Children animations
  27256. if (target.getAnimatables) {
  27257. var animatables = target.getAnimatables();
  27258. for (var index = 0; index < animatables.length; index++) {
  27259. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  27260. }
  27261. }
  27262. animatable.reset();
  27263. return animatable;
  27264. };
  27265. /**
  27266. * Begin a new animation on a given node
  27267. * @param target defines the target where the animation will take place
  27268. * @param animations defines the list of animations to start
  27269. * @param from defines the initial value
  27270. * @param to defines the final value
  27271. * @param loop defines if you want animation to loop (off by default)
  27272. * @param speedRatio defines the speed ratio to apply to all animations
  27273. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27274. * @returns the list of created animatables
  27275. */
  27276. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27277. if (speedRatio === undefined) {
  27278. speedRatio = 1.0;
  27279. }
  27280. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  27281. return animatable;
  27282. };
  27283. /**
  27284. * Begin a new animation on a given node and its hierarchy
  27285. * @param target defines the root node where the animation will take place
  27286. * @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.
  27287. * @param animations defines the list of animations to start
  27288. * @param from defines the initial value
  27289. * @param to defines the final value
  27290. * @param loop defines if you want animation to loop (off by default)
  27291. * @param speedRatio defines the speed ratio to apply to all animations
  27292. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27293. * @returns the list of animatables created for all nodes
  27294. */
  27295. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27296. var children = target.getDescendants(directDescendantsOnly);
  27297. var result = [];
  27298. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  27299. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  27300. var child = children_1[_i];
  27301. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  27302. }
  27303. return result;
  27304. };
  27305. /**
  27306. * Gets the animatable associated with a specific target
  27307. * @param target defines the target of the animatable
  27308. * @returns the required animatable if found
  27309. */
  27310. Scene.prototype.getAnimatableByTarget = function (target) {
  27311. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27312. if (this._activeAnimatables[index].target === target) {
  27313. return this._activeAnimatables[index];
  27314. }
  27315. }
  27316. return null;
  27317. };
  27318. /**
  27319. * Gets all animatables associated with a given target
  27320. * @param target defines the target to look animatables for
  27321. * @returns an array of Animatables
  27322. */
  27323. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  27324. var result = [];
  27325. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27326. if (this._activeAnimatables[index].target === target) {
  27327. result.push(this._activeAnimatables[index]);
  27328. }
  27329. }
  27330. return result;
  27331. };
  27332. Object.defineProperty(Scene.prototype, "animatables", {
  27333. /**
  27334. * Gets all animatable attached to the scene
  27335. */
  27336. get: function () {
  27337. return this._activeAnimatables;
  27338. },
  27339. enumerable: true,
  27340. configurable: true
  27341. });
  27342. /**
  27343. * Will stop the animation of the given target
  27344. * @param target - the target
  27345. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  27346. * @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)
  27347. */
  27348. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  27349. var animatables = this.getAllAnimatablesByTarget(target);
  27350. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  27351. var animatable = animatables_1[_i];
  27352. animatable.stop(animationName, targetMask);
  27353. }
  27354. };
  27355. /**
  27356. * Stops and removes all animations that have been applied to the scene
  27357. */
  27358. Scene.prototype.stopAllAnimations = function () {
  27359. if (this._activeAnimatables) {
  27360. for (var i = 0; i < this._activeAnimatables.length; i++) {
  27361. this._activeAnimatables[i].stop();
  27362. }
  27363. this._activeAnimatables = [];
  27364. }
  27365. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  27366. var group = _a[_i];
  27367. group.stop();
  27368. }
  27369. };
  27370. Scene.prototype._animate = function () {
  27371. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  27372. return;
  27373. }
  27374. // Getting time
  27375. var now = BABYLON.Tools.Now;
  27376. if (!this._animationTimeLast) {
  27377. if (this._pendingData.length > 0) {
  27378. return;
  27379. }
  27380. this._animationTimeLast = now;
  27381. }
  27382. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  27383. this._animationTime += deltaTime;
  27384. this._animationTimeLast = now;
  27385. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27386. this._activeAnimatables[index]._animate(this._animationTime);
  27387. }
  27388. // Late animation bindings
  27389. this._processLateAnimationBindings();
  27390. };
  27391. /** @hidden */
  27392. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  27393. var target = runtimeAnimation.target;
  27394. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  27395. if (!target._lateAnimationHolders) {
  27396. target._lateAnimationHolders = {};
  27397. }
  27398. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  27399. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  27400. totalWeight: 0,
  27401. animations: [],
  27402. originalValue: originalValue
  27403. };
  27404. }
  27405. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  27406. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  27407. };
  27408. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  27409. var normalizer = 1.0;
  27410. var finalPosition = BABYLON.Tmp.Vector3[0];
  27411. var finalScaling = BABYLON.Tmp.Vector3[1];
  27412. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  27413. var startIndex = 0;
  27414. var originalAnimation = holder.animations[0];
  27415. var originalValue = holder.originalValue;
  27416. var scale = 1;
  27417. if (holder.totalWeight < 1.0) {
  27418. // We need to mix the original value in
  27419. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27420. scale = 1.0 - holder.totalWeight;
  27421. }
  27422. else {
  27423. startIndex = 1;
  27424. // We need to normalize the weights
  27425. normalizer = holder.totalWeight;
  27426. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27427. scale = originalAnimation.weight / normalizer;
  27428. if (scale == 1) {
  27429. return originalAnimation.currentValue;
  27430. }
  27431. }
  27432. finalScaling.scaleInPlace(scale);
  27433. finalPosition.scaleInPlace(scale);
  27434. finalQuaternion.scaleInPlace(scale);
  27435. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27436. var runtimeAnimation = holder.animations[animIndex];
  27437. var scale = runtimeAnimation.weight / normalizer;
  27438. var currentPosition = BABYLON.Tmp.Vector3[2];
  27439. var currentScaling = BABYLON.Tmp.Vector3[3];
  27440. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  27441. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  27442. currentScaling.scaleAndAddToRef(scale, finalScaling);
  27443. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  27444. currentPosition.scaleAndAddToRef(scale, finalPosition);
  27445. }
  27446. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  27447. return originalAnimation._workValue;
  27448. };
  27449. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  27450. var originalAnimation = holder.animations[0];
  27451. var originalValue = holder.originalValue;
  27452. if (holder.animations.length === 1) {
  27453. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  27454. return refQuaternion;
  27455. }
  27456. var normalizer = 1.0;
  27457. var quaternions;
  27458. var weights;
  27459. if (holder.totalWeight < 1.0) {
  27460. var scale = 1.0 - holder.totalWeight;
  27461. quaternions = [];
  27462. weights = [];
  27463. quaternions.push(originalValue);
  27464. weights.push(scale);
  27465. }
  27466. else {
  27467. if (holder.animations.length === 2) { // Slerp as soon as we can
  27468. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  27469. return refQuaternion;
  27470. }
  27471. quaternions = [];
  27472. weights = [];
  27473. normalizer = holder.totalWeight;
  27474. }
  27475. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  27476. var runtimeAnimation = holder.animations[animIndex];
  27477. quaternions.push(runtimeAnimation.currentValue);
  27478. weights.push(runtimeAnimation.weight / normalizer);
  27479. }
  27480. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  27481. var cumulativeAmount = 0;
  27482. var cumulativeQuaternion = null;
  27483. for (var index = 0; index < quaternions.length;) {
  27484. if (!cumulativeQuaternion) {
  27485. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  27486. cumulativeQuaternion = refQuaternion;
  27487. cumulativeAmount = weights[index] + weights[index + 1];
  27488. index += 2;
  27489. continue;
  27490. }
  27491. cumulativeAmount += weights[index];
  27492. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  27493. index++;
  27494. }
  27495. return cumulativeQuaternion;
  27496. };
  27497. Scene.prototype._processLateAnimationBindings = function () {
  27498. if (!this._registeredForLateAnimationBindings.length) {
  27499. return;
  27500. }
  27501. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  27502. var target = this._registeredForLateAnimationBindings.data[index];
  27503. for (var path in target._lateAnimationHolders) {
  27504. var holder = target._lateAnimationHolders[path];
  27505. var originalAnimation = holder.animations[0];
  27506. var originalValue = holder.originalValue;
  27507. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  27508. var finalValue = target[path];
  27509. if (matrixDecomposeMode) {
  27510. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  27511. }
  27512. else {
  27513. var quaternionMode = originalValue.w !== undefined;
  27514. if (quaternionMode) {
  27515. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  27516. }
  27517. else {
  27518. var startIndex = 0;
  27519. var normalizer = 1.0;
  27520. if (holder.totalWeight < 1.0) {
  27521. // We need to mix the original value in
  27522. if (originalValue.scale) {
  27523. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  27524. }
  27525. else {
  27526. finalValue = originalValue * (1.0 - holder.totalWeight);
  27527. }
  27528. }
  27529. else {
  27530. // We need to normalize the weights
  27531. normalizer = holder.totalWeight;
  27532. var scale_1 = originalAnimation.weight / normalizer;
  27533. if (scale_1 !== 1) {
  27534. if (originalAnimation.currentValue.scale) {
  27535. finalValue = originalAnimation.currentValue.scale(scale_1);
  27536. }
  27537. else {
  27538. finalValue = originalAnimation.currentValue * scale_1;
  27539. }
  27540. }
  27541. else {
  27542. finalValue = originalAnimation.currentValue;
  27543. }
  27544. startIndex = 1;
  27545. }
  27546. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27547. var runtimeAnimation = holder.animations[animIndex];
  27548. var scale = runtimeAnimation.weight / normalizer;
  27549. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  27550. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  27551. }
  27552. else {
  27553. finalValue += runtimeAnimation.currentValue * scale;
  27554. }
  27555. }
  27556. }
  27557. }
  27558. target[path] = finalValue;
  27559. }
  27560. target._lateAnimationHolders = {};
  27561. }
  27562. this._registeredForLateAnimationBindings.reset();
  27563. };
  27564. // Matrix
  27565. /** @hidden */
  27566. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  27567. this._useAlternateCameraConfiguration = active;
  27568. };
  27569. /**
  27570. * Gets the current view matrix
  27571. * @returns a Matrix
  27572. */
  27573. Scene.prototype.getViewMatrix = function () {
  27574. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  27575. };
  27576. /**
  27577. * Gets the current projection matrix
  27578. * @returns a Matrix
  27579. */
  27580. Scene.prototype.getProjectionMatrix = function () {
  27581. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  27582. };
  27583. /**
  27584. * Gets the current transform matrix
  27585. * @returns a Matrix made of View * Projection
  27586. */
  27587. Scene.prototype.getTransformMatrix = function () {
  27588. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  27589. };
  27590. /**
  27591. * Sets the current transform matrix
  27592. * @param view defines the View matrix to use
  27593. * @param projection defines the Projection matrix to use
  27594. */
  27595. Scene.prototype.setTransformMatrix = function (view, projection) {
  27596. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  27597. return;
  27598. }
  27599. this._viewUpdateFlag = view.updateFlag;
  27600. this._projectionUpdateFlag = projection.updateFlag;
  27601. this._viewMatrix = view;
  27602. this._projectionMatrix = projection;
  27603. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  27604. // Update frustum
  27605. if (!this._frustumPlanes) {
  27606. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  27607. }
  27608. else {
  27609. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  27610. }
  27611. if (this.activeCamera && this.activeCamera._alternateCamera) {
  27612. var otherCamera = this.activeCamera._alternateCamera;
  27613. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  27614. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  27615. }
  27616. if (this._sceneUbo.useUbo) {
  27617. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  27618. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  27619. this._sceneUbo.update();
  27620. }
  27621. };
  27622. /** @hidden */
  27623. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  27624. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  27625. return;
  27626. }
  27627. this._alternateViewUpdateFlag = view.updateFlag;
  27628. this._alternateProjectionUpdateFlag = projection.updateFlag;
  27629. this._alternateViewMatrix = view;
  27630. this._alternateProjectionMatrix = projection;
  27631. if (!this._alternateTransformMatrix) {
  27632. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  27633. }
  27634. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  27635. if (!this._alternateSceneUbo) {
  27636. this._createAlternateUbo();
  27637. }
  27638. if (this._alternateSceneUbo.useUbo) {
  27639. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  27640. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  27641. this._alternateSceneUbo.update();
  27642. }
  27643. };
  27644. /**
  27645. * Gets the uniform buffer used to store scene data
  27646. * @returns a UniformBuffer
  27647. */
  27648. Scene.prototype.getSceneUniformBuffer = function () {
  27649. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  27650. };
  27651. /**
  27652. * Gets an unique (relatively to the current scene) Id
  27653. * @returns an unique number for the scene
  27654. */
  27655. Scene.prototype.getUniqueId = function () {
  27656. var result = Scene._uniqueIdCounter;
  27657. Scene._uniqueIdCounter++;
  27658. return result;
  27659. };
  27660. /**
  27661. * Add a mesh to the list of scene's meshes
  27662. * @param newMesh defines the mesh to add
  27663. * @param recursive if all child meshes should also be added to the scene
  27664. */
  27665. Scene.prototype.addMesh = function (newMesh, recursive) {
  27666. var _this = this;
  27667. if (recursive === void 0) { recursive = false; }
  27668. this.meshes.push(newMesh);
  27669. //notify the collision coordinator
  27670. if (this.collisionCoordinator) {
  27671. this.collisionCoordinator.onMeshAdded(newMesh);
  27672. }
  27673. newMesh._resyncLightSources();
  27674. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  27675. if (recursive) {
  27676. newMesh.getChildMeshes().forEach(function (m) {
  27677. _this.addMesh(m);
  27678. });
  27679. }
  27680. };
  27681. /**
  27682. * Remove a mesh for the list of scene's meshes
  27683. * @param toRemove defines the mesh to remove
  27684. * @param recursive if all child meshes should also be removed from the scene
  27685. * @returns the index where the mesh was in the mesh list
  27686. */
  27687. Scene.prototype.removeMesh = function (toRemove, recursive) {
  27688. var _this = this;
  27689. if (recursive === void 0) { recursive = false; }
  27690. var index = this.meshes.indexOf(toRemove);
  27691. if (index !== -1) {
  27692. // Remove from the scene if mesh found
  27693. this.meshes.splice(index, 1);
  27694. }
  27695. this.onMeshRemovedObservable.notifyObservers(toRemove);
  27696. if (recursive) {
  27697. toRemove.getChildMeshes().forEach(function (m) {
  27698. _this.removeMesh(m);
  27699. });
  27700. }
  27701. return index;
  27702. };
  27703. /**
  27704. * Add a transform node to the list of scene's transform nodes
  27705. * @param newTransformNode defines the transform node to add
  27706. */
  27707. Scene.prototype.addTransformNode = function (newTransformNode) {
  27708. this.transformNodes.push(newTransformNode);
  27709. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  27710. };
  27711. /**
  27712. * Remove a transform node for the list of scene's transform nodes
  27713. * @param toRemove defines the transform node to remove
  27714. * @returns the index where the transform node was in the transform node list
  27715. */
  27716. Scene.prototype.removeTransformNode = function (toRemove) {
  27717. var index = this.transformNodes.indexOf(toRemove);
  27718. if (index !== -1) {
  27719. // Remove from the scene if found
  27720. this.transformNodes.splice(index, 1);
  27721. }
  27722. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  27723. return index;
  27724. };
  27725. /**
  27726. * Remove a skeleton for the list of scene's skeletons
  27727. * @param toRemove defines the skeleton to remove
  27728. * @returns the index where the skeleton was in the skeleton list
  27729. */
  27730. Scene.prototype.removeSkeleton = function (toRemove) {
  27731. var index = this.skeletons.indexOf(toRemove);
  27732. if (index !== -1) {
  27733. // Remove from the scene if found
  27734. this.skeletons.splice(index, 1);
  27735. }
  27736. return index;
  27737. };
  27738. /**
  27739. * Remove a morph target for the list of scene's morph targets
  27740. * @param toRemove defines the morph target to remove
  27741. * @returns the index where the morph target was in the morph target list
  27742. */
  27743. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  27744. var index = this.morphTargetManagers.indexOf(toRemove);
  27745. if (index !== -1) {
  27746. // Remove from the scene if found
  27747. this.morphTargetManagers.splice(index, 1);
  27748. }
  27749. return index;
  27750. };
  27751. /**
  27752. * Remove a light for the list of scene's lights
  27753. * @param toRemove defines the light to remove
  27754. * @returns the index where the light was in the light list
  27755. */
  27756. Scene.prototype.removeLight = function (toRemove) {
  27757. var index = this.lights.indexOf(toRemove);
  27758. if (index !== -1) {
  27759. // Remove from meshes
  27760. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27761. var mesh = _a[_i];
  27762. mesh._removeLightSource(toRemove);
  27763. }
  27764. // Remove from the scene if mesh found
  27765. this.lights.splice(index, 1);
  27766. this.sortLightsByPriority();
  27767. }
  27768. this.onLightRemovedObservable.notifyObservers(toRemove);
  27769. return index;
  27770. };
  27771. /**
  27772. * Remove a camera for the list of scene's cameras
  27773. * @param toRemove defines the camera to remove
  27774. * @returns the index where the camera was in the camera list
  27775. */
  27776. Scene.prototype.removeCamera = function (toRemove) {
  27777. var index = this.cameras.indexOf(toRemove);
  27778. if (index !== -1) {
  27779. // Remove from the scene if mesh found
  27780. this.cameras.splice(index, 1);
  27781. }
  27782. // Remove from activeCameras
  27783. var index2 = this.activeCameras.indexOf(toRemove);
  27784. if (index2 !== -1) {
  27785. // Remove from the scene if mesh found
  27786. this.activeCameras.splice(index2, 1);
  27787. }
  27788. // Reset the activeCamera
  27789. if (this.activeCamera === toRemove) {
  27790. if (this.cameras.length > 0) {
  27791. this.activeCamera = this.cameras[0];
  27792. }
  27793. else {
  27794. this.activeCamera = null;
  27795. }
  27796. }
  27797. this.onCameraRemovedObservable.notifyObservers(toRemove);
  27798. return index;
  27799. };
  27800. /**
  27801. * Remove a particle system for the list of scene's particle systems
  27802. * @param toRemove defines the particle system to remove
  27803. * @returns the index where the particle system was in the particle system list
  27804. */
  27805. Scene.prototype.removeParticleSystem = function (toRemove) {
  27806. var index = this.particleSystems.indexOf(toRemove);
  27807. if (index !== -1) {
  27808. this.particleSystems.splice(index, 1);
  27809. }
  27810. return index;
  27811. };
  27812. /**
  27813. * Remove a animation for the list of scene's animations
  27814. * @param toRemove defines the animation to remove
  27815. * @returns the index where the animation was in the animation list
  27816. */
  27817. Scene.prototype.removeAnimation = function (toRemove) {
  27818. var index = this.animations.indexOf(toRemove);
  27819. if (index !== -1) {
  27820. this.animations.splice(index, 1);
  27821. }
  27822. return index;
  27823. };
  27824. /**
  27825. * Removes the given animation group from this scene.
  27826. * @param toRemove The animation group to remove
  27827. * @returns The index of the removed animation group
  27828. */
  27829. Scene.prototype.removeAnimationGroup = function (toRemove) {
  27830. var index = this.animationGroups.indexOf(toRemove);
  27831. if (index !== -1) {
  27832. this.animationGroups.splice(index, 1);
  27833. }
  27834. return index;
  27835. };
  27836. /**
  27837. * Removes the given multi-material from this scene.
  27838. * @param toRemove The multi-material to remove
  27839. * @returns The index of the removed multi-material
  27840. */
  27841. Scene.prototype.removeMultiMaterial = function (toRemove) {
  27842. var index = this.multiMaterials.indexOf(toRemove);
  27843. if (index !== -1) {
  27844. this.multiMaterials.splice(index, 1);
  27845. }
  27846. return index;
  27847. };
  27848. /**
  27849. * Removes the given material from this scene.
  27850. * @param toRemove The material to remove
  27851. * @returns The index of the removed material
  27852. */
  27853. Scene.prototype.removeMaterial = function (toRemove) {
  27854. var index = this.materials.indexOf(toRemove);
  27855. if (index !== -1) {
  27856. this.materials.splice(index, 1);
  27857. }
  27858. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  27859. return index;
  27860. };
  27861. /**
  27862. * Removes the given action manager from this scene.
  27863. * @param toRemove The action manager to remove
  27864. * @returns The index of the removed action manager
  27865. */
  27866. Scene.prototype.removeActionManager = function (toRemove) {
  27867. var index = this.actionManagers.indexOf(toRemove);
  27868. if (index !== -1) {
  27869. this.actionManagers.splice(index, 1);
  27870. }
  27871. return index;
  27872. };
  27873. /**
  27874. * Removes the given texture from this scene.
  27875. * @param toRemove The texture to remove
  27876. * @returns The index of the removed texture
  27877. */
  27878. Scene.prototype.removeTexture = function (toRemove) {
  27879. var index = this.textures.indexOf(toRemove);
  27880. if (index !== -1) {
  27881. this.textures.splice(index, 1);
  27882. }
  27883. this.onTextureRemovedObservable.notifyObservers(toRemove);
  27884. return index;
  27885. };
  27886. /**
  27887. * Adds the given light to this scene
  27888. * @param newLight The light to add
  27889. */
  27890. Scene.prototype.addLight = function (newLight) {
  27891. this.lights.push(newLight);
  27892. this.sortLightsByPriority();
  27893. // Add light to all meshes (To support if the light is removed and then readded)
  27894. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27895. var mesh = _a[_i];
  27896. if (mesh._lightSources.indexOf(newLight) === -1) {
  27897. mesh._lightSources.push(newLight);
  27898. mesh._resyncLightSources();
  27899. }
  27900. }
  27901. this.onNewLightAddedObservable.notifyObservers(newLight);
  27902. };
  27903. /**
  27904. * Sorts the list list based on light priorities
  27905. */
  27906. Scene.prototype.sortLightsByPriority = function () {
  27907. if (this.requireLightSorting) {
  27908. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  27909. }
  27910. };
  27911. /**
  27912. * Adds the given camera to this scene
  27913. * @param newCamera The camera to add
  27914. */
  27915. Scene.prototype.addCamera = function (newCamera) {
  27916. this.cameras.push(newCamera);
  27917. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  27918. };
  27919. /**
  27920. * Adds the given skeleton to this scene
  27921. * @param newSkeleton The skeleton to add
  27922. */
  27923. Scene.prototype.addSkeleton = function (newSkeleton) {
  27924. this.skeletons.push(newSkeleton);
  27925. };
  27926. /**
  27927. * Adds the given particle system to this scene
  27928. * @param newParticleSystem The particle system to add
  27929. */
  27930. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  27931. this.particleSystems.push(newParticleSystem);
  27932. };
  27933. /**
  27934. * Adds the given animation to this scene
  27935. * @param newAnimation The animation to add
  27936. */
  27937. Scene.prototype.addAnimation = function (newAnimation) {
  27938. this.animations.push(newAnimation);
  27939. };
  27940. /**
  27941. * Adds the given animation group to this scene.
  27942. * @param newAnimationGroup The animation group to add
  27943. */
  27944. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  27945. this.animationGroups.push(newAnimationGroup);
  27946. };
  27947. /**
  27948. * Adds the given multi-material to this scene
  27949. * @param newMultiMaterial The multi-material to add
  27950. */
  27951. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  27952. this.multiMaterials.push(newMultiMaterial);
  27953. };
  27954. /**
  27955. * Adds the given material to this scene
  27956. * @param newMaterial The material to add
  27957. */
  27958. Scene.prototype.addMaterial = function (newMaterial) {
  27959. this.materials.push(newMaterial);
  27960. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  27961. };
  27962. /**
  27963. * Adds the given morph target to this scene
  27964. * @param newMorphTargetManager The morph target to add
  27965. */
  27966. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  27967. this.morphTargetManagers.push(newMorphTargetManager);
  27968. };
  27969. /**
  27970. * Adds the given geometry to this scene
  27971. * @param newGeometry The geometry to add
  27972. */
  27973. Scene.prototype.addGeometry = function (newGeometry) {
  27974. this.geometries.push(newGeometry);
  27975. };
  27976. /**
  27977. * Adds the given action manager to this scene
  27978. * @param newActionManager The action manager to add
  27979. */
  27980. Scene.prototype.addActionManager = function (newActionManager) {
  27981. this.actionManagers.push(newActionManager);
  27982. };
  27983. /**
  27984. * Adds the given texture to this scene.
  27985. * @param newTexture The texture to add
  27986. */
  27987. Scene.prototype.addTexture = function (newTexture) {
  27988. this.textures.push(newTexture);
  27989. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  27990. };
  27991. /**
  27992. * Switch active camera
  27993. * @param newCamera defines the new active camera
  27994. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  27995. */
  27996. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  27997. if (attachControl === void 0) { attachControl = true; }
  27998. var canvas = this._engine.getRenderingCanvas();
  27999. if (!canvas) {
  28000. return;
  28001. }
  28002. if (this.activeCamera) {
  28003. this.activeCamera.detachControl(canvas);
  28004. }
  28005. this.activeCamera = newCamera;
  28006. if (attachControl) {
  28007. newCamera.attachControl(canvas);
  28008. }
  28009. };
  28010. /**
  28011. * sets the active camera of the scene using its ID
  28012. * @param id defines the camera's ID
  28013. * @return the new active camera or null if none found.
  28014. */
  28015. Scene.prototype.setActiveCameraByID = function (id) {
  28016. var camera = this.getCameraByID(id);
  28017. if (camera) {
  28018. this.activeCamera = camera;
  28019. return camera;
  28020. }
  28021. return null;
  28022. };
  28023. /**
  28024. * sets the active camera of the scene using its name
  28025. * @param name defines the camera's name
  28026. * @returns the new active camera or null if none found.
  28027. */
  28028. Scene.prototype.setActiveCameraByName = function (name) {
  28029. var camera = this.getCameraByName(name);
  28030. if (camera) {
  28031. this.activeCamera = camera;
  28032. return camera;
  28033. }
  28034. return null;
  28035. };
  28036. /**
  28037. * get an animation group using its name
  28038. * @param name defines the material's name
  28039. * @return the animation group or null if none found.
  28040. */
  28041. Scene.prototype.getAnimationGroupByName = function (name) {
  28042. for (var index = 0; index < this.animationGroups.length; index++) {
  28043. if (this.animationGroups[index].name === name) {
  28044. return this.animationGroups[index];
  28045. }
  28046. }
  28047. return null;
  28048. };
  28049. /**
  28050. * get a material using its id
  28051. * @param id defines the material's ID
  28052. * @return the material or null if none found.
  28053. */
  28054. Scene.prototype.getMaterialByID = function (id) {
  28055. for (var index = 0; index < this.materials.length; index++) {
  28056. if (this.materials[index].id === id) {
  28057. return this.materials[index];
  28058. }
  28059. }
  28060. return null;
  28061. };
  28062. /**
  28063. * Gets a material using its name
  28064. * @param name defines the material's name
  28065. * @return the material or null if none found.
  28066. */
  28067. Scene.prototype.getMaterialByName = function (name) {
  28068. for (var index = 0; index < this.materials.length; index++) {
  28069. if (this.materials[index].name === name) {
  28070. return this.materials[index];
  28071. }
  28072. }
  28073. return null;
  28074. };
  28075. /**
  28076. * Gets a camera using its id
  28077. * @param id defines the id to look for
  28078. * @returns the camera or null if not found
  28079. */
  28080. Scene.prototype.getCameraByID = function (id) {
  28081. for (var index = 0; index < this.cameras.length; index++) {
  28082. if (this.cameras[index].id === id) {
  28083. return this.cameras[index];
  28084. }
  28085. }
  28086. return null;
  28087. };
  28088. /**
  28089. * Gets a camera using its unique id
  28090. * @param uniqueId defines the unique id to look for
  28091. * @returns the camera or null if not found
  28092. */
  28093. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  28094. for (var index = 0; index < this.cameras.length; index++) {
  28095. if (this.cameras[index].uniqueId === uniqueId) {
  28096. return this.cameras[index];
  28097. }
  28098. }
  28099. return null;
  28100. };
  28101. /**
  28102. * Gets a camera using its name
  28103. * @param name defines the camera's name
  28104. * @return the camera or null if none found.
  28105. */
  28106. Scene.prototype.getCameraByName = function (name) {
  28107. for (var index = 0; index < this.cameras.length; index++) {
  28108. if (this.cameras[index].name === name) {
  28109. return this.cameras[index];
  28110. }
  28111. }
  28112. return null;
  28113. };
  28114. /**
  28115. * Gets a bone using its id
  28116. * @param id defines the bone's id
  28117. * @return the bone or null if not found
  28118. */
  28119. Scene.prototype.getBoneByID = function (id) {
  28120. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28121. var skeleton = this.skeletons[skeletonIndex];
  28122. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28123. if (skeleton.bones[boneIndex].id === id) {
  28124. return skeleton.bones[boneIndex];
  28125. }
  28126. }
  28127. }
  28128. return null;
  28129. };
  28130. /**
  28131. * Gets a bone using its id
  28132. * @param name defines the bone's name
  28133. * @return the bone or null if not found
  28134. */
  28135. Scene.prototype.getBoneByName = function (name) {
  28136. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28137. var skeleton = this.skeletons[skeletonIndex];
  28138. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28139. if (skeleton.bones[boneIndex].name === name) {
  28140. return skeleton.bones[boneIndex];
  28141. }
  28142. }
  28143. }
  28144. return null;
  28145. };
  28146. /**
  28147. * Gets a light node using its name
  28148. * @param name defines the the light's name
  28149. * @return the light or null if none found.
  28150. */
  28151. Scene.prototype.getLightByName = function (name) {
  28152. for (var index = 0; index < this.lights.length; index++) {
  28153. if (this.lights[index].name === name) {
  28154. return this.lights[index];
  28155. }
  28156. }
  28157. return null;
  28158. };
  28159. /**
  28160. * Gets a light node using its id
  28161. * @param id defines the light's id
  28162. * @return the light or null if none found.
  28163. */
  28164. Scene.prototype.getLightByID = function (id) {
  28165. for (var index = 0; index < this.lights.length; index++) {
  28166. if (this.lights[index].id === id) {
  28167. return this.lights[index];
  28168. }
  28169. }
  28170. return null;
  28171. };
  28172. /**
  28173. * Gets a light node using its scene-generated unique ID
  28174. * @param uniqueId defines the light's unique id
  28175. * @return the light or null if none found.
  28176. */
  28177. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  28178. for (var index = 0; index < this.lights.length; index++) {
  28179. if (this.lights[index].uniqueId === uniqueId) {
  28180. return this.lights[index];
  28181. }
  28182. }
  28183. return null;
  28184. };
  28185. /**
  28186. * Gets a particle system by id
  28187. * @param id defines the particle system id
  28188. * @return the corresponding system or null if none found
  28189. */
  28190. Scene.prototype.getParticleSystemByID = function (id) {
  28191. for (var index = 0; index < this.particleSystems.length; index++) {
  28192. if (this.particleSystems[index].id === id) {
  28193. return this.particleSystems[index];
  28194. }
  28195. }
  28196. return null;
  28197. };
  28198. /**
  28199. * Gets a geometry using its ID
  28200. * @param id defines the geometry's id
  28201. * @return the geometry or null if none found.
  28202. */
  28203. Scene.prototype.getGeometryByID = function (id) {
  28204. for (var index = 0; index < this.geometries.length; index++) {
  28205. if (this.geometries[index].id === id) {
  28206. return this.geometries[index];
  28207. }
  28208. }
  28209. return null;
  28210. };
  28211. /**
  28212. * Add a new geometry to this scene
  28213. * @param geometry defines the geometry to be added to the scene.
  28214. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  28215. * @return a boolean defining if the geometry was added or not
  28216. */
  28217. Scene.prototype.pushGeometry = function (geometry, force) {
  28218. if (!force && this.getGeometryByID(geometry.id)) {
  28219. return false;
  28220. }
  28221. this.geometries.push(geometry);
  28222. //notify the collision coordinator
  28223. if (this.collisionCoordinator) {
  28224. this.collisionCoordinator.onGeometryAdded(geometry);
  28225. }
  28226. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  28227. return true;
  28228. };
  28229. /**
  28230. * Removes an existing geometry
  28231. * @param geometry defines the geometry to be removed from the scene
  28232. * @return a boolean defining if the geometry was removed or not
  28233. */
  28234. Scene.prototype.removeGeometry = function (geometry) {
  28235. var index = this.geometries.indexOf(geometry);
  28236. if (index > -1) {
  28237. this.geometries.splice(index, 1);
  28238. //notify the collision coordinator
  28239. if (this.collisionCoordinator) {
  28240. this.collisionCoordinator.onGeometryDeleted(geometry);
  28241. }
  28242. this.onGeometryRemovedObservable.notifyObservers(geometry);
  28243. return true;
  28244. }
  28245. return false;
  28246. };
  28247. /**
  28248. * Gets the list of geometries attached to the scene
  28249. * @returns an array of Geometry
  28250. */
  28251. Scene.prototype.getGeometries = function () {
  28252. return this.geometries;
  28253. };
  28254. /**
  28255. * Gets the first added mesh found of a given ID
  28256. * @param id defines the id to search for
  28257. * @return the mesh found or null if not found at all
  28258. */
  28259. Scene.prototype.getMeshByID = function (id) {
  28260. for (var index = 0; index < this.meshes.length; index++) {
  28261. if (this.meshes[index].id === id) {
  28262. return this.meshes[index];
  28263. }
  28264. }
  28265. return null;
  28266. };
  28267. /**
  28268. * Gets a list of meshes using their id
  28269. * @param id defines the id to search for
  28270. * @returns a list of meshes
  28271. */
  28272. Scene.prototype.getMeshesByID = function (id) {
  28273. return this.meshes.filter(function (m) {
  28274. return m.id === id;
  28275. });
  28276. };
  28277. /**
  28278. * Gets the first added transform node found of a given ID
  28279. * @param id defines the id to search for
  28280. * @return the found transform node or null if not found at all.
  28281. */
  28282. Scene.prototype.getTransformNodeByID = function (id) {
  28283. for (var index = 0; index < this.transformNodes.length; index++) {
  28284. if (this.transformNodes[index].id === id) {
  28285. return this.transformNodes[index];
  28286. }
  28287. }
  28288. return null;
  28289. };
  28290. /**
  28291. * Gets a list of transform nodes using their id
  28292. * @param id defines the id to search for
  28293. * @returns a list of transform nodes
  28294. */
  28295. Scene.prototype.getTransformNodesByID = function (id) {
  28296. return this.transformNodes.filter(function (m) {
  28297. return m.id === id;
  28298. });
  28299. };
  28300. /**
  28301. * Gets a mesh with its auto-generated unique id
  28302. * @param uniqueId defines the unique id to search for
  28303. * @return the found mesh or null if not found at all.
  28304. */
  28305. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  28306. for (var index = 0; index < this.meshes.length; index++) {
  28307. if (this.meshes[index].uniqueId === uniqueId) {
  28308. return this.meshes[index];
  28309. }
  28310. }
  28311. return null;
  28312. };
  28313. /**
  28314. * Gets a the last added mesh using a given id
  28315. * @param id defines the id to search for
  28316. * @return the found mesh or null if not found at all.
  28317. */
  28318. Scene.prototype.getLastMeshByID = function (id) {
  28319. for (var index = this.meshes.length - 1; index >= 0; index--) {
  28320. if (this.meshes[index].id === id) {
  28321. return this.meshes[index];
  28322. }
  28323. }
  28324. return null;
  28325. };
  28326. /**
  28327. * Gets a the last added node (Mesh, Camera, Light) using a given id
  28328. * @param id defines the id to search for
  28329. * @return the found node or null if not found at all
  28330. */
  28331. Scene.prototype.getLastEntryByID = function (id) {
  28332. var index;
  28333. for (index = this.meshes.length - 1; index >= 0; index--) {
  28334. if (this.meshes[index].id === id) {
  28335. return this.meshes[index];
  28336. }
  28337. }
  28338. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  28339. if (this.transformNodes[index].id === id) {
  28340. return this.transformNodes[index];
  28341. }
  28342. }
  28343. for (index = this.cameras.length - 1; index >= 0; index--) {
  28344. if (this.cameras[index].id === id) {
  28345. return this.cameras[index];
  28346. }
  28347. }
  28348. for (index = this.lights.length - 1; index >= 0; index--) {
  28349. if (this.lights[index].id === id) {
  28350. return this.lights[index];
  28351. }
  28352. }
  28353. return null;
  28354. };
  28355. /**
  28356. * Gets a node (Mesh, Camera, Light) using a given id
  28357. * @param id defines the id to search for
  28358. * @return the found node or null if not found at all
  28359. */
  28360. Scene.prototype.getNodeByID = function (id) {
  28361. var mesh = this.getMeshByID(id);
  28362. if (mesh) {
  28363. return mesh;
  28364. }
  28365. var light = this.getLightByID(id);
  28366. if (light) {
  28367. return light;
  28368. }
  28369. var camera = this.getCameraByID(id);
  28370. if (camera) {
  28371. return camera;
  28372. }
  28373. var bone = this.getBoneByID(id);
  28374. return bone;
  28375. };
  28376. /**
  28377. * Gets a node (Mesh, Camera, Light) using a given name
  28378. * @param name defines the name to search for
  28379. * @return the found node or null if not found at all.
  28380. */
  28381. Scene.prototype.getNodeByName = function (name) {
  28382. var mesh = this.getMeshByName(name);
  28383. if (mesh) {
  28384. return mesh;
  28385. }
  28386. var light = this.getLightByName(name);
  28387. if (light) {
  28388. return light;
  28389. }
  28390. var camera = this.getCameraByName(name);
  28391. if (camera) {
  28392. return camera;
  28393. }
  28394. var bone = this.getBoneByName(name);
  28395. return bone;
  28396. };
  28397. /**
  28398. * Gets a mesh using a given name
  28399. * @param name defines the name to search for
  28400. * @return the found mesh or null if not found at all.
  28401. */
  28402. Scene.prototype.getMeshByName = function (name) {
  28403. for (var index = 0; index < this.meshes.length; index++) {
  28404. if (this.meshes[index].name === name) {
  28405. return this.meshes[index];
  28406. }
  28407. }
  28408. return null;
  28409. };
  28410. /**
  28411. * Gets a transform node using a given name
  28412. * @param name defines the name to search for
  28413. * @return the found transform node or null if not found at all.
  28414. */
  28415. Scene.prototype.getTransformNodeByName = function (name) {
  28416. for (var index = 0; index < this.transformNodes.length; index++) {
  28417. if (this.transformNodes[index].name === name) {
  28418. return this.transformNodes[index];
  28419. }
  28420. }
  28421. return null;
  28422. };
  28423. /**
  28424. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  28425. * @param id defines the id to search for
  28426. * @return the found skeleton or null if not found at all.
  28427. */
  28428. Scene.prototype.getLastSkeletonByID = function (id) {
  28429. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  28430. if (this.skeletons[index].id === id) {
  28431. return this.skeletons[index];
  28432. }
  28433. }
  28434. return null;
  28435. };
  28436. /**
  28437. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  28438. * @param id defines the id to search for
  28439. * @return the found skeleton or null if not found at all.
  28440. */
  28441. Scene.prototype.getSkeletonById = function (id) {
  28442. for (var index = 0; index < this.skeletons.length; index++) {
  28443. if (this.skeletons[index].id === id) {
  28444. return this.skeletons[index];
  28445. }
  28446. }
  28447. return null;
  28448. };
  28449. /**
  28450. * Gets a skeleton using a given name
  28451. * @param name defines the name to search for
  28452. * @return the found skeleton or null if not found at all.
  28453. */
  28454. Scene.prototype.getSkeletonByName = function (name) {
  28455. for (var index = 0; index < this.skeletons.length; index++) {
  28456. if (this.skeletons[index].name === name) {
  28457. return this.skeletons[index];
  28458. }
  28459. }
  28460. return null;
  28461. };
  28462. /**
  28463. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  28464. * @param id defines the id to search for
  28465. * @return the found morph target manager or null if not found at all.
  28466. */
  28467. Scene.prototype.getMorphTargetManagerById = function (id) {
  28468. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  28469. if (this.morphTargetManagers[index].uniqueId === id) {
  28470. return this.morphTargetManagers[index];
  28471. }
  28472. }
  28473. return null;
  28474. };
  28475. /**
  28476. * Gets a boolean indicating if the given mesh is active
  28477. * @param mesh defines the mesh to look for
  28478. * @returns true if the mesh is in the active list
  28479. */
  28480. Scene.prototype.isActiveMesh = function (mesh) {
  28481. return (this._activeMeshes.indexOf(mesh) !== -1);
  28482. };
  28483. Object.defineProperty(Scene.prototype, "uid", {
  28484. /**
  28485. * Return a unique id as a string which can serve as an identifier for the scene
  28486. */
  28487. get: function () {
  28488. if (!this._uid) {
  28489. this._uid = BABYLON.Tools.RandomId();
  28490. }
  28491. return this._uid;
  28492. },
  28493. enumerable: true,
  28494. configurable: true
  28495. });
  28496. /**
  28497. * Add an externaly attached data from its key.
  28498. * This method call will fail and return false, if such key already exists.
  28499. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  28500. * @param key the unique key that identifies the data
  28501. * @param data the data object to associate to the key for this Engine instance
  28502. * @return true if no such key were already present and the data was added successfully, false otherwise
  28503. */
  28504. Scene.prototype.addExternalData = function (key, data) {
  28505. if (!this._externalData) {
  28506. this._externalData = new BABYLON.StringDictionary();
  28507. }
  28508. return this._externalData.add(key, data);
  28509. };
  28510. /**
  28511. * Get an externaly attached data from its key
  28512. * @param key the unique key that identifies the data
  28513. * @return the associated data, if present (can be null), or undefined if not present
  28514. */
  28515. Scene.prototype.getExternalData = function (key) {
  28516. if (!this._externalData) {
  28517. return null;
  28518. }
  28519. return this._externalData.get(key);
  28520. };
  28521. /**
  28522. * Get an externaly attached data from its key, create it using a factory if it's not already present
  28523. * @param key the unique key that identifies the data
  28524. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  28525. * @return the associated data, can be null if the factory returned null.
  28526. */
  28527. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  28528. if (!this._externalData) {
  28529. this._externalData = new BABYLON.StringDictionary();
  28530. }
  28531. return this._externalData.getOrAddWithFactory(key, factory);
  28532. };
  28533. /**
  28534. * Remove an externaly attached data from the Engine instance
  28535. * @param key the unique key that identifies the data
  28536. * @return true if the data was successfully removed, false if it doesn't exist
  28537. */
  28538. Scene.prototype.removeExternalData = function (key) {
  28539. return this._externalData.remove(key);
  28540. };
  28541. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  28542. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  28543. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  28544. var step = _a[_i];
  28545. step.action(mesh, subMesh);
  28546. }
  28547. var material = subMesh.getMaterial();
  28548. if (material !== null && material !== undefined) {
  28549. // Render targets
  28550. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  28551. if (this._processedMaterials.indexOf(material) === -1) {
  28552. this._processedMaterials.push(material);
  28553. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  28554. }
  28555. }
  28556. // Dispatch
  28557. this._activeIndices.addCount(subMesh.indexCount, false);
  28558. this._renderingManager.dispatch(subMesh, mesh, material);
  28559. }
  28560. }
  28561. };
  28562. /**
  28563. * Clear the processed materials smart array preventing retention point in material dispose.
  28564. */
  28565. Scene.prototype.freeProcessedMaterials = function () {
  28566. this._processedMaterials.dispose();
  28567. };
  28568. /**
  28569. * Clear the active meshes smart array preventing retention point in mesh dispose.
  28570. */
  28571. Scene.prototype.freeActiveMeshes = function () {
  28572. this._activeMeshes.dispose();
  28573. if (this.activeCamera && this.activeCamera._activeMeshes) {
  28574. this.activeCamera._activeMeshes.dispose();
  28575. }
  28576. if (this.activeCameras) {
  28577. for (var i = 0; i < this.activeCameras.length; i++) {
  28578. var activeCamera = this.activeCameras[i];
  28579. if (activeCamera && activeCamera._activeMeshes) {
  28580. activeCamera._activeMeshes.dispose();
  28581. }
  28582. }
  28583. }
  28584. };
  28585. /**
  28586. * Clear the info related to rendering groups preventing retention points during dispose.
  28587. */
  28588. Scene.prototype.freeRenderingGroups = function () {
  28589. if (this._renderingManager) {
  28590. this._renderingManager.freeRenderingGroups();
  28591. }
  28592. if (this.textures) {
  28593. for (var i = 0; i < this.textures.length; i++) {
  28594. var texture = this.textures[i];
  28595. if (texture && texture.renderList) {
  28596. texture.freeRenderingGroups();
  28597. }
  28598. }
  28599. }
  28600. };
  28601. /** @hidden */
  28602. Scene.prototype._isInIntermediateRendering = function () {
  28603. return this._intermediateRendering;
  28604. };
  28605. /**
  28606. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  28607. * @returns the current scene
  28608. */
  28609. Scene.prototype.freezeActiveMeshes = function () {
  28610. if (!this.activeCamera) {
  28611. return this;
  28612. }
  28613. if (!this._frustumPlanes) {
  28614. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28615. }
  28616. this._evaluateActiveMeshes();
  28617. this._activeMeshesFrozen = true;
  28618. return this;
  28619. };
  28620. /**
  28621. * Use this function to restart evaluating active meshes on every frame
  28622. * @returns the current scene
  28623. */
  28624. Scene.prototype.unfreezeActiveMeshes = function () {
  28625. this._activeMeshesFrozen = false;
  28626. return this;
  28627. };
  28628. Scene.prototype._evaluateActiveMeshes = function () {
  28629. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  28630. return;
  28631. }
  28632. if (!this.activeCamera) {
  28633. return;
  28634. }
  28635. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  28636. this.activeCamera._activeMeshes.reset();
  28637. this._activeMeshes.reset();
  28638. this._renderingManager.reset();
  28639. this._processedMaterials.reset();
  28640. this._activeParticleSystems.reset();
  28641. this._activeSkeletons.reset();
  28642. this._softwareSkinnedMeshes.reset();
  28643. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  28644. var step = _a[_i];
  28645. step.action();
  28646. }
  28647. // Determine mesh candidates
  28648. var meshes = this.getActiveMeshCandidates();
  28649. // Check each mesh
  28650. var len = meshes.length;
  28651. for (var i = 0; i < len; i++) {
  28652. var mesh = meshes.data[i];
  28653. if (mesh.isBlocked) {
  28654. continue;
  28655. }
  28656. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  28657. if (!mesh.isReady() || !mesh.isEnabled()) {
  28658. continue;
  28659. }
  28660. mesh.computeWorldMatrix();
  28661. // Intersections
  28662. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  28663. this._meshesForIntersections.pushNoDuplicate(mesh);
  28664. }
  28665. // Switch to current LOD
  28666. var meshLOD = mesh.getLOD(this.activeCamera);
  28667. if (meshLOD === undefined || meshLOD === null) {
  28668. continue;
  28669. }
  28670. mesh._preActivate();
  28671. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  28672. this._activeMeshes.push(mesh);
  28673. this.activeCamera._activeMeshes.push(mesh);
  28674. mesh._activate(this._renderId);
  28675. if (meshLOD !== mesh) {
  28676. meshLOD._activate(this._renderId);
  28677. }
  28678. this._activeMesh(mesh, meshLOD);
  28679. }
  28680. }
  28681. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  28682. // Particle systems
  28683. if (this.particlesEnabled) {
  28684. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  28685. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  28686. var particleSystem = this.particleSystems[particleIndex];
  28687. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  28688. continue;
  28689. }
  28690. var emitter = particleSystem.emitter;
  28691. if (!emitter.position || emitter.isEnabled()) {
  28692. this._activeParticleSystems.push(particleSystem);
  28693. particleSystem.animate();
  28694. this._renderingManager.dispatchParticles(particleSystem);
  28695. }
  28696. }
  28697. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  28698. }
  28699. };
  28700. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  28701. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  28702. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  28703. mesh.skeleton.prepare();
  28704. }
  28705. if (!mesh.computeBonesUsingShaders) {
  28706. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  28707. }
  28708. }
  28709. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  28710. var step = _a[_i];
  28711. step.action(sourceMesh, mesh);
  28712. }
  28713. if (mesh !== undefined && mesh !== null
  28714. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  28715. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  28716. var len = subMeshes.length;
  28717. for (var i = 0; i < len; i++) {
  28718. var subMesh = subMeshes.data[i];
  28719. this._evaluateSubMesh(subMesh, mesh);
  28720. }
  28721. }
  28722. };
  28723. /**
  28724. * Update the transform matrix to update from the current active camera
  28725. * @param force defines a boolean used to force the update even if cache is up to date
  28726. */
  28727. Scene.prototype.updateTransformMatrix = function (force) {
  28728. if (!this.activeCamera) {
  28729. return;
  28730. }
  28731. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  28732. };
  28733. /**
  28734. * 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)
  28735. * @param alternateCamera defines the camera to use
  28736. */
  28737. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  28738. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  28739. };
  28740. Scene.prototype._renderForCamera = function (camera, rigParent) {
  28741. if (camera && camera._skipRendering) {
  28742. return;
  28743. }
  28744. var engine = this._engine;
  28745. this.activeCamera = camera;
  28746. if (!this.activeCamera) {
  28747. throw new Error("Active camera not set");
  28748. }
  28749. // Viewport
  28750. engine.setViewport(this.activeCamera.viewport);
  28751. // Camera
  28752. this.resetCachedMaterial();
  28753. this._renderId++;
  28754. this.updateTransformMatrix();
  28755. if (camera._alternateCamera) {
  28756. this.updateAlternateTransformMatrix(camera._alternateCamera);
  28757. this._alternateRendering = true;
  28758. }
  28759. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  28760. // Meshes
  28761. this._evaluateActiveMeshes();
  28762. // Software skinning
  28763. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  28764. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  28765. mesh.applySkeleton(mesh.skeleton);
  28766. }
  28767. // Render targets
  28768. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28769. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  28770. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  28771. }
  28772. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  28773. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  28774. }
  28775. // Collects render targets from external components.
  28776. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  28777. var step = _a[_i];
  28778. step.action(this._renderTargets);
  28779. }
  28780. if (this.renderTargetsEnabled) {
  28781. this._intermediateRendering = true;
  28782. if (this._renderTargets.length > 0) {
  28783. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28784. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  28785. var renderTarget = this._renderTargets.data[renderIndex];
  28786. if (renderTarget._shouldRender()) {
  28787. this._renderId++;
  28788. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  28789. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  28790. }
  28791. }
  28792. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28793. this._renderId++;
  28794. }
  28795. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  28796. var step = _c[_b];
  28797. step.action(this.activeCamera);
  28798. }
  28799. this._intermediateRendering = false;
  28800. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  28801. }
  28802. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28803. // Prepare Frame
  28804. if (this.postProcessManager) {
  28805. this.postProcessManager._prepareFrame();
  28806. }
  28807. // Before Camera Draw
  28808. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  28809. var step = _e[_d];
  28810. step.action(this.activeCamera);
  28811. }
  28812. // Render
  28813. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  28814. this._renderingManager.render(null, null, true, true);
  28815. this.onAfterDrawPhaseObservable.notifyObservers(this);
  28816. // After Camera Draw
  28817. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  28818. var step = _g[_f];
  28819. step.action(this.activeCamera);
  28820. }
  28821. // Finalize frame
  28822. if (this.postProcessManager) {
  28823. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  28824. }
  28825. // Reset some special arrays
  28826. this._renderTargets.reset();
  28827. this._alternateRendering = false;
  28828. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  28829. };
  28830. Scene.prototype._processSubCameras = function (camera) {
  28831. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  28832. this._renderForCamera(camera);
  28833. return;
  28834. }
  28835. // rig cameras
  28836. for (var index = 0; index < camera._rigCameras.length; index++) {
  28837. this._renderForCamera(camera._rigCameras[index], camera);
  28838. }
  28839. this.activeCamera = camera;
  28840. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28841. };
  28842. Scene.prototype._checkIntersections = function () {
  28843. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  28844. var sourceMesh = this._meshesForIntersections.data[index];
  28845. if (!sourceMesh.actionManager) {
  28846. continue;
  28847. }
  28848. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  28849. var action = sourceMesh.actionManager.actions[actionIndex];
  28850. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28851. var parameters = action.getTriggerParameter();
  28852. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  28853. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  28854. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  28855. if (areIntersecting && currentIntersectionInProgress === -1) {
  28856. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  28857. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28858. sourceMesh._intersectionsInProgress.push(otherMesh);
  28859. }
  28860. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28861. sourceMesh._intersectionsInProgress.push(otherMesh);
  28862. }
  28863. }
  28864. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  28865. //They intersected, and now they don't.
  28866. //is this trigger an exit trigger? execute an event.
  28867. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28868. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28869. }
  28870. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  28871. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  28872. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  28873. return otherMesh === parameterMesh;
  28874. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28875. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  28876. }
  28877. }
  28878. }
  28879. }
  28880. }
  28881. };
  28882. /** @hidden */
  28883. Scene.prototype._advancePhysicsEngineStep = function (step) {
  28884. // Do nothing. Code will be replaced if physics engine component is referenced
  28885. };
  28886. /**
  28887. * Render the scene
  28888. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  28889. */
  28890. Scene.prototype.render = function (updateCameras) {
  28891. if (updateCameras === void 0) { updateCameras = true; }
  28892. if (this.isDisposed) {
  28893. return;
  28894. }
  28895. this._frameId++;
  28896. // Register components that have been associated lately to the scene.
  28897. this._registerTransientComponents();
  28898. this._activeParticles.fetchNewFrame();
  28899. this._totalVertices.fetchNewFrame();
  28900. this._activeIndices.fetchNewFrame();
  28901. this._activeBones.fetchNewFrame();
  28902. this._meshesForIntersections.reset();
  28903. this.resetCachedMaterial();
  28904. this.onBeforeAnimationsObservable.notifyObservers(this);
  28905. // Actions
  28906. if (this.actionManager) {
  28907. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  28908. }
  28909. if (this._engine.isDeterministicLockStep()) {
  28910. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  28911. var defaultFPS = (60.0 / 1000.0);
  28912. var defaultFrameTime = this.getDeterministicFrameTime();
  28913. var stepsTaken = 0;
  28914. var maxSubSteps = this._engine.getLockstepMaxSteps();
  28915. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  28916. internalSteps = Math.min(internalSteps, maxSubSteps);
  28917. do {
  28918. this.onBeforeStepObservable.notifyObservers(this);
  28919. // Animations
  28920. this._animationRatio = defaultFrameTime * defaultFPS;
  28921. this._animate();
  28922. this.onAfterAnimationsObservable.notifyObservers(this);
  28923. // Physics
  28924. this._advancePhysicsEngineStep(defaultFrameTime);
  28925. this.onAfterStepObservable.notifyObservers(this);
  28926. this._currentStepId++;
  28927. stepsTaken++;
  28928. deltaTime -= defaultFrameTime;
  28929. } while (deltaTime > 0 && stepsTaken < internalSteps);
  28930. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  28931. }
  28932. else {
  28933. // Animations
  28934. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28935. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28936. this._animate();
  28937. this.onAfterAnimationsObservable.notifyObservers(this);
  28938. // Physics
  28939. this._advancePhysicsEngineStep(deltaTime);
  28940. }
  28941. // Before camera update steps
  28942. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  28943. var step = _a[_i];
  28944. step.action();
  28945. }
  28946. // Update Cameras
  28947. if (updateCameras) {
  28948. if (this.activeCameras.length > 0) {
  28949. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28950. var camera = this.activeCameras[cameraIndex];
  28951. camera.update();
  28952. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28953. // rig cameras
  28954. for (var index = 0; index < camera._rigCameras.length; index++) {
  28955. camera._rigCameras[index].update();
  28956. }
  28957. }
  28958. }
  28959. }
  28960. else if (this.activeCamera) {
  28961. this.activeCamera.update();
  28962. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28963. // rig cameras
  28964. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28965. this.activeCamera._rigCameras[index].update();
  28966. }
  28967. }
  28968. }
  28969. }
  28970. // Before render
  28971. this.onBeforeRenderObservable.notifyObservers(this);
  28972. // Customs render targets
  28973. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28974. var engine = this.getEngine();
  28975. var currentActiveCamera = this.activeCamera;
  28976. if (this.renderTargetsEnabled) {
  28977. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28978. this._intermediateRendering = true;
  28979. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28980. var renderTarget = this.customRenderTargets[customIndex];
  28981. if (renderTarget._shouldRender()) {
  28982. this._renderId++;
  28983. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28984. if (!this.activeCamera) {
  28985. throw new Error("Active camera not set");
  28986. }
  28987. // Viewport
  28988. engine.setViewport(this.activeCamera.viewport);
  28989. // Camera
  28990. this.updateTransformMatrix();
  28991. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28992. }
  28993. }
  28994. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28995. this._intermediateRendering = false;
  28996. this._renderId++;
  28997. }
  28998. // Restore back buffer
  28999. if (this.customRenderTargets.length > 0) {
  29000. engine.restoreDefaultFramebuffer();
  29001. }
  29002. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  29003. this.activeCamera = currentActiveCamera;
  29004. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  29005. var step = _c[_b];
  29006. step.action();
  29007. }
  29008. // Clear
  29009. if (this.autoClearDepthAndStencil || this.autoClear) {
  29010. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  29011. }
  29012. // Collects render targets from external components.
  29013. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  29014. var step = _e[_d];
  29015. step.action(this._renderTargets);
  29016. }
  29017. // Multi-cameras?
  29018. if (this.activeCameras.length > 0) {
  29019. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  29020. if (cameraIndex > 0) {
  29021. this._engine.clear(null, false, true, true);
  29022. }
  29023. this._processSubCameras(this.activeCameras[cameraIndex]);
  29024. }
  29025. }
  29026. else {
  29027. if (!this.activeCamera) {
  29028. throw new Error("No camera defined");
  29029. }
  29030. this._processSubCameras(this.activeCamera);
  29031. }
  29032. // Intersection checks
  29033. this._checkIntersections();
  29034. // Executes the after render stage actions.
  29035. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  29036. var step = _g[_f];
  29037. step.action();
  29038. }
  29039. // After render
  29040. if (this.afterRender) {
  29041. this.afterRender();
  29042. }
  29043. this.onAfterRenderObservable.notifyObservers(this);
  29044. // Cleaning
  29045. if (this._toBeDisposed.length) {
  29046. for (var index = 0; index < this._toBeDisposed.length; index++) {
  29047. var data = this._toBeDisposed[index];
  29048. if (data) {
  29049. data.dispose();
  29050. }
  29051. }
  29052. this._toBeDisposed = [];
  29053. }
  29054. if (this.dumpNextRenderTargets) {
  29055. this.dumpNextRenderTargets = false;
  29056. }
  29057. this._activeBones.addCount(0, true);
  29058. this._activeIndices.addCount(0, true);
  29059. this._activeParticles.addCount(0, true);
  29060. };
  29061. /**
  29062. * Freeze all materials
  29063. * A frozen material will not be updatable but should be faster to render
  29064. */
  29065. Scene.prototype.freezeMaterials = function () {
  29066. for (var i = 0; i < this.materials.length; i++) {
  29067. this.materials[i].freeze();
  29068. }
  29069. };
  29070. /**
  29071. * Unfreeze all materials
  29072. * A frozen material will not be updatable but should be faster to render
  29073. */
  29074. Scene.prototype.unfreezeMaterials = function () {
  29075. for (var i = 0; i < this.materials.length; i++) {
  29076. this.materials[i].unfreeze();
  29077. }
  29078. };
  29079. /**
  29080. * Releases all held ressources
  29081. */
  29082. Scene.prototype.dispose = function () {
  29083. this.beforeRender = null;
  29084. this.afterRender = null;
  29085. this.skeletons = [];
  29086. this.morphTargetManagers = [];
  29087. this._transientComponents = [];
  29088. this._isReadyForMeshStage.clear();
  29089. this._beforeEvaluateActiveMeshStage.clear();
  29090. this._evaluateSubMeshStage.clear();
  29091. this._activeMeshStage.clear();
  29092. this._cameraDrawRenderTargetStage.clear();
  29093. this._beforeCameraDrawStage.clear();
  29094. this._beforeRenderingGroupDrawStage.clear();
  29095. this._beforeRenderingMeshStage.clear();
  29096. this._afterRenderingMeshStage.clear();
  29097. this._afterRenderingGroupDrawStage.clear();
  29098. this._afterCameraDrawStage.clear();
  29099. this._afterRenderStage.clear();
  29100. this._beforeCameraUpdateStage.clear();
  29101. this._beforeClearStage.clear();
  29102. this._gatherRenderTargetsStage.clear();
  29103. this._gatherActiveCameraRenderTargetsStage.clear();
  29104. this._pointerMoveStage.clear();
  29105. this._pointerDownStage.clear();
  29106. this._pointerUpStage.clear();
  29107. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  29108. var component = _a[_i];
  29109. component.dispose();
  29110. }
  29111. this.importedMeshesFiles = new Array();
  29112. this.stopAllAnimations();
  29113. this.resetCachedMaterial();
  29114. // Smart arrays
  29115. if (this.activeCamera) {
  29116. this.activeCamera._activeMeshes.dispose();
  29117. this.activeCamera = null;
  29118. }
  29119. this._activeMeshes.dispose();
  29120. this._renderingManager.dispose();
  29121. this._processedMaterials.dispose();
  29122. this._activeParticleSystems.dispose();
  29123. this._activeSkeletons.dispose();
  29124. this._softwareSkinnedMeshes.dispose();
  29125. this._renderTargets.dispose();
  29126. this._registeredForLateAnimationBindings.dispose();
  29127. this._meshesForIntersections.dispose();
  29128. this._toBeDisposed = [];
  29129. // Abort active requests
  29130. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  29131. var request = _c[_b];
  29132. request.abort();
  29133. }
  29134. // Events
  29135. this.onDisposeObservable.notifyObservers(this);
  29136. this.onDisposeObservable.clear();
  29137. this.onBeforeRenderObservable.clear();
  29138. this.onAfterRenderObservable.clear();
  29139. this.onBeforeRenderTargetsRenderObservable.clear();
  29140. this.onAfterRenderTargetsRenderObservable.clear();
  29141. this.onAfterStepObservable.clear();
  29142. this.onBeforeStepObservable.clear();
  29143. this.onBeforeActiveMeshesEvaluationObservable.clear();
  29144. this.onAfterActiveMeshesEvaluationObservable.clear();
  29145. this.onBeforeParticlesRenderingObservable.clear();
  29146. this.onAfterParticlesRenderingObservable.clear();
  29147. this.onBeforeDrawPhaseObservable.clear();
  29148. this.onAfterDrawPhaseObservable.clear();
  29149. this.onBeforeAnimationsObservable.clear();
  29150. this.onAfterAnimationsObservable.clear();
  29151. this.onDataLoadedObservable.clear();
  29152. this.onBeforeRenderingGroupObservable.clear();
  29153. this.onAfterRenderingGroupObservable.clear();
  29154. this.onMeshImportedObservable.clear();
  29155. this.onBeforeCameraRenderObservable.clear();
  29156. this.onAfterCameraRenderObservable.clear();
  29157. this.onReadyObservable.clear();
  29158. this.onNewCameraAddedObservable.clear();
  29159. this.onCameraRemovedObservable.clear();
  29160. this.onNewLightAddedObservable.clear();
  29161. this.onLightRemovedObservable.clear();
  29162. this.onNewGeometryAddedObservable.clear();
  29163. this.onGeometryRemovedObservable.clear();
  29164. this.onNewTransformNodeAddedObservable.clear();
  29165. this.onTransformNodeRemovedObservable.clear();
  29166. this.onNewMeshAddedObservable.clear();
  29167. this.onMeshRemovedObservable.clear();
  29168. this.onNewMaterialAddedObservable.clear();
  29169. this.onMaterialRemovedObservable.clear();
  29170. this.onNewTextureAddedObservable.clear();
  29171. this.onTextureRemovedObservable.clear();
  29172. this.onPrePointerObservable.clear();
  29173. this.onPointerObservable.clear();
  29174. this.onPreKeyboardObservable.clear();
  29175. this.onKeyboardObservable.clear();
  29176. this.detachControl();
  29177. // Detach cameras
  29178. var canvas = this._engine.getRenderingCanvas();
  29179. if (canvas) {
  29180. var index;
  29181. for (index = 0; index < this.cameras.length; index++) {
  29182. this.cameras[index].detachControl(canvas);
  29183. }
  29184. }
  29185. // Release animation groups
  29186. while (this.animationGroups.length) {
  29187. this.animationGroups[0].dispose();
  29188. }
  29189. // Release lights
  29190. while (this.lights.length) {
  29191. this.lights[0].dispose();
  29192. }
  29193. // Release meshes
  29194. while (this.meshes.length) {
  29195. this.meshes[0].dispose(true);
  29196. }
  29197. while (this.transformNodes.length) {
  29198. this.removeTransformNode(this.transformNodes[0]);
  29199. }
  29200. // Release cameras
  29201. while (this.cameras.length) {
  29202. this.cameras[0].dispose();
  29203. }
  29204. // Release materials
  29205. if (this.defaultMaterial) {
  29206. this.defaultMaterial.dispose();
  29207. }
  29208. while (this.multiMaterials.length) {
  29209. this.multiMaterials[0].dispose();
  29210. }
  29211. while (this.materials.length) {
  29212. this.materials[0].dispose();
  29213. }
  29214. // Release particles
  29215. while (this.particleSystems.length) {
  29216. this.particleSystems[0].dispose();
  29217. }
  29218. // Release postProcesses
  29219. while (this.postProcesses.length) {
  29220. this.postProcesses[0].dispose();
  29221. }
  29222. // Release textures
  29223. while (this.textures.length) {
  29224. this.textures[0].dispose();
  29225. }
  29226. // Release UBO
  29227. this._sceneUbo.dispose();
  29228. if (this._alternateSceneUbo) {
  29229. this._alternateSceneUbo.dispose();
  29230. }
  29231. // Post-processes
  29232. this.postProcessManager.dispose();
  29233. // Remove from engine
  29234. index = this._engine.scenes.indexOf(this);
  29235. if (index > -1) {
  29236. this._engine.scenes.splice(index, 1);
  29237. }
  29238. this._engine.wipeCaches(true);
  29239. this._isDisposed = true;
  29240. };
  29241. Object.defineProperty(Scene.prototype, "isDisposed", {
  29242. /**
  29243. * Gets if the scene is already disposed
  29244. */
  29245. get: function () {
  29246. return this._isDisposed;
  29247. },
  29248. enumerable: true,
  29249. configurable: true
  29250. });
  29251. /**
  29252. * Call this function to reduce memory footprint of the scene.
  29253. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  29254. */
  29255. Scene.prototype.clearCachedVertexData = function () {
  29256. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29257. var mesh = this.meshes[meshIndex];
  29258. var geometry = mesh.geometry;
  29259. if (geometry) {
  29260. geometry._indices = [];
  29261. for (var vbName in geometry._vertexBuffers) {
  29262. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  29263. continue;
  29264. }
  29265. geometry._vertexBuffers[vbName]._buffer._data = null;
  29266. }
  29267. }
  29268. }
  29269. };
  29270. /**
  29271. * This function will remove the local cached buffer data from texture.
  29272. * It will save memory but will prevent the texture from being rebuilt
  29273. */
  29274. Scene.prototype.cleanCachedTextureBuffer = function () {
  29275. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29276. var baseTexture = _a[_i];
  29277. var buffer = baseTexture._buffer;
  29278. if (buffer) {
  29279. baseTexture._buffer = null;
  29280. }
  29281. }
  29282. };
  29283. /**
  29284. * Get the world extend vectors with an optional filter
  29285. *
  29286. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  29287. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  29288. */
  29289. Scene.prototype.getWorldExtends = function (filterPredicate) {
  29290. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29291. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  29292. filterPredicate = filterPredicate || (function () { return true; });
  29293. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  29294. mesh.computeWorldMatrix(true);
  29295. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  29296. return;
  29297. }
  29298. var boundingInfo = mesh.getBoundingInfo();
  29299. var minBox = boundingInfo.boundingBox.minimumWorld;
  29300. var maxBox = boundingInfo.boundingBox.maximumWorld;
  29301. BABYLON.Tools.CheckExtends(minBox, min, max);
  29302. BABYLON.Tools.CheckExtends(maxBox, min, max);
  29303. });
  29304. return {
  29305. min: min,
  29306. max: max
  29307. };
  29308. };
  29309. // Picking
  29310. /**
  29311. * Creates a ray that can be used to pick in the scene
  29312. * @param x defines the x coordinate of the origin (on-screen)
  29313. * @param y defines the y coordinate of the origin (on-screen)
  29314. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29315. * @param camera defines the camera to use for the picking
  29316. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29317. * @returns a Ray
  29318. */
  29319. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  29320. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29321. var result = BABYLON.Ray.Zero();
  29322. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  29323. return result;
  29324. };
  29325. /**
  29326. * Creates a ray that can be used to pick in the scene
  29327. * @param x defines the x coordinate of the origin (on-screen)
  29328. * @param y defines the y coordinate of the origin (on-screen)
  29329. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29330. * @param result defines the ray where to store the picking ray
  29331. * @param camera defines the camera to use for the picking
  29332. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29333. * @returns the current scene
  29334. */
  29335. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  29336. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29337. var engine = this._engine;
  29338. if (!camera) {
  29339. if (!this.activeCamera) {
  29340. throw new Error("Active camera not set");
  29341. }
  29342. camera = this.activeCamera;
  29343. }
  29344. var cameraViewport = camera.viewport;
  29345. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29346. // Moving coordinates to local viewport world
  29347. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29348. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29349. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  29350. return this;
  29351. };
  29352. /**
  29353. * Creates a ray that can be used to pick in the scene
  29354. * @param x defines the x coordinate of the origin (on-screen)
  29355. * @param y defines the y coordinate of the origin (on-screen)
  29356. * @param camera defines the camera to use for the picking
  29357. * @returns a Ray
  29358. */
  29359. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  29360. var result = BABYLON.Ray.Zero();
  29361. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  29362. return result;
  29363. };
  29364. /**
  29365. * Creates a ray that can be used to pick in the scene
  29366. * @param x defines the x coordinate of the origin (on-screen)
  29367. * @param y defines the y coordinate of the origin (on-screen)
  29368. * @param result defines the ray where to store the picking ray
  29369. * @param camera defines the camera to use for the picking
  29370. * @returns the current scene
  29371. */
  29372. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  29373. if (!BABYLON.PickingInfo) {
  29374. return this;
  29375. }
  29376. var engine = this._engine;
  29377. if (!camera) {
  29378. if (!this.activeCamera) {
  29379. throw new Error("Active camera not set");
  29380. }
  29381. camera = this.activeCamera;
  29382. }
  29383. var cameraViewport = camera.viewport;
  29384. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29385. var identity = BABYLON.Matrix.Identity();
  29386. // Moving coordinates to local viewport world
  29387. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29388. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29389. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  29390. return this;
  29391. };
  29392. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  29393. if (!BABYLON.PickingInfo) {
  29394. return null;
  29395. }
  29396. var pickingInfo = null;
  29397. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29398. var mesh = this.meshes[meshIndex];
  29399. if (predicate) {
  29400. if (!predicate(mesh)) {
  29401. continue;
  29402. }
  29403. }
  29404. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29405. continue;
  29406. }
  29407. var world = mesh.getWorldMatrix();
  29408. var ray = rayFunction(world);
  29409. var result = mesh.intersects(ray, fastCheck);
  29410. if (!result || !result.hit) {
  29411. continue;
  29412. }
  29413. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
  29414. continue;
  29415. }
  29416. pickingInfo = result;
  29417. if (fastCheck) {
  29418. break;
  29419. }
  29420. }
  29421. return pickingInfo || new BABYLON.PickingInfo();
  29422. };
  29423. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  29424. if (!BABYLON.PickingInfo) {
  29425. return null;
  29426. }
  29427. var pickingInfos = new Array();
  29428. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29429. var mesh = this.meshes[meshIndex];
  29430. if (predicate) {
  29431. if (!predicate(mesh)) {
  29432. continue;
  29433. }
  29434. }
  29435. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29436. continue;
  29437. }
  29438. var world = mesh.getWorldMatrix();
  29439. var ray = rayFunction(world);
  29440. var result = mesh.intersects(ray, false);
  29441. if (!result || !result.hit) {
  29442. continue;
  29443. }
  29444. pickingInfos.push(result);
  29445. }
  29446. return pickingInfos;
  29447. };
  29448. /** Launch a ray to try to pick a mesh in the scene
  29449. * @param x position on screen
  29450. * @param y position on screen
  29451. * @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
  29452. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  29453. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29454. * @returns a PickingInfo
  29455. */
  29456. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  29457. var _this = this;
  29458. if (!BABYLON.PickingInfo) {
  29459. return null;
  29460. }
  29461. var result = this._internalPick(function (world) {
  29462. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  29463. return _this._tempPickingRay;
  29464. }, predicate, fastCheck);
  29465. if (result) {
  29466. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  29467. }
  29468. return result;
  29469. };
  29470. /** Use the given ray to pick a mesh in the scene
  29471. * @param ray The ray to use to pick meshes
  29472. * @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
  29473. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  29474. * @returns a PickingInfo
  29475. */
  29476. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  29477. var _this = this;
  29478. var result = this._internalPick(function (world) {
  29479. if (!_this._pickWithRayInverseMatrix) {
  29480. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29481. }
  29482. world.invertToRef(_this._pickWithRayInverseMatrix);
  29483. if (!_this._cachedRayForTransform) {
  29484. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29485. }
  29486. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29487. return _this._cachedRayForTransform;
  29488. }, predicate, fastCheck);
  29489. if (result) {
  29490. result.ray = ray;
  29491. }
  29492. return result;
  29493. };
  29494. /**
  29495. * Launch a ray to try to pick a mesh in the scene
  29496. * @param x X position on screen
  29497. * @param y Y position on screen
  29498. * @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
  29499. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29500. * @returns an array of PickingInfo
  29501. */
  29502. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  29503. var _this = this;
  29504. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  29505. };
  29506. /**
  29507. * Launch a ray to try to pick a mesh in the scene
  29508. * @param ray Ray to use
  29509. * @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
  29510. * @returns an array of PickingInfo
  29511. */
  29512. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  29513. var _this = this;
  29514. return this._internalMultiPick(function (world) {
  29515. if (!_this._pickWithRayInverseMatrix) {
  29516. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29517. }
  29518. world.invertToRef(_this._pickWithRayInverseMatrix);
  29519. if (!_this._cachedRayForTransform) {
  29520. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29521. }
  29522. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29523. return _this._cachedRayForTransform;
  29524. }, predicate);
  29525. };
  29526. /**
  29527. * Force the value of meshUnderPointer
  29528. * @param mesh defines the mesh to use
  29529. */
  29530. Scene.prototype.setPointerOverMesh = function (mesh) {
  29531. if (this._pointerOverMesh === mesh) {
  29532. return;
  29533. }
  29534. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29535. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29536. }
  29537. this._pointerOverMesh = mesh;
  29538. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29539. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29540. }
  29541. };
  29542. /**
  29543. * Gets the mesh under the pointer
  29544. * @returns a Mesh or null if no mesh is under the pointer
  29545. */
  29546. Scene.prototype.getPointerOverMesh = function () {
  29547. return this._pointerOverMesh;
  29548. };
  29549. // Misc.
  29550. /** @hidden */
  29551. Scene.prototype._rebuildGeometries = function () {
  29552. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  29553. var geometry = _a[_i];
  29554. geometry._rebuild();
  29555. }
  29556. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  29557. var mesh = _c[_b];
  29558. mesh._rebuild();
  29559. }
  29560. if (this.postProcessManager) {
  29561. this.postProcessManager._rebuild();
  29562. }
  29563. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  29564. var component = _e[_d];
  29565. component.rebuild();
  29566. }
  29567. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  29568. var system = _g[_f];
  29569. system.rebuild();
  29570. }
  29571. };
  29572. /** @hidden */
  29573. Scene.prototype._rebuildTextures = function () {
  29574. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29575. var texture = _a[_i];
  29576. texture._rebuild();
  29577. }
  29578. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29579. };
  29580. // Tags
  29581. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29582. if (tagsQuery === undefined) {
  29583. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29584. return list;
  29585. }
  29586. var listByTags = [];
  29587. forEach = forEach || (function (item) { return; });
  29588. for (var i in list) {
  29589. var item = list[i];
  29590. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29591. listByTags.push(item);
  29592. forEach(item);
  29593. }
  29594. }
  29595. return listByTags;
  29596. };
  29597. /**
  29598. * Get a list of meshes by tags
  29599. * @param tagsQuery defines the tags query to use
  29600. * @param forEach defines a predicate used to filter results
  29601. * @returns an array of Mesh
  29602. */
  29603. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29604. return this._getByTags(this.meshes, tagsQuery, forEach);
  29605. };
  29606. /**
  29607. * Get a list of cameras by tags
  29608. * @param tagsQuery defines the tags query to use
  29609. * @param forEach defines a predicate used to filter results
  29610. * @returns an array of Camera
  29611. */
  29612. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29613. return this._getByTags(this.cameras, tagsQuery, forEach);
  29614. };
  29615. /**
  29616. * Get a list of lights by tags
  29617. * @param tagsQuery defines the tags query to use
  29618. * @param forEach defines a predicate used to filter results
  29619. * @returns an array of Light
  29620. */
  29621. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29622. return this._getByTags(this.lights, tagsQuery, forEach);
  29623. };
  29624. /**
  29625. * Get a list of materials by tags
  29626. * @param tagsQuery defines the tags query to use
  29627. * @param forEach defines a predicate used to filter results
  29628. * @returns an array of Material
  29629. */
  29630. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29631. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29632. };
  29633. /**
  29634. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29635. * This allowed control for front to back rendering or reversly depending of the special needs.
  29636. *
  29637. * @param renderingGroupId The rendering group id corresponding to its index
  29638. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29639. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29640. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29641. */
  29642. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29643. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29644. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29645. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29646. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29647. };
  29648. /**
  29649. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29650. *
  29651. * @param renderingGroupId The rendering group id corresponding to its index
  29652. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29653. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29654. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29655. */
  29656. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29657. if (depth === void 0) { depth = true; }
  29658. if (stencil === void 0) { stencil = true; }
  29659. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29660. };
  29661. /**
  29662. * Gets the current auto clear configuration for one rendering group of the rendering
  29663. * manager.
  29664. * @param index the rendering group index to get the information for
  29665. * @returns The auto clear setup for the requested rendering group
  29666. */
  29667. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  29668. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  29669. };
  29670. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  29671. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  29672. get: function () {
  29673. return this._blockMaterialDirtyMechanism;
  29674. },
  29675. set: function (value) {
  29676. if (this._blockMaterialDirtyMechanism === value) {
  29677. return;
  29678. }
  29679. this._blockMaterialDirtyMechanism = value;
  29680. if (!value) { // Do a complete update
  29681. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  29682. }
  29683. },
  29684. enumerable: true,
  29685. configurable: true
  29686. });
  29687. /**
  29688. * Will flag all materials as dirty to trigger new shader compilation
  29689. * @param flag defines the flag used to specify which material part must be marked as dirty
  29690. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29691. */
  29692. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29693. if (this._blockMaterialDirtyMechanism) {
  29694. return;
  29695. }
  29696. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29697. var material = _a[_i];
  29698. if (predicate && !predicate(material)) {
  29699. continue;
  29700. }
  29701. material.markAsDirty(flag);
  29702. }
  29703. };
  29704. /** @hidden */
  29705. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29706. var _this = this;
  29707. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29708. this._activeRequests.push(request);
  29709. request.onCompleteObservable.add(function (request) {
  29710. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29711. });
  29712. return request;
  29713. };
  29714. /** @hidden */
  29715. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29716. var _this = this;
  29717. return new Promise(function (resolve, reject) {
  29718. _this._loadFile(url, function (data) {
  29719. resolve(data);
  29720. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29721. reject(exception);
  29722. });
  29723. });
  29724. };
  29725. // Statics
  29726. Scene._uniqueIdCounter = 0;
  29727. /** The fog is deactivated */
  29728. Scene.FOGMODE_NONE = 0;
  29729. /** The fog density is following an exponential function */
  29730. Scene.FOGMODE_EXP = 1;
  29731. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  29732. Scene.FOGMODE_EXP2 = 2;
  29733. /** The fog density is following a linear function. */
  29734. Scene.FOGMODE_LINEAR = 3;
  29735. /**
  29736. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29737. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29738. */
  29739. Scene.MinDeltaTime = 1.0;
  29740. /**
  29741. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29742. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29743. */
  29744. Scene.MaxDeltaTime = 1000.0;
  29745. /** The distance in pixel that you have to move to prevent some events */
  29746. Scene.DragMovementThreshold = 10; // in pixels
  29747. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29748. Scene.LongPressDelay = 500; // in milliseconds
  29749. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29750. Scene.DoubleClickDelay = 300; // in milliseconds
  29751. /** If you need to check double click without raising a single click at first click, enable this flag */
  29752. Scene.ExclusiveDoubleClickMode = false;
  29753. return Scene;
  29754. }(BABYLON.AbstractScene));
  29755. BABYLON.Scene = Scene;
  29756. })(BABYLON || (BABYLON = {}));
  29757. //# sourceMappingURL=babylon.scene.js.map
  29758. var BABYLON;
  29759. (function (BABYLON) {
  29760. /**
  29761. * Set of assets to keep when moving a scene into an asset container.
  29762. */
  29763. var KeepAssets = /** @class */ (function (_super) {
  29764. __extends(KeepAssets, _super);
  29765. function KeepAssets() {
  29766. return _super !== null && _super.apply(this, arguments) || this;
  29767. }
  29768. return KeepAssets;
  29769. }(BABYLON.AbstractScene));
  29770. BABYLON.KeepAssets = KeepAssets;
  29771. /**
  29772. * Container with a set of assets that can be added or removed from a scene.
  29773. */
  29774. var AssetContainer = /** @class */ (function (_super) {
  29775. __extends(AssetContainer, _super);
  29776. /**
  29777. * Instantiates an AssetContainer.
  29778. * @param scene The scene the AssetContainer belongs to.
  29779. */
  29780. function AssetContainer(scene) {
  29781. var _this = _super.call(this) || this;
  29782. _this.scene = scene;
  29783. return _this;
  29784. }
  29785. /**
  29786. * Adds all the assets from the container to the scene.
  29787. */
  29788. AssetContainer.prototype.addAllToScene = function () {
  29789. var _this = this;
  29790. this.cameras.forEach(function (o) {
  29791. _this.scene.addCamera(o);
  29792. });
  29793. this.lights.forEach(function (o) {
  29794. _this.scene.addLight(o);
  29795. });
  29796. this.meshes.forEach(function (o) {
  29797. _this.scene.addMesh(o);
  29798. });
  29799. this.skeletons.forEach(function (o) {
  29800. _this.scene.addSkeleton(o);
  29801. });
  29802. this.animations.forEach(function (o) {
  29803. _this.scene.addAnimation(o);
  29804. });
  29805. this.animationGroups.forEach(function (o) {
  29806. _this.scene.addAnimationGroup(o);
  29807. });
  29808. this.multiMaterials.forEach(function (o) {
  29809. _this.scene.addMultiMaterial(o);
  29810. });
  29811. this.materials.forEach(function (o) {
  29812. _this.scene.addMaterial(o);
  29813. });
  29814. this.morphTargetManagers.forEach(function (o) {
  29815. _this.scene.addMorphTargetManager(o);
  29816. });
  29817. this.geometries.forEach(function (o) {
  29818. _this.scene.addGeometry(o);
  29819. });
  29820. this.transformNodes.forEach(function (o) {
  29821. _this.scene.addTransformNode(o);
  29822. });
  29823. this.actionManagers.forEach(function (o) {
  29824. _this.scene.addActionManager(o);
  29825. });
  29826. this.textures.forEach(function (o) {
  29827. _this.scene.addTexture(o);
  29828. });
  29829. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29830. var component = _a[_i];
  29831. component.addFromContainer(this.scene);
  29832. }
  29833. };
  29834. /**
  29835. * Removes all the assets in the container from the scene
  29836. */
  29837. AssetContainer.prototype.removeAllFromScene = function () {
  29838. var _this = this;
  29839. this.cameras.forEach(function (o) {
  29840. _this.scene.removeCamera(o);
  29841. });
  29842. this.lights.forEach(function (o) {
  29843. _this.scene.removeLight(o);
  29844. });
  29845. this.meshes.forEach(function (o) {
  29846. _this.scene.removeMesh(o);
  29847. });
  29848. this.skeletons.forEach(function (o) {
  29849. _this.scene.removeSkeleton(o);
  29850. });
  29851. this.animations.forEach(function (o) {
  29852. _this.scene.removeAnimation(o);
  29853. });
  29854. this.animationGroups.forEach(function (o) {
  29855. _this.scene.removeAnimationGroup(o);
  29856. });
  29857. this.multiMaterials.forEach(function (o) {
  29858. _this.scene.removeMultiMaterial(o);
  29859. });
  29860. this.materials.forEach(function (o) {
  29861. _this.scene.removeMaterial(o);
  29862. });
  29863. this.morphTargetManagers.forEach(function (o) {
  29864. _this.scene.removeMorphTargetManager(o);
  29865. });
  29866. this.geometries.forEach(function (o) {
  29867. _this.scene.removeGeometry(o);
  29868. });
  29869. this.transformNodes.forEach(function (o) {
  29870. _this.scene.removeTransformNode(o);
  29871. });
  29872. this.actionManagers.forEach(function (o) {
  29873. _this.scene.removeActionManager(o);
  29874. });
  29875. this.textures.forEach(function (o) {
  29876. _this.scene.removeTexture(o);
  29877. });
  29878. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29879. var component = _a[_i];
  29880. component.removeFromContainer(this.scene);
  29881. }
  29882. };
  29883. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29884. if (!sourceAssets) {
  29885. return;
  29886. }
  29887. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29888. var asset = sourceAssets_1[_i];
  29889. var move = true;
  29890. if (keepAssets) {
  29891. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29892. var keepAsset = keepAssets_1[_a];
  29893. if (asset === keepAsset) {
  29894. move = false;
  29895. break;
  29896. }
  29897. }
  29898. }
  29899. if (move) {
  29900. targetAssets.push(asset);
  29901. }
  29902. }
  29903. };
  29904. /**
  29905. * Removes all the assets contained in the scene and adds them to the container.
  29906. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29907. */
  29908. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29909. if (keepAssets === undefined) {
  29910. keepAssets = new KeepAssets();
  29911. }
  29912. for (var key in this) {
  29913. if (this.hasOwnProperty(key)) {
  29914. this[key] = this[key] || [];
  29915. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29916. }
  29917. }
  29918. this.removeAllFromScene();
  29919. };
  29920. /**
  29921. * 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.
  29922. * @returns the root mesh
  29923. */
  29924. AssetContainer.prototype.createRootMesh = function () {
  29925. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29926. this.meshes.forEach(function (m) {
  29927. if (!m.parent) {
  29928. rootMesh.addChild(m);
  29929. }
  29930. });
  29931. this.meshes.unshift(rootMesh);
  29932. return rootMesh;
  29933. };
  29934. return AssetContainer;
  29935. }(BABYLON.AbstractScene));
  29936. BABYLON.AssetContainer = AssetContainer;
  29937. })(BABYLON || (BABYLON = {}));
  29938. //# sourceMappingURL=babylon.assetContainer.js.map
  29939. var BABYLON;
  29940. (function (BABYLON) {
  29941. /**
  29942. * Class used to store data that will be store in GPU memory
  29943. */
  29944. var Buffer = /** @class */ (function () {
  29945. /**
  29946. * Constructor
  29947. * @param engine the engine
  29948. * @param data the data to use for this buffer
  29949. * @param updatable whether the data is updatable
  29950. * @param stride the stride (optional)
  29951. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29952. * @param instanced whether the buffer is instanced (optional)
  29953. * @param useBytes set to true if the stride in in bytes (optional)
  29954. */
  29955. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29956. if (stride === void 0) { stride = 0; }
  29957. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29958. if (instanced === void 0) { instanced = false; }
  29959. if (useBytes === void 0) { useBytes = false; }
  29960. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29961. this._engine = engine.getScene().getEngine();
  29962. }
  29963. else {
  29964. this._engine = engine;
  29965. }
  29966. this._updatable = updatable;
  29967. this._instanced = instanced;
  29968. this._data = data;
  29969. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29970. if (!postponeInternalCreation) { // by default
  29971. this.create();
  29972. }
  29973. }
  29974. /**
  29975. * Create a new VertexBuffer based on the current buffer
  29976. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29977. * @param offset defines offset in the buffer (0 by default)
  29978. * @param size defines the size in floats of attributes (position is 3 for instance)
  29979. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29980. * @param instanced defines if the vertex buffer contains indexed data
  29981. * @param useBytes defines if the offset and stride are in bytes
  29982. * @returns the new vertex buffer
  29983. */
  29984. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29985. if (useBytes === void 0) { useBytes = false; }
  29986. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29987. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29988. // a lot of these parameters are ignored as they are overriden by the buffer
  29989. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29990. };
  29991. // Properties
  29992. /**
  29993. * Gets a boolean indicating if the Buffer is updatable?
  29994. * @returns true if the buffer is updatable
  29995. */
  29996. Buffer.prototype.isUpdatable = function () {
  29997. return this._updatable;
  29998. };
  29999. /**
  30000. * Gets current buffer's data
  30001. * @returns a DataArray or null
  30002. */
  30003. Buffer.prototype.getData = function () {
  30004. return this._data;
  30005. };
  30006. /**
  30007. * Gets underlying native buffer
  30008. * @returns underlying native buffer
  30009. */
  30010. Buffer.prototype.getBuffer = function () {
  30011. return this._buffer;
  30012. };
  30013. /**
  30014. * Gets the stride in float32 units (i.e. byte stride / 4).
  30015. * May not be an integer if the byte stride is not divisible by 4.
  30016. * DEPRECATED. Use byteStride instead.
  30017. * @returns the stride in float32 units
  30018. */
  30019. Buffer.prototype.getStrideSize = function () {
  30020. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  30021. };
  30022. // Methods
  30023. /**
  30024. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  30025. * @param data defines the data to store
  30026. */
  30027. Buffer.prototype.create = function (data) {
  30028. if (data === void 0) { data = null; }
  30029. if (!data && this._buffer) {
  30030. return; // nothing to do
  30031. }
  30032. data = data || this._data;
  30033. if (!data) {
  30034. return;
  30035. }
  30036. if (!this._buffer) { // create buffer
  30037. if (this._updatable) {
  30038. this._buffer = this._engine.createDynamicVertexBuffer(data);
  30039. this._data = data;
  30040. }
  30041. else {
  30042. this._buffer = this._engine.createVertexBuffer(data);
  30043. }
  30044. }
  30045. else if (this._updatable) { // update buffer
  30046. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  30047. this._data = data;
  30048. }
  30049. };
  30050. /** @hidden */
  30051. Buffer.prototype._rebuild = function () {
  30052. this._buffer = null;
  30053. this.create(this._data);
  30054. };
  30055. /**
  30056. * Update current buffer data
  30057. * @param data defines the data to store
  30058. */
  30059. Buffer.prototype.update = function (data) {
  30060. this.create(data);
  30061. };
  30062. /**
  30063. * Updates the data directly.
  30064. * @param data the new data
  30065. * @param offset the new offset
  30066. * @param vertexCount the vertex count (optional)
  30067. * @param useBytes set to true if the offset is in bytes
  30068. */
  30069. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  30070. if (useBytes === void 0) { useBytes = false; }
  30071. if (!this._buffer) {
  30072. return;
  30073. }
  30074. if (this._updatable) { // update buffer
  30075. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  30076. this._data = null;
  30077. }
  30078. };
  30079. /**
  30080. * Release all resources
  30081. */
  30082. Buffer.prototype.dispose = function () {
  30083. if (!this._buffer) {
  30084. return;
  30085. }
  30086. if (this._engine._releaseBuffer(this._buffer)) {
  30087. this._buffer = null;
  30088. }
  30089. };
  30090. return Buffer;
  30091. }());
  30092. BABYLON.Buffer = Buffer;
  30093. })(BABYLON || (BABYLON = {}));
  30094. //# sourceMappingURL=babylon.buffer.js.map
  30095. var BABYLON;
  30096. (function (BABYLON) {
  30097. /**
  30098. * Specialized buffer used to store vertex data
  30099. */
  30100. var VertexBuffer = /** @class */ (function () {
  30101. /**
  30102. * Constructor
  30103. * @param engine the engine
  30104. * @param data the data to use for this vertex buffer
  30105. * @param kind the vertex buffer kind
  30106. * @param updatable whether the data is updatable
  30107. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  30108. * @param stride the stride (optional)
  30109. * @param instanced whether the buffer is instanced (optional)
  30110. * @param offset the offset of the data (optional)
  30111. * @param size the number of components (optional)
  30112. * @param type the type of the component (optional)
  30113. * @param normalized whether the data contains normalized data (optional)
  30114. * @param useBytes set to true if stride and offset are in bytes (optional)
  30115. */
  30116. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  30117. if (normalized === void 0) { normalized = false; }
  30118. if (useBytes === void 0) { useBytes = false; }
  30119. if (data instanceof BABYLON.Buffer) {
  30120. this._buffer = data;
  30121. this._ownsBuffer = false;
  30122. }
  30123. else {
  30124. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  30125. this._ownsBuffer = true;
  30126. }
  30127. this._kind = kind;
  30128. if (type == undefined) {
  30129. var data_1 = this.getData();
  30130. this.type = VertexBuffer.FLOAT;
  30131. if (data_1 instanceof Int8Array) {
  30132. this.type = VertexBuffer.BYTE;
  30133. }
  30134. else if (data_1 instanceof Uint8Array) {
  30135. this.type = VertexBuffer.UNSIGNED_BYTE;
  30136. }
  30137. else if (data_1 instanceof Int16Array) {
  30138. this.type = VertexBuffer.SHORT;
  30139. }
  30140. else if (data_1 instanceof Uint16Array) {
  30141. this.type = VertexBuffer.UNSIGNED_SHORT;
  30142. }
  30143. else if (data_1 instanceof Int32Array) {
  30144. this.type = VertexBuffer.INT;
  30145. }
  30146. else if (data_1 instanceof Uint32Array) {
  30147. this.type = VertexBuffer.UNSIGNED_INT;
  30148. }
  30149. }
  30150. else {
  30151. this.type = type;
  30152. }
  30153. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  30154. if (useBytes) {
  30155. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  30156. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  30157. this.byteOffset = offset || 0;
  30158. }
  30159. else {
  30160. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  30161. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  30162. this.byteOffset = (offset || 0) * typeByteLength;
  30163. }
  30164. this.normalized = normalized;
  30165. this._instanced = instanced !== undefined ? instanced : false;
  30166. this._instanceDivisor = instanced ? 1 : 0;
  30167. }
  30168. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  30169. /**
  30170. * Gets or sets the instance divisor when in instanced mode
  30171. */
  30172. get: function () {
  30173. return this._instanceDivisor;
  30174. },
  30175. set: function (value) {
  30176. this._instanceDivisor = value;
  30177. if (value == 0) {
  30178. this._instanced = false;
  30179. }
  30180. else {
  30181. this._instanced = true;
  30182. }
  30183. },
  30184. enumerable: true,
  30185. configurable: true
  30186. });
  30187. /** @hidden */
  30188. VertexBuffer.prototype._rebuild = function () {
  30189. if (!this._buffer) {
  30190. return;
  30191. }
  30192. this._buffer._rebuild();
  30193. };
  30194. /**
  30195. * Returns the kind of the VertexBuffer (string)
  30196. * @returns a string
  30197. */
  30198. VertexBuffer.prototype.getKind = function () {
  30199. return this._kind;
  30200. };
  30201. // Properties
  30202. /**
  30203. * Gets a boolean indicating if the VertexBuffer is updatable?
  30204. * @returns true if the buffer is updatable
  30205. */
  30206. VertexBuffer.prototype.isUpdatable = function () {
  30207. return this._buffer.isUpdatable();
  30208. };
  30209. /**
  30210. * Gets current buffer's data
  30211. * @returns a DataArray or null
  30212. */
  30213. VertexBuffer.prototype.getData = function () {
  30214. return this._buffer.getData();
  30215. };
  30216. /**
  30217. * Gets underlying native buffer
  30218. * @returns underlying native buffer
  30219. */
  30220. VertexBuffer.prototype.getBuffer = function () {
  30221. return this._buffer.getBuffer();
  30222. };
  30223. /**
  30224. * Gets the stride in float32 units (i.e. byte stride / 4).
  30225. * May not be an integer if the byte stride is not divisible by 4.
  30226. * DEPRECATED. Use byteStride instead.
  30227. * @returns the stride in float32 units
  30228. */
  30229. VertexBuffer.prototype.getStrideSize = function () {
  30230. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  30231. };
  30232. /**
  30233. * Returns the offset as a multiple of the type byte length.
  30234. * DEPRECATED. Use byteOffset instead.
  30235. * @returns the offset in bytes
  30236. */
  30237. VertexBuffer.prototype.getOffset = function () {
  30238. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  30239. };
  30240. /**
  30241. * Returns the number of components per vertex attribute (integer)
  30242. * @returns the size in float
  30243. */
  30244. VertexBuffer.prototype.getSize = function () {
  30245. return this._size;
  30246. };
  30247. /**
  30248. * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced
  30249. * @returns true if this buffer is instanced
  30250. */
  30251. VertexBuffer.prototype.getIsInstanced = function () {
  30252. return this._instanced;
  30253. };
  30254. /**
  30255. * Returns the instancing divisor, zero for non-instanced (integer).
  30256. * @returns a number
  30257. */
  30258. VertexBuffer.prototype.getInstanceDivisor = function () {
  30259. return this._instanceDivisor;
  30260. };
  30261. // Methods
  30262. /**
  30263. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  30264. * @param data defines the data to store
  30265. */
  30266. VertexBuffer.prototype.create = function (data) {
  30267. this._buffer.create(data);
  30268. };
  30269. /**
  30270. * Updates the underlying buffer according to the passed numeric array or Float32Array.
  30271. * This function will create a new buffer if the current one is not updatable
  30272. * @param data defines the data to store
  30273. */
  30274. VertexBuffer.prototype.update = function (data) {
  30275. this._buffer.update(data);
  30276. };
  30277. /**
  30278. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  30279. * Returns the directly updated WebGLBuffer.
  30280. * @param data the new data
  30281. * @param offset the new offset
  30282. * @param useBytes set to true if the offset is in bytes
  30283. */
  30284. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  30285. if (useBytes === void 0) { useBytes = false; }
  30286. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  30287. };
  30288. /**
  30289. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  30290. */
  30291. VertexBuffer.prototype.dispose = function () {
  30292. if (this._ownsBuffer) {
  30293. this._buffer.dispose();
  30294. }
  30295. };
  30296. /**
  30297. * Enumerates each value of this vertex buffer as numbers.
  30298. * @param count the number of values to enumerate
  30299. * @param callback the callback function called for each value
  30300. */
  30301. VertexBuffer.prototype.forEach = function (count, callback) {
  30302. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  30303. };
  30304. /**
  30305. * Deduces the stride given a kind.
  30306. * @param kind The kind string to deduce
  30307. * @returns The deduced stride
  30308. */
  30309. VertexBuffer.DeduceStride = function (kind) {
  30310. switch (kind) {
  30311. case VertexBuffer.UVKind:
  30312. case VertexBuffer.UV2Kind:
  30313. case VertexBuffer.UV3Kind:
  30314. case VertexBuffer.UV4Kind:
  30315. case VertexBuffer.UV5Kind:
  30316. case VertexBuffer.UV6Kind:
  30317. return 2;
  30318. case VertexBuffer.NormalKind:
  30319. case VertexBuffer.PositionKind:
  30320. return 3;
  30321. case VertexBuffer.ColorKind:
  30322. case VertexBuffer.MatricesIndicesKind:
  30323. case VertexBuffer.MatricesIndicesExtraKind:
  30324. case VertexBuffer.MatricesWeightsKind:
  30325. case VertexBuffer.MatricesWeightsExtraKind:
  30326. case VertexBuffer.TangentKind:
  30327. return 4;
  30328. default:
  30329. throw new Error("Invalid kind '" + kind + "'");
  30330. }
  30331. };
  30332. /**
  30333. * Gets the byte length of the given type.
  30334. * @param type the type
  30335. * @returns the number of bytes
  30336. */
  30337. VertexBuffer.GetTypeByteLength = function (type) {
  30338. switch (type) {
  30339. case VertexBuffer.BYTE:
  30340. case VertexBuffer.UNSIGNED_BYTE:
  30341. return 1;
  30342. case VertexBuffer.SHORT:
  30343. case VertexBuffer.UNSIGNED_SHORT:
  30344. return 2;
  30345. case VertexBuffer.INT:
  30346. case VertexBuffer.FLOAT:
  30347. return 4;
  30348. default:
  30349. throw new Error("Invalid type '" + type + "'");
  30350. }
  30351. };
  30352. /**
  30353. * Enumerates each value of the given parameters as numbers.
  30354. * @param data the data to enumerate
  30355. * @param byteOffset the byte offset of the data
  30356. * @param byteStride the byte stride of the data
  30357. * @param componentCount the number of components per element
  30358. * @param componentType the type of the component
  30359. * @param count the total number of components
  30360. * @param normalized whether the data is normalized
  30361. * @param callback the callback function called for each value
  30362. */
  30363. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30364. if (data instanceof Array) {
  30365. var offset = byteOffset / 4;
  30366. var stride = byteStride / 4;
  30367. for (var index = 0; index < count; index += componentCount) {
  30368. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30369. callback(data[offset + componentIndex], index + componentIndex);
  30370. }
  30371. offset += stride;
  30372. }
  30373. }
  30374. else {
  30375. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30376. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30377. for (var index = 0; index < count; index += componentCount) {
  30378. var componentByteOffset = byteOffset;
  30379. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30380. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30381. callback(value, index + componentIndex);
  30382. componentByteOffset += componentByteLength;
  30383. }
  30384. byteOffset += byteStride;
  30385. }
  30386. }
  30387. };
  30388. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30389. switch (type) {
  30390. case VertexBuffer.BYTE: {
  30391. var value = dataView.getInt8(byteOffset);
  30392. if (normalized) {
  30393. value = Math.max(value / 127, -1);
  30394. }
  30395. return value;
  30396. }
  30397. case VertexBuffer.UNSIGNED_BYTE: {
  30398. var value = dataView.getUint8(byteOffset);
  30399. if (normalized) {
  30400. value = value / 255;
  30401. }
  30402. return value;
  30403. }
  30404. case VertexBuffer.SHORT: {
  30405. var value = dataView.getInt16(byteOffset, true);
  30406. if (normalized) {
  30407. value = Math.max(value / 16383, -1);
  30408. }
  30409. return value;
  30410. }
  30411. case VertexBuffer.UNSIGNED_SHORT: {
  30412. var value = dataView.getUint16(byteOffset, true);
  30413. if (normalized) {
  30414. value = value / 65535;
  30415. }
  30416. return value;
  30417. }
  30418. case VertexBuffer.FLOAT: {
  30419. return dataView.getFloat32(byteOffset, true);
  30420. }
  30421. default: {
  30422. throw new Error("Invalid component type " + type);
  30423. }
  30424. }
  30425. };
  30426. /**
  30427. * The byte type.
  30428. */
  30429. VertexBuffer.BYTE = 5120;
  30430. /**
  30431. * The unsigned byte type.
  30432. */
  30433. VertexBuffer.UNSIGNED_BYTE = 5121;
  30434. /**
  30435. * The short type.
  30436. */
  30437. VertexBuffer.SHORT = 5122;
  30438. /**
  30439. * The unsigned short type.
  30440. */
  30441. VertexBuffer.UNSIGNED_SHORT = 5123;
  30442. /**
  30443. * The integer type.
  30444. */
  30445. VertexBuffer.INT = 5124;
  30446. /**
  30447. * The unsigned integer type.
  30448. */
  30449. VertexBuffer.UNSIGNED_INT = 5125;
  30450. /**
  30451. * The float type.
  30452. */
  30453. VertexBuffer.FLOAT = 5126;
  30454. // Enums
  30455. /**
  30456. * Positions
  30457. */
  30458. VertexBuffer.PositionKind = "position";
  30459. /**
  30460. * Normals
  30461. */
  30462. VertexBuffer.NormalKind = "normal";
  30463. /**
  30464. * Tangents
  30465. */
  30466. VertexBuffer.TangentKind = "tangent";
  30467. /**
  30468. * Texture coordinates
  30469. */
  30470. VertexBuffer.UVKind = "uv";
  30471. /**
  30472. * Texture coordinates 2
  30473. */
  30474. VertexBuffer.UV2Kind = "uv2";
  30475. /**
  30476. * Texture coordinates 3
  30477. */
  30478. VertexBuffer.UV3Kind = "uv3";
  30479. /**
  30480. * Texture coordinates 4
  30481. */
  30482. VertexBuffer.UV4Kind = "uv4";
  30483. /**
  30484. * Texture coordinates 5
  30485. */
  30486. VertexBuffer.UV5Kind = "uv5";
  30487. /**
  30488. * Texture coordinates 6
  30489. */
  30490. VertexBuffer.UV6Kind = "uv6";
  30491. /**
  30492. * Colors
  30493. */
  30494. VertexBuffer.ColorKind = "color";
  30495. /**
  30496. * Matrix indices (for bones)
  30497. */
  30498. VertexBuffer.MatricesIndicesKind = "matricesIndices";
  30499. /**
  30500. * Matrix weights (for bones)
  30501. */
  30502. VertexBuffer.MatricesWeightsKind = "matricesWeights";
  30503. /**
  30504. * Additional matrix indices (for bones)
  30505. */
  30506. VertexBuffer.MatricesIndicesExtraKind = "matricesIndicesExtra";
  30507. /**
  30508. * Additional matrix weights (for bones)
  30509. */
  30510. VertexBuffer.MatricesWeightsExtraKind = "matricesWeightsExtra";
  30511. return VertexBuffer;
  30512. }());
  30513. BABYLON.VertexBuffer = VertexBuffer;
  30514. })(BABYLON || (BABYLON = {}));
  30515. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30516. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  30517. var BABYLON;
  30518. (function (BABYLON) {
  30519. /**
  30520. * Internal class used by the engine to get list of InternalTexture already bound to the GL context
  30521. */
  30522. var DummyInternalTextureTracker = /** @class */ (function () {
  30523. function DummyInternalTextureTracker() {
  30524. /**
  30525. * Gets or set the previous tracker in the list
  30526. */
  30527. this.previous = null;
  30528. /**
  30529. * Gets or set the next tracker in the list
  30530. */
  30531. this.next = null;
  30532. }
  30533. return DummyInternalTextureTracker;
  30534. }());
  30535. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30536. })(BABYLON || (BABYLON = {}));
  30537. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30538. var BABYLON;
  30539. (function (BABYLON) {
  30540. /**
  30541. * Class used to store data associated with WebGL texture data for the engine
  30542. * This class should not be used directly
  30543. */
  30544. var InternalTexture = /** @class */ (function () {
  30545. /**
  30546. * Creates a new InternalTexture
  30547. * @param engine defines the engine to use
  30548. * @param dataSource defines the type of data that will be used
  30549. */
  30550. function InternalTexture(engine, dataSource) {
  30551. /**
  30552. * Observable called when the texture is loaded
  30553. */
  30554. this.onLoadedObservable = new BABYLON.Observable();
  30555. /**
  30556. * Gets or set the previous tracker in the list
  30557. */
  30558. this.previous = null;
  30559. /**
  30560. * Gets or set the next tracker in the list
  30561. */
  30562. this.next = null;
  30563. // Private
  30564. /** @hidden */
  30565. this._initialSlot = -1;
  30566. /** @hidden */
  30567. this._designatedSlot = -1;
  30568. /** @hidden */
  30569. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30570. /** @hidden */
  30571. this._comparisonFunction = 0;
  30572. /** @hidden */
  30573. this._sphericalPolynomial = null;
  30574. /** @hidden */
  30575. this._lodGenerationScale = 0;
  30576. /** @hidden */
  30577. this._lodGenerationOffset = 0;
  30578. /** @hidden */
  30579. this._isRGBD = false;
  30580. /** @hidden */
  30581. this._references = 1;
  30582. this._engine = engine;
  30583. this._dataSource = dataSource;
  30584. this._webGLTexture = engine._createTexture();
  30585. }
  30586. /**
  30587. * Gets the Engine the texture belongs to.
  30588. * @returns The babylon engine
  30589. */
  30590. InternalTexture.prototype.getEngine = function () {
  30591. return this._engine;
  30592. };
  30593. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30594. /**
  30595. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30596. */
  30597. get: function () {
  30598. return this._dataSource;
  30599. },
  30600. enumerable: true,
  30601. configurable: true
  30602. });
  30603. /**
  30604. * Increments the number of references (ie. the number of Texture that point to it)
  30605. */
  30606. InternalTexture.prototype.incrementReferences = function () {
  30607. this._references++;
  30608. };
  30609. /**
  30610. * Change the size of the texture (not the size of the content)
  30611. * @param width defines the new width
  30612. * @param height defines the new height
  30613. * @param depth defines the new depth (1 by default)
  30614. */
  30615. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30616. if (depth === void 0) { depth = 1; }
  30617. this.width = width;
  30618. this.height = height;
  30619. this.depth = depth;
  30620. this.baseWidth = width;
  30621. this.baseHeight = height;
  30622. this.baseDepth = depth;
  30623. this._size = width * height * depth;
  30624. };
  30625. /** @hidden */
  30626. InternalTexture.prototype._rebuild = function () {
  30627. var _this = this;
  30628. var proxy;
  30629. this.isReady = false;
  30630. this._cachedCoordinatesMode = null;
  30631. this._cachedWrapU = null;
  30632. this._cachedWrapV = null;
  30633. this._cachedAnisotropicFilteringLevel = null;
  30634. switch (this._dataSource) {
  30635. case InternalTexture.DATASOURCE_TEMP:
  30636. return;
  30637. case InternalTexture.DATASOURCE_URL:
  30638. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30639. _this.isReady = true;
  30640. }, null, this._buffer, undefined, this.format);
  30641. proxy._swapAndDie(this);
  30642. return;
  30643. case InternalTexture.DATASOURCE_RAW:
  30644. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30645. proxy._swapAndDie(this);
  30646. this.isReady = true;
  30647. return;
  30648. case InternalTexture.DATASOURCE_RAW3D:
  30649. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30650. proxy._swapAndDie(this);
  30651. this.isReady = true;
  30652. return;
  30653. case InternalTexture.DATASOURCE_DYNAMIC:
  30654. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30655. proxy._swapAndDie(this);
  30656. // The engine will make sure to update content so no need to flag it as isReady = true
  30657. return;
  30658. case InternalTexture.DATASOURCE_RENDERTARGET:
  30659. var options = new BABYLON.RenderTargetCreationOptions();
  30660. options.generateDepthBuffer = this._generateDepthBuffer;
  30661. options.generateMipMaps = this.generateMipMaps;
  30662. options.generateStencilBuffer = this._generateStencilBuffer;
  30663. options.samplingMode = this.samplingMode;
  30664. options.type = this.type;
  30665. if (this.isCube) {
  30666. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30667. }
  30668. else {
  30669. var size = {
  30670. width: this.width,
  30671. height: this.height
  30672. };
  30673. proxy = this._engine.createRenderTargetTexture(size, options);
  30674. }
  30675. proxy._swapAndDie(this);
  30676. this.isReady = true;
  30677. return;
  30678. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30679. var depthTextureOptions = {
  30680. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30681. comparisonFunction: this._comparisonFunction,
  30682. generateStencil: this._generateStencilBuffer,
  30683. isCube: this.isCube
  30684. };
  30685. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30686. proxy._swapAndDie(this);
  30687. this.isReady = true;
  30688. return;
  30689. case InternalTexture.DATASOURCE_CUBE:
  30690. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30691. _this.isReady = true;
  30692. }, null, this.format, this._extension);
  30693. proxy._swapAndDie(this);
  30694. return;
  30695. case InternalTexture.DATASOURCE_CUBERAW:
  30696. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30697. proxy._swapAndDie(this);
  30698. this.isReady = true;
  30699. return;
  30700. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30701. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30702. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30703. _this.isReady = true;
  30704. });
  30705. proxy._swapAndDie(this);
  30706. return;
  30707. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30708. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30709. if (proxy) {
  30710. proxy._swapAndDie(_this);
  30711. }
  30712. _this.isReady = true;
  30713. }, null, this.format, this._extension);
  30714. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30715. return;
  30716. }
  30717. };
  30718. /** @hidden */
  30719. InternalTexture.prototype._swapAndDie = function (target) {
  30720. target._webGLTexture = this._webGLTexture;
  30721. if (this._framebuffer) {
  30722. target._framebuffer = this._framebuffer;
  30723. }
  30724. if (this._depthStencilBuffer) {
  30725. target._depthStencilBuffer = this._depthStencilBuffer;
  30726. }
  30727. if (this._lodTextureHigh) {
  30728. if (target._lodTextureHigh) {
  30729. target._lodTextureHigh.dispose();
  30730. }
  30731. target._lodTextureHigh = this._lodTextureHigh;
  30732. }
  30733. if (this._lodTextureMid) {
  30734. if (target._lodTextureMid) {
  30735. target._lodTextureMid.dispose();
  30736. }
  30737. target._lodTextureMid = this._lodTextureMid;
  30738. }
  30739. if (this._lodTextureLow) {
  30740. if (target._lodTextureLow) {
  30741. target._lodTextureLow.dispose();
  30742. }
  30743. target._lodTextureLow = this._lodTextureLow;
  30744. }
  30745. var cache = this._engine.getLoadedTexturesCache();
  30746. var index = cache.indexOf(this);
  30747. if (index !== -1) {
  30748. cache.splice(index, 1);
  30749. }
  30750. };
  30751. /**
  30752. * Dispose the current allocated resources
  30753. */
  30754. InternalTexture.prototype.dispose = function () {
  30755. if (!this._webGLTexture) {
  30756. return;
  30757. }
  30758. this._references--;
  30759. if (this._references === 0) {
  30760. this._engine._releaseTexture(this);
  30761. this._webGLTexture = null;
  30762. this.previous = null;
  30763. this.next = null;
  30764. }
  30765. };
  30766. /**
  30767. * The source of the texture data is unknown
  30768. */
  30769. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30770. /**
  30771. * Texture data comes from an URL
  30772. */
  30773. InternalTexture.DATASOURCE_URL = 1;
  30774. /**
  30775. * Texture data is only used for temporary storage
  30776. */
  30777. InternalTexture.DATASOURCE_TEMP = 2;
  30778. /**
  30779. * Texture data comes from raw data (ArrayBuffer)
  30780. */
  30781. InternalTexture.DATASOURCE_RAW = 3;
  30782. /**
  30783. * Texture content is dynamic (video or dynamic texture)
  30784. */
  30785. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30786. /**
  30787. * Texture content is generated by rendering to it
  30788. */
  30789. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30790. /**
  30791. * Texture content is part of a multi render target process
  30792. */
  30793. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30794. /**
  30795. * Texture data comes from a cube data file
  30796. */
  30797. InternalTexture.DATASOURCE_CUBE = 7;
  30798. /**
  30799. * Texture data comes from a raw cube data
  30800. */
  30801. InternalTexture.DATASOURCE_CUBERAW = 8;
  30802. /**
  30803. * Texture data come from a prefiltered cube data file
  30804. */
  30805. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30806. /**
  30807. * Texture content is raw 3D data
  30808. */
  30809. InternalTexture.DATASOURCE_RAW3D = 10;
  30810. /**
  30811. * Texture content is a depth texture
  30812. */
  30813. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30814. /**
  30815. * Texture data comes from a raw cube data encoded with RGBD
  30816. */
  30817. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30818. return InternalTexture;
  30819. }());
  30820. BABYLON.InternalTexture = InternalTexture;
  30821. })(BABYLON || (BABYLON = {}));
  30822. //# sourceMappingURL=babylon.internalTexture.js.map
  30823. var BABYLON;
  30824. (function (BABYLON) {
  30825. /**
  30826. * Base class of all the textures in babylon.
  30827. * It groups all the common properties the materials, post process, lights... might need
  30828. * in order to make a correct use of the texture.
  30829. */
  30830. var BaseTexture = /** @class */ (function () {
  30831. /**
  30832. * Instantiates a new BaseTexture.
  30833. * Base class of all the textures in babylon.
  30834. * It groups all the common properties the materials, post process, lights... might need
  30835. * in order to make a correct use of the texture.
  30836. * @param scene Define the scene the texture blongs to
  30837. */
  30838. function BaseTexture(scene) {
  30839. this._hasAlpha = false;
  30840. /**
  30841. * Defines if the alpha value should be determined via the rgb values.
  30842. * If true the luminance of the pixel might be used to find the corresponding alpha value.
  30843. */
  30844. this.getAlphaFromRGB = false;
  30845. /**
  30846. * Intensity or strength of the texture.
  30847. * It is commonly used by materials to fine tune the intensity of the texture
  30848. */
  30849. this.level = 1;
  30850. /**
  30851. * Define the UV chanel to use starting from 0 and defaulting to 0.
  30852. * This is part of the texture as textures usually maps to one uv set.
  30853. */
  30854. this.coordinatesIndex = 0;
  30855. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30856. /**
  30857. * | Value | Type | Description |
  30858. * | ----- | ------------------ | ----------- |
  30859. * | 0 | CLAMP_ADDRESSMODE | |
  30860. * | 1 | WRAP_ADDRESSMODE | |
  30861. * | 2 | MIRROR_ADDRESSMODE | |
  30862. */
  30863. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30864. /**
  30865. * | Value | Type | Description |
  30866. * | ----- | ------------------ | ----------- |
  30867. * | 0 | CLAMP_ADDRESSMODE | |
  30868. * | 1 | WRAP_ADDRESSMODE | |
  30869. * | 2 | MIRROR_ADDRESSMODE | |
  30870. */
  30871. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30872. /**
  30873. * | Value | Type | Description |
  30874. * | ----- | ------------------ | ----------- |
  30875. * | 0 | CLAMP_ADDRESSMODE | |
  30876. * | 1 | WRAP_ADDRESSMODE | |
  30877. * | 2 | MIRROR_ADDRESSMODE | |
  30878. */
  30879. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30880. /**
  30881. * With compliant hardware and browser (supporting anisotropic filtering)
  30882. * this defines the level of anisotropic filtering in the texture.
  30883. * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.
  30884. */
  30885. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30886. /**
  30887. * Define if the texture is a cube texture or if false a 2d texture.
  30888. */
  30889. this.isCube = false;
  30890. /**
  30891. * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.
  30892. */
  30893. this.is3D = false;
  30894. /**
  30895. * Define if the texture contains data in gamma space (most of the png/jpg aside bump).
  30896. * HDR texture are usually stored in linear space.
  30897. * This only impacts the PBR and Background materials
  30898. */
  30899. this.gammaSpace = true;
  30900. /**
  30901. * Is Z inverted in the texture (useful in a cube texture).
  30902. */
  30903. this.invertZ = false;
  30904. /**
  30905. * @hidden
  30906. */
  30907. this.lodLevelInAlpha = false;
  30908. /**
  30909. * Define if the texture is a render target.
  30910. */
  30911. this.isRenderTarget = false;
  30912. /**
  30913. * Define the list of animation attached to the texture.
  30914. */
  30915. this.animations = new Array();
  30916. /**
  30917. * An event triggered when the texture is disposed.
  30918. */
  30919. this.onDisposeObservable = new BABYLON.Observable();
  30920. /**
  30921. * Define the current state of the loading sequence when in delayed load mode.
  30922. */
  30923. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30924. this._cachedSize = BABYLON.Size.Zero();
  30925. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30926. if (this._scene) {
  30927. this._scene.textures.push(this);
  30928. this._scene.onNewTextureAddedObservable.notifyObservers(this);
  30929. }
  30930. this._uid = null;
  30931. }
  30932. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30933. get: function () {
  30934. return this._hasAlpha;
  30935. },
  30936. /**
  30937. * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance).
  30938. */
  30939. set: function (value) {
  30940. if (this._hasAlpha === value) {
  30941. return;
  30942. }
  30943. this._hasAlpha = value;
  30944. if (this._scene) {
  30945. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30946. }
  30947. },
  30948. enumerable: true,
  30949. configurable: true
  30950. });
  30951. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30952. get: function () {
  30953. return this._coordinatesMode;
  30954. },
  30955. /**
  30956. * How a texture is mapped.
  30957. *
  30958. * | Value | Type | Description |
  30959. * | ----- | ----------------------------------- | ----------- |
  30960. * | 0 | EXPLICIT_MODE | |
  30961. * | 1 | SPHERICAL_MODE | |
  30962. * | 2 | PLANAR_MODE | |
  30963. * | 3 | CUBIC_MODE | |
  30964. * | 4 | PROJECTION_MODE | |
  30965. * | 5 | SKYBOX_MODE | |
  30966. * | 6 | INVCUBIC_MODE | |
  30967. * | 7 | EQUIRECTANGULAR_MODE | |
  30968. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30969. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30970. */
  30971. set: function (value) {
  30972. if (this._coordinatesMode === value) {
  30973. return;
  30974. }
  30975. this._coordinatesMode = value;
  30976. if (this._scene) {
  30977. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30978. }
  30979. },
  30980. enumerable: true,
  30981. configurable: true
  30982. });
  30983. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30984. /**
  30985. * Gets whether or not the texture contains RGBD data.
  30986. */
  30987. get: function () {
  30988. return this._texture != null && this._texture._isRGBD;
  30989. },
  30990. enumerable: true,
  30991. configurable: true
  30992. });
  30993. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30994. /**
  30995. * With prefiltered texture, defined the offset used during the prefiltering steps.
  30996. */
  30997. get: function () {
  30998. if (this._texture) {
  30999. return this._texture._lodGenerationOffset;
  31000. }
  31001. return 0.0;
  31002. },
  31003. set: function (value) {
  31004. if (this._texture) {
  31005. this._texture._lodGenerationOffset = value;
  31006. }
  31007. },
  31008. enumerable: true,
  31009. configurable: true
  31010. });
  31011. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  31012. /**
  31013. * With prefiltered texture, defined the scale used during the prefiltering steps.
  31014. */
  31015. get: function () {
  31016. if (this._texture) {
  31017. return this._texture._lodGenerationScale;
  31018. }
  31019. return 0.0;
  31020. },
  31021. set: function (value) {
  31022. if (this._texture) {
  31023. this._texture._lodGenerationScale = value;
  31024. }
  31025. },
  31026. enumerable: true,
  31027. configurable: true
  31028. });
  31029. Object.defineProperty(BaseTexture.prototype, "uid", {
  31030. /**
  31031. * Define the unique id of the texture in the scene.
  31032. */
  31033. get: function () {
  31034. if (!this._uid) {
  31035. this._uid = BABYLON.Tools.RandomId();
  31036. }
  31037. return this._uid;
  31038. },
  31039. enumerable: true,
  31040. configurable: true
  31041. });
  31042. /**
  31043. * Return a string representation of the texture.
  31044. * @returns the texture as a string
  31045. */
  31046. BaseTexture.prototype.toString = function () {
  31047. return this.name;
  31048. };
  31049. /**
  31050. * Get the class name of the texture.
  31051. * @returns "BaseTexture"
  31052. */
  31053. BaseTexture.prototype.getClassName = function () {
  31054. return "BaseTexture";
  31055. };
  31056. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  31057. /**
  31058. * Callback triggered when the texture has been disposed.
  31059. * Kept for back compatibility, you can use the onDisposeObservable instead.
  31060. */
  31061. set: function (callback) {
  31062. if (this._onDisposeObserver) {
  31063. this.onDisposeObservable.remove(this._onDisposeObserver);
  31064. }
  31065. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31066. },
  31067. enumerable: true,
  31068. configurable: true
  31069. });
  31070. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  31071. /**
  31072. * Define if the texture is preventinga material to render or not.
  31073. * If not and the texture is not ready, the engine will use a default black texture instead.
  31074. */
  31075. get: function () {
  31076. return true;
  31077. },
  31078. enumerable: true,
  31079. configurable: true
  31080. });
  31081. /**
  31082. * Get the scene the texture belongs to.
  31083. * @returns the scene or null if undefined
  31084. */
  31085. BaseTexture.prototype.getScene = function () {
  31086. return this._scene;
  31087. };
  31088. /**
  31089. * Get the texture transform matrix used to offset tile the texture for istance.
  31090. * @returns the transformation matrix
  31091. */
  31092. BaseTexture.prototype.getTextureMatrix = function () {
  31093. return BABYLON.Matrix.IdentityReadOnly;
  31094. };
  31095. /**
  31096. * Get the texture reflection matrix used to rotate/transform the reflection.
  31097. * @returns the reflection matrix
  31098. */
  31099. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  31100. return BABYLON.Matrix.IdentityReadOnly;
  31101. };
  31102. /**
  31103. * Get the underlying lower level texture from Babylon.
  31104. * @returns the insternal texture
  31105. */
  31106. BaseTexture.prototype.getInternalTexture = function () {
  31107. return this._texture;
  31108. };
  31109. /**
  31110. * Get if the texture is ready to be consumed (either it is ready or it is not blocking)
  31111. * @returns true if ready or not blocking
  31112. */
  31113. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  31114. return !this.isBlocking || this.isReady();
  31115. };
  31116. /**
  31117. * Get if the texture is ready to be used (downloaded, converted, mip mapped...).
  31118. * @returns true if fully ready
  31119. */
  31120. BaseTexture.prototype.isReady = function () {
  31121. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31122. this.delayLoad();
  31123. return false;
  31124. }
  31125. if (this._texture) {
  31126. return this._texture.isReady;
  31127. }
  31128. return false;
  31129. };
  31130. /**
  31131. * Get the size of the texture.
  31132. * @returns the texture size.
  31133. */
  31134. BaseTexture.prototype.getSize = function () {
  31135. if (this._texture) {
  31136. if (this._texture.width) {
  31137. this._cachedSize.width = this._texture.width;
  31138. this._cachedSize.height = this._texture.height;
  31139. return this._cachedSize;
  31140. }
  31141. if (this._texture._size) {
  31142. this._cachedSize.width = this._texture._size;
  31143. this._cachedSize.height = this._texture._size;
  31144. return this._cachedSize;
  31145. }
  31146. }
  31147. return this._cachedSize;
  31148. };
  31149. /**
  31150. * Get the base size of the texture.
  31151. * It can be different from the size if the texture has been resized for POT for instance
  31152. * @returns the base size
  31153. */
  31154. BaseTexture.prototype.getBaseSize = function () {
  31155. if (!this.isReady() || !this._texture) {
  31156. return BABYLON.Size.Zero();
  31157. }
  31158. if (this._texture._size) {
  31159. return new BABYLON.Size(this._texture._size, this._texture._size);
  31160. }
  31161. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  31162. };
  31163. /**
  31164. * Scales the texture if is `canRescale()`
  31165. * @param ratio the resize factor we want to use to rescale
  31166. */
  31167. BaseTexture.prototype.scale = function (ratio) {
  31168. };
  31169. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  31170. /**
  31171. * Get if the texture can rescale.
  31172. */
  31173. get: function () {
  31174. return false;
  31175. },
  31176. enumerable: true,
  31177. configurable: true
  31178. });
  31179. /** @hidden */
  31180. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  31181. if (!this._scene) {
  31182. return null;
  31183. }
  31184. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  31185. for (var index = 0; index < texturesCache.length; index++) {
  31186. var texturesCacheEntry = texturesCache[index];
  31187. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  31188. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  31189. texturesCacheEntry.incrementReferences();
  31190. return texturesCacheEntry;
  31191. }
  31192. }
  31193. }
  31194. return null;
  31195. };
  31196. /** @hidden */
  31197. BaseTexture.prototype._rebuild = function () {
  31198. };
  31199. /**
  31200. * Triggers the load sequence in delayed load mode.
  31201. */
  31202. BaseTexture.prototype.delayLoad = function () {
  31203. };
  31204. /**
  31205. * Clones the texture.
  31206. * @returns the cloned texture
  31207. */
  31208. BaseTexture.prototype.clone = function () {
  31209. return null;
  31210. };
  31211. Object.defineProperty(BaseTexture.prototype, "textureType", {
  31212. /**
  31213. * Get the texture underlying type (INT, FLOAT...)
  31214. */
  31215. get: function () {
  31216. if (!this._texture) {
  31217. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31218. }
  31219. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31220. },
  31221. enumerable: true,
  31222. configurable: true
  31223. });
  31224. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  31225. /**
  31226. * Get the texture underlying format (RGB, RGBA...)
  31227. */
  31228. get: function () {
  31229. if (!this._texture) {
  31230. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31231. }
  31232. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31233. },
  31234. enumerable: true,
  31235. configurable: true
  31236. });
  31237. /**
  31238. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  31239. * This will returns an RGBA array buffer containing either in values (0-255) or
  31240. * float values (0-1) depending of the underlying buffer type.
  31241. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  31242. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  31243. * @param buffer defines a user defined buffer to fill with data (can be null)
  31244. * @returns The Array buffer containing the pixels data.
  31245. */
  31246. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  31247. if (faceIndex === void 0) { faceIndex = 0; }
  31248. if (level === void 0) { level = 0; }
  31249. if (buffer === void 0) { buffer = null; }
  31250. if (!this._texture) {
  31251. return null;
  31252. }
  31253. var size = this.getSize();
  31254. var width = size.width;
  31255. var height = size.height;
  31256. var scene = this.getScene();
  31257. if (!scene) {
  31258. return null;
  31259. }
  31260. var engine = scene.getEngine();
  31261. if (level != 0) {
  31262. width = width / Math.pow(2, level);
  31263. height = height / Math.pow(2, level);
  31264. width = Math.round(width);
  31265. height = Math.round(height);
  31266. }
  31267. if (this._texture.isCube) {
  31268. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  31269. }
  31270. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  31271. };
  31272. /**
  31273. * Release and destroy the underlying lower level texture aka internalTexture.
  31274. */
  31275. BaseTexture.prototype.releaseInternalTexture = function () {
  31276. if (this._texture) {
  31277. this._texture.dispose();
  31278. this._texture = null;
  31279. }
  31280. };
  31281. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  31282. /**
  31283. * Get the polynomial representation of the texture data.
  31284. * This is mainly use as a fast way to recover IBL Diffuse irradiance data.
  31285. * @see https://learnopengl.com/PBR/IBL/Diffuse-irradiance
  31286. */
  31287. get: function () {
  31288. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  31289. return null;
  31290. }
  31291. if (!this._texture._sphericalPolynomial) {
  31292. this._texture._sphericalPolynomial =
  31293. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  31294. }
  31295. return this._texture._sphericalPolynomial;
  31296. },
  31297. set: function (value) {
  31298. if (this._texture) {
  31299. this._texture._sphericalPolynomial = value;
  31300. }
  31301. },
  31302. enumerable: true,
  31303. configurable: true
  31304. });
  31305. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  31306. /** @hidden */
  31307. get: function () {
  31308. if (this._texture) {
  31309. return this._texture._lodTextureHigh;
  31310. }
  31311. return null;
  31312. },
  31313. enumerable: true,
  31314. configurable: true
  31315. });
  31316. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  31317. /** @hidden */
  31318. get: function () {
  31319. if (this._texture) {
  31320. return this._texture._lodTextureMid;
  31321. }
  31322. return null;
  31323. },
  31324. enumerable: true,
  31325. configurable: true
  31326. });
  31327. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  31328. /** @hidden */
  31329. get: function () {
  31330. if (this._texture) {
  31331. return this._texture._lodTextureLow;
  31332. }
  31333. return null;
  31334. },
  31335. enumerable: true,
  31336. configurable: true
  31337. });
  31338. /**
  31339. * Dispose the texture and release its associated resources.
  31340. */
  31341. BaseTexture.prototype.dispose = function () {
  31342. if (!this._scene) {
  31343. return;
  31344. }
  31345. // Animations
  31346. this._scene.stopAnimation(this);
  31347. // Remove from scene
  31348. this._scene._removePendingData(this);
  31349. var index = this._scene.textures.indexOf(this);
  31350. if (index >= 0) {
  31351. this._scene.textures.splice(index, 1);
  31352. }
  31353. this._scene.onTextureRemovedObservable.notifyObservers(this);
  31354. if (this._texture === undefined) {
  31355. return;
  31356. }
  31357. // Release
  31358. this.releaseInternalTexture();
  31359. // Callback
  31360. this.onDisposeObservable.notifyObservers(this);
  31361. this.onDisposeObservable.clear();
  31362. };
  31363. /**
  31364. * Serialize the texture into a JSON representation that can be parsed later on.
  31365. * @returns the JSON representation of the texture
  31366. */
  31367. BaseTexture.prototype.serialize = function () {
  31368. if (!this.name) {
  31369. return null;
  31370. }
  31371. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31372. // Animations
  31373. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  31374. return serializationObject;
  31375. };
  31376. /**
  31377. * Helper function to be called back once a list of texture contains only ready textures.
  31378. * @param textures Define the list of textures to wait for
  31379. * @param callback Define the callback triggered once the entire list will be ready
  31380. */
  31381. BaseTexture.WhenAllReady = function (textures, callback) {
  31382. var numRemaining = textures.length;
  31383. if (numRemaining === 0) {
  31384. callback();
  31385. return;
  31386. }
  31387. var _loop_1 = function () {
  31388. texture = textures[i];
  31389. if (texture.isReady()) {
  31390. if (--numRemaining === 0) {
  31391. callback();
  31392. }
  31393. }
  31394. else {
  31395. onLoadObservable = texture.onLoadObservable;
  31396. var onLoadCallback_1 = function () {
  31397. onLoadObservable.removeCallback(onLoadCallback_1);
  31398. if (--numRemaining === 0) {
  31399. callback();
  31400. }
  31401. };
  31402. onLoadObservable.add(onLoadCallback_1);
  31403. }
  31404. };
  31405. var texture, onLoadObservable;
  31406. for (var i = 0; i < textures.length; i++) {
  31407. _loop_1();
  31408. }
  31409. };
  31410. /**
  31411. * Default anisotropic filtering level for the application.
  31412. * It is set to 4 as a good tradeoff between perf and quality.
  31413. */
  31414. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  31415. __decorate([
  31416. BABYLON.serialize()
  31417. ], BaseTexture.prototype, "name", void 0);
  31418. __decorate([
  31419. BABYLON.serialize("hasAlpha")
  31420. ], BaseTexture.prototype, "_hasAlpha", void 0);
  31421. __decorate([
  31422. BABYLON.serialize()
  31423. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  31424. __decorate([
  31425. BABYLON.serialize()
  31426. ], BaseTexture.prototype, "level", void 0);
  31427. __decorate([
  31428. BABYLON.serialize()
  31429. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  31430. __decorate([
  31431. BABYLON.serialize("coordinatesMode")
  31432. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  31433. __decorate([
  31434. BABYLON.serialize()
  31435. ], BaseTexture.prototype, "wrapU", void 0);
  31436. __decorate([
  31437. BABYLON.serialize()
  31438. ], BaseTexture.prototype, "wrapV", void 0);
  31439. __decorate([
  31440. BABYLON.serialize()
  31441. ], BaseTexture.prototype, "wrapR", void 0);
  31442. __decorate([
  31443. BABYLON.serialize()
  31444. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  31445. __decorate([
  31446. BABYLON.serialize()
  31447. ], BaseTexture.prototype, "isCube", void 0);
  31448. __decorate([
  31449. BABYLON.serialize()
  31450. ], BaseTexture.prototype, "is3D", void 0);
  31451. __decorate([
  31452. BABYLON.serialize()
  31453. ], BaseTexture.prototype, "gammaSpace", void 0);
  31454. __decorate([
  31455. BABYLON.serialize()
  31456. ], BaseTexture.prototype, "invertZ", void 0);
  31457. __decorate([
  31458. BABYLON.serialize()
  31459. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  31460. __decorate([
  31461. BABYLON.serialize()
  31462. ], BaseTexture.prototype, "lodGenerationOffset", null);
  31463. __decorate([
  31464. BABYLON.serialize()
  31465. ], BaseTexture.prototype, "lodGenerationScale", null);
  31466. __decorate([
  31467. BABYLON.serialize()
  31468. ], BaseTexture.prototype, "isRenderTarget", void 0);
  31469. return BaseTexture;
  31470. }());
  31471. BABYLON.BaseTexture = BaseTexture;
  31472. })(BABYLON || (BABYLON = {}));
  31473. //# sourceMappingURL=babylon.baseTexture.js.map
  31474. var BABYLON;
  31475. (function (BABYLON) {
  31476. /**
  31477. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  31478. * @see http://doc.babylonjs.com/babylon101/materials#texture
  31479. */
  31480. var Texture = /** @class */ (function (_super) {
  31481. __extends(Texture, _super);
  31482. /**
  31483. * Instantiates a new texture.
  31484. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  31485. * @see http://doc.babylonjs.com/babylon101/materials#texture
  31486. * @param url define the url of the picture to load as a texture
  31487. * @param scene define the scene the texture will belong to
  31488. * @param noMipmap define if the texture will require mip maps or not
  31489. * @param invertY define if the texture needs to be inverted on the y axis during loading
  31490. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  31491. * @param onLoad define a callback triggered when the texture has been loaded
  31492. * @param onError define a callback triggered when an error occurred during the loading session
  31493. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  31494. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  31495. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  31496. */
  31497. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  31498. if (noMipmap === void 0) { noMipmap = false; }
  31499. if (invertY === void 0) { invertY = true; }
  31500. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31501. if (onLoad === void 0) { onLoad = null; }
  31502. if (onError === void 0) { onError = null; }
  31503. if (buffer === void 0) { buffer = null; }
  31504. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31505. var _this = _super.call(this, scene) || this;
  31506. /**
  31507. * Define an offset on the texture to offset the u coordinates of the UVs
  31508. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  31509. */
  31510. _this.uOffset = 0;
  31511. /**
  31512. * Define an offset on the texture to offset the v coordinates of the UVs
  31513. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  31514. */
  31515. _this.vOffset = 0;
  31516. /**
  31517. * Define an offset on the texture to scale the u coordinates of the UVs
  31518. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  31519. */
  31520. _this.uScale = 1.0;
  31521. /**
  31522. * Define an offset on the texture to scale the v coordinates of the UVs
  31523. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  31524. */
  31525. _this.vScale = 1.0;
  31526. /**
  31527. * Define an offset on the texture to rotate around the u coordinates of the UVs
  31528. * @see http://doc.babylonjs.com/how_to/more_materials
  31529. */
  31530. _this.uAng = 0;
  31531. /**
  31532. * Define an offset on the texture to rotate around the v coordinates of the UVs
  31533. * @see http://doc.babylonjs.com/how_to/more_materials
  31534. */
  31535. _this.vAng = 0;
  31536. /**
  31537. * Define an offset on the texture to rotate around the w coordinates of the UVs (in case of 3d texture)
  31538. * @see http://doc.babylonjs.com/how_to/more_materials
  31539. */
  31540. _this.wAng = 0;
  31541. /**
  31542. * Defines the center of rotation (U)
  31543. */
  31544. _this.uRotationCenter = 0.5;
  31545. /**
  31546. * Defines the center of rotation (V)
  31547. */
  31548. _this.vRotationCenter = 0.5;
  31549. /**
  31550. * Defines the center of rotation (W)
  31551. */
  31552. _this.wRotationCenter = 0.5;
  31553. /**
  31554. * Observable triggered once the texture has been loaded.
  31555. */
  31556. _this.onLoadObservable = new BABYLON.Observable();
  31557. _this._isBlocking = true;
  31558. _this.name = url || "";
  31559. _this.url = url;
  31560. _this._noMipmap = noMipmap;
  31561. _this._invertY = invertY;
  31562. _this._samplingMode = samplingMode;
  31563. _this._buffer = buffer;
  31564. _this._deleteBuffer = deleteBuffer;
  31565. if (format) {
  31566. _this._format = format;
  31567. }
  31568. scene = _this.getScene();
  31569. if (!scene) {
  31570. return _this;
  31571. }
  31572. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  31573. var load = function () {
  31574. if (_this.onLoadObservable.hasObservers()) {
  31575. _this.onLoadObservable.notifyObservers(_this);
  31576. }
  31577. if (onLoad) {
  31578. onLoad();
  31579. }
  31580. if (!_this.isBlocking && scene) {
  31581. scene.resetCachedMaterial();
  31582. }
  31583. };
  31584. if (!_this.url) {
  31585. _this._delayedOnLoad = load;
  31586. _this._delayedOnError = onError;
  31587. return _this;
  31588. }
  31589. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  31590. if (!_this._texture) {
  31591. if (!scene.useDelayedTextureLoading) {
  31592. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  31593. if (deleteBuffer) {
  31594. delete _this._buffer;
  31595. }
  31596. }
  31597. else {
  31598. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31599. _this._delayedOnLoad = load;
  31600. _this._delayedOnError = onError;
  31601. }
  31602. }
  31603. else {
  31604. if (_this._texture.isReady) {
  31605. BABYLON.Tools.SetImmediate(function () { return load(); });
  31606. }
  31607. else {
  31608. _this._texture.onLoadedObservable.add(load);
  31609. }
  31610. }
  31611. return _this;
  31612. }
  31613. Object.defineProperty(Texture.prototype, "noMipmap", {
  31614. /**
  31615. * Are mip maps generated for this texture or not.
  31616. */
  31617. get: function () {
  31618. return this._noMipmap;
  31619. },
  31620. enumerable: true,
  31621. configurable: true
  31622. });
  31623. Object.defineProperty(Texture.prototype, "isBlocking", {
  31624. get: function () {
  31625. return this._isBlocking;
  31626. },
  31627. /**
  31628. * Is the texture preventing material to render while loading.
  31629. * If false, a default texture will be used instead of the loading one during the preparation step.
  31630. */
  31631. set: function (value) {
  31632. this._isBlocking = value;
  31633. },
  31634. enumerable: true,
  31635. configurable: true
  31636. });
  31637. Object.defineProperty(Texture.prototype, "samplingMode", {
  31638. /**
  31639. * Get the current sampling mode associated with the texture.
  31640. */
  31641. get: function () {
  31642. return this._samplingMode;
  31643. },
  31644. enumerable: true,
  31645. configurable: true
  31646. });
  31647. /**
  31648. * Update the url (and optional buffer) of this texture if url was null during construction.
  31649. * @param url the url of the texture
  31650. * @param buffer the buffer of the texture (defaults to null)
  31651. */
  31652. Texture.prototype.updateURL = function (url, buffer) {
  31653. if (buffer === void 0) { buffer = null; }
  31654. if (this.url) {
  31655. throw new Error("URL is already set");
  31656. }
  31657. this.url = url;
  31658. this._buffer = buffer;
  31659. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31660. this.delayLoad();
  31661. };
  31662. /**
  31663. * Finish the loading sequence of a texture flagged as delayed load.
  31664. * @hidden
  31665. */
  31666. Texture.prototype.delayLoad = function () {
  31667. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31668. return;
  31669. }
  31670. var scene = this.getScene();
  31671. if (!scene) {
  31672. return;
  31673. }
  31674. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31675. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31676. if (!this._texture) {
  31677. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31678. if (this._deleteBuffer) {
  31679. delete this._buffer;
  31680. }
  31681. }
  31682. else {
  31683. if (this._delayedOnLoad) {
  31684. if (this._texture.isReady) {
  31685. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31686. }
  31687. else {
  31688. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31689. }
  31690. }
  31691. }
  31692. this._delayedOnLoad = null;
  31693. this._delayedOnError = null;
  31694. };
  31695. /**
  31696. * Update the sampling mode of the texture.
  31697. * Default is Trilinear mode.
  31698. *
  31699. * | Value | Type | Description |
  31700. * | ----- | ------------------ | ----------- |
  31701. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  31702. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  31703. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  31704. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  31705. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  31706. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  31707. * | 7 | NEAREST_LINEAR | |
  31708. * | 8 | NEAREST_NEAREST | |
  31709. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  31710. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  31711. * | 11 | LINEAR_LINEAR | |
  31712. * | 12 | LINEAR_NEAREST | |
  31713. *
  31714. * > _mag_: magnification filter (close to the viewer)
  31715. * > _min_: minification filter (far from the viewer)
  31716. * > _mip_: filter used between mip map levels
  31717. *@param samplingMode Define the new sampling mode of the texture
  31718. */
  31719. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31720. if (!this._texture) {
  31721. return;
  31722. }
  31723. var scene = this.getScene();
  31724. if (!scene) {
  31725. return;
  31726. }
  31727. this._samplingMode = samplingMode;
  31728. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31729. };
  31730. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31731. x *= this.uScale;
  31732. y *= this.vScale;
  31733. x -= this.uRotationCenter * this.uScale;
  31734. y -= this.vRotationCenter * this.vScale;
  31735. z -= this.wRotationCenter;
  31736. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31737. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31738. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31739. t.z += this.wRotationCenter;
  31740. };
  31741. /**
  31742. * Get the current texture matrix which includes the requested offsetting, tiling and rotation components.
  31743. * @returns the transform matrix of the texture.
  31744. */
  31745. Texture.prototype.getTextureMatrix = function () {
  31746. var _this = this;
  31747. if (this.uOffset === this._cachedUOffset &&
  31748. this.vOffset === this._cachedVOffset &&
  31749. this.uScale === this._cachedUScale &&
  31750. this.vScale === this._cachedVScale &&
  31751. this.uAng === this._cachedUAng &&
  31752. this.vAng === this._cachedVAng &&
  31753. this.wAng === this._cachedWAng) {
  31754. return this._cachedTextureMatrix;
  31755. }
  31756. this._cachedUOffset = this.uOffset;
  31757. this._cachedVOffset = this.vOffset;
  31758. this._cachedUScale = this.uScale;
  31759. this._cachedVScale = this.vScale;
  31760. this._cachedUAng = this.uAng;
  31761. this._cachedVAng = this.vAng;
  31762. this._cachedWAng = this.wAng;
  31763. if (!this._cachedTextureMatrix) {
  31764. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31765. this._rowGenerationMatrix = new BABYLON.Matrix();
  31766. this._t0 = BABYLON.Vector3.Zero();
  31767. this._t1 = BABYLON.Vector3.Zero();
  31768. this._t2 = BABYLON.Vector3.Zero();
  31769. }
  31770. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31771. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31772. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31773. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31774. this._t1.subtractInPlace(this._t0);
  31775. this._t2.subtractInPlace(this._t0);
  31776. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31777. this._cachedTextureMatrix.m[0] = this._t1.x;
  31778. this._cachedTextureMatrix.m[1] = this._t1.y;
  31779. this._cachedTextureMatrix.m[2] = this._t1.z;
  31780. this._cachedTextureMatrix.m[4] = this._t2.x;
  31781. this._cachedTextureMatrix.m[5] = this._t2.y;
  31782. this._cachedTextureMatrix.m[6] = this._t2.z;
  31783. this._cachedTextureMatrix.m[8] = this._t0.x;
  31784. this._cachedTextureMatrix.m[9] = this._t0.y;
  31785. this._cachedTextureMatrix.m[10] = this._t0.z;
  31786. var scene = this.getScene();
  31787. if (!scene) {
  31788. return this._cachedTextureMatrix;
  31789. }
  31790. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31791. return mat.hasTexture(_this);
  31792. });
  31793. return this._cachedTextureMatrix;
  31794. };
  31795. /**
  31796. * Get the current matrix used to apply reflection. This is useful to rotate an environment texture for instance.
  31797. * @returns The reflection texture transform
  31798. */
  31799. Texture.prototype.getReflectionTextureMatrix = function () {
  31800. var _this = this;
  31801. var scene = this.getScene();
  31802. if (!scene) {
  31803. return this._cachedTextureMatrix;
  31804. }
  31805. if (this.uOffset === this._cachedUOffset &&
  31806. this.vOffset === this._cachedVOffset &&
  31807. this.uScale === this._cachedUScale &&
  31808. this.vScale === this._cachedVScale &&
  31809. this.coordinatesMode === this._cachedCoordinatesMode) {
  31810. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31811. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31812. return this._cachedTextureMatrix;
  31813. }
  31814. }
  31815. else {
  31816. return this._cachedTextureMatrix;
  31817. }
  31818. }
  31819. if (!this._cachedTextureMatrix) {
  31820. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31821. }
  31822. if (!this._projectionModeMatrix) {
  31823. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31824. }
  31825. this._cachedUOffset = this.uOffset;
  31826. this._cachedVOffset = this.vOffset;
  31827. this._cachedUScale = this.uScale;
  31828. this._cachedVScale = this.vScale;
  31829. this._cachedCoordinatesMode = this.coordinatesMode;
  31830. switch (this.coordinatesMode) {
  31831. case Texture.PLANAR_MODE:
  31832. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31833. this._cachedTextureMatrix[0] = this.uScale;
  31834. this._cachedTextureMatrix[5] = this.vScale;
  31835. this._cachedTextureMatrix[12] = this.uOffset;
  31836. this._cachedTextureMatrix[13] = this.vOffset;
  31837. break;
  31838. case Texture.PROJECTION_MODE:
  31839. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31840. this._projectionModeMatrix.m[0] = 0.5;
  31841. this._projectionModeMatrix.m[5] = -0.5;
  31842. this._projectionModeMatrix.m[10] = 0.0;
  31843. this._projectionModeMatrix.m[12] = 0.5;
  31844. this._projectionModeMatrix.m[13] = 0.5;
  31845. this._projectionModeMatrix.m[14] = 1.0;
  31846. this._projectionModeMatrix.m[15] = 1.0;
  31847. var projectionMatrix = scene.getProjectionMatrix();
  31848. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31849. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31850. break;
  31851. default:
  31852. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31853. break;
  31854. }
  31855. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31856. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31857. });
  31858. return this._cachedTextureMatrix;
  31859. };
  31860. /**
  31861. * Clones the texture.
  31862. * @returns the cloned texture
  31863. */
  31864. Texture.prototype.clone = function () {
  31865. var _this = this;
  31866. return BABYLON.SerializationHelper.Clone(function () {
  31867. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31868. }, this);
  31869. };
  31870. /**
  31871. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  31872. * @returns The JSON representation of the texture
  31873. */
  31874. Texture.prototype.serialize = function () {
  31875. var serializationObject = _super.prototype.serialize.call(this);
  31876. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31877. serializationObject.base64String = this._buffer;
  31878. serializationObject.name = serializationObject.name.replace("data:", "");
  31879. }
  31880. serializationObject.invertY = this._invertY;
  31881. serializationObject.samplingMode = this.samplingMode;
  31882. return serializationObject;
  31883. };
  31884. /**
  31885. * Get the current class name of the texture usefull for serialization or dynamic coding.
  31886. * @returns "Texture"
  31887. */
  31888. Texture.prototype.getClassName = function () {
  31889. return "Texture";
  31890. };
  31891. /**
  31892. * Dispose the texture and release its associated resources.
  31893. */
  31894. Texture.prototype.dispose = function () {
  31895. _super.prototype.dispose.call(this);
  31896. this.onLoadObservable.clear();
  31897. this._delayedOnLoad = null;
  31898. this._delayedOnError = null;
  31899. };
  31900. /**
  31901. * Parse the JSON representation of a texture in order to recreate the texture in the given scene.
  31902. * @param parsedTexture Define the JSON representation of the texture
  31903. * @param scene Define the scene the parsed texture should be instantiated in
  31904. * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies
  31905. * @returns The parsed texture if successful
  31906. */
  31907. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31908. if (parsedTexture.customType) {
  31909. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31910. // Update Sampling Mode
  31911. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31912. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31913. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31914. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31915. }
  31916. }
  31917. return parsedCustomTexture;
  31918. }
  31919. if (parsedTexture.isCube) {
  31920. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31921. }
  31922. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31923. return null;
  31924. }
  31925. var texture = BABYLON.SerializationHelper.Parse(function () {
  31926. var generateMipMaps = true;
  31927. if (parsedTexture.noMipmap) {
  31928. generateMipMaps = false;
  31929. }
  31930. if (parsedTexture.mirrorPlane) {
  31931. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31932. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31933. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31934. return mirrorTexture;
  31935. }
  31936. else if (parsedTexture.isRenderTarget) {
  31937. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31938. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31939. return renderTargetTexture;
  31940. }
  31941. else {
  31942. var texture;
  31943. if (parsedTexture.base64String) {
  31944. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31945. }
  31946. else {
  31947. var url = rootUrl + parsedTexture.name;
  31948. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31949. url = parsedTexture.url;
  31950. }
  31951. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31952. }
  31953. return texture;
  31954. }
  31955. }, parsedTexture, scene);
  31956. // Update Sampling Mode
  31957. if (parsedTexture.samplingMode) {
  31958. var sampling = parsedTexture.samplingMode;
  31959. if (texture._samplingMode !== sampling) {
  31960. texture.updateSamplingMode(sampling);
  31961. }
  31962. }
  31963. // Animations
  31964. if (parsedTexture.animations) {
  31965. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31966. var parsedAnimation = parsedTexture.animations[animationIndex];
  31967. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31968. }
  31969. }
  31970. return texture;
  31971. };
  31972. /**
  31973. * Creates a texture from its base 64 representation.
  31974. * @param data Define the base64 payload without the data: prefix
  31975. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  31976. * @param scene Define the scene the texture should belong to
  31977. * @param noMipmap Forces the texture to not create mip map information if true
  31978. * @param invertY define if the texture needs to be inverted on the y axis during loading
  31979. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  31980. * @param onLoad define a callback triggered when the texture has been loaded
  31981. * @param onError define a callback triggered when an error occurred during the loading session
  31982. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  31983. * @returns the created texture
  31984. */
  31985. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31986. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31987. if (onLoad === void 0) { onLoad = null; }
  31988. if (onError === void 0) { onError = null; }
  31989. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31990. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31991. };
  31992. /**
  31993. * Creates a texture from its data: representation. (data: will be added in case only the payload has been passed in)
  31994. * @param data Define the base64 payload without the data: prefix
  31995. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  31996. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  31997. * @param scene Define the scene the texture should belong to
  31998. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  31999. * @param noMipmap Forces the texture to not create mip map information if true
  32000. * @param invertY define if the texture needs to be inverted on the y axis during loading
  32001. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  32002. * @param onLoad define a callback triggered when the texture has been loaded
  32003. * @param onError define a callback triggered when an error occurred during the loading session
  32004. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  32005. * @returns the created texture
  32006. */
  32007. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  32008. if (deleteBuffer === void 0) { deleteBuffer = false; }
  32009. if (noMipmap === void 0) { noMipmap = false; }
  32010. if (invertY === void 0) { invertY = true; }
  32011. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  32012. if (onLoad === void 0) { onLoad = null; }
  32013. if (onError === void 0) { onError = null; }
  32014. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32015. if (name.substr(0, 5) !== "data:") {
  32016. name = "data:" + name;
  32017. }
  32018. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  32019. };
  32020. /** nearest is mag = nearest and min = nearest and mip = linear */
  32021. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  32022. /** nearest is mag = nearest and min = nearest and mip = linear */
  32023. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  32024. /** Bilinear is mag = linear and min = linear and mip = nearest */
  32025. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  32026. /** Bilinear is mag = linear and min = linear and mip = nearest */
  32027. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  32028. /** Trilinear is mag = linear and min = linear and mip = linear */
  32029. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  32030. /** Trilinear is mag = linear and min = linear and mip = linear */
  32031. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  32032. /** mag = nearest and min = nearest and mip = nearest */
  32033. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  32034. /** mag = nearest and min = linear and mip = nearest */
  32035. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  32036. /** mag = nearest and min = linear and mip = linear */
  32037. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  32038. /** mag = nearest and min = linear and mip = none */
  32039. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  32040. /** mag = nearest and min = nearest and mip = none */
  32041. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  32042. /** mag = linear and min = nearest and mip = nearest */
  32043. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  32044. /** mag = linear and min = nearest and mip = linear */
  32045. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  32046. /** mag = linear and min = linear and mip = none */
  32047. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  32048. /** mag = linear and min = nearest and mip = none */
  32049. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  32050. /** Explicit coordinates mode */
  32051. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  32052. /** Spherical coordinates mode */
  32053. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  32054. /** Planar coordinates mode */
  32055. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  32056. /** Cubic coordinates mode */
  32057. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  32058. /** Projection coordinates mode */
  32059. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  32060. /** Inverse Cubic coordinates mode */
  32061. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  32062. /** Inverse Cubic coordinates mode */
  32063. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  32064. /** Equirectangular coordinates mode */
  32065. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  32066. /** Equirectangular Fixed coordinates mode */
  32067. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  32068. /** Equirectangular Fixed Mirrored coordinates mode */
  32069. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  32070. /** Texture is not repeating outside of 0..1 UVs */
  32071. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  32072. /** Texture is repeating outside of 0..1 UVs */
  32073. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  32074. /** Texture is repeating and mirrored */
  32075. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  32076. /**
  32077. * 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
  32078. */
  32079. Texture.UseSerializedUrlIfAny = false;
  32080. __decorate([
  32081. BABYLON.serialize()
  32082. ], Texture.prototype, "url", void 0);
  32083. __decorate([
  32084. BABYLON.serialize()
  32085. ], Texture.prototype, "uOffset", void 0);
  32086. __decorate([
  32087. BABYLON.serialize()
  32088. ], Texture.prototype, "vOffset", void 0);
  32089. __decorate([
  32090. BABYLON.serialize()
  32091. ], Texture.prototype, "uScale", void 0);
  32092. __decorate([
  32093. BABYLON.serialize()
  32094. ], Texture.prototype, "vScale", void 0);
  32095. __decorate([
  32096. BABYLON.serialize()
  32097. ], Texture.prototype, "uAng", void 0);
  32098. __decorate([
  32099. BABYLON.serialize()
  32100. ], Texture.prototype, "vAng", void 0);
  32101. __decorate([
  32102. BABYLON.serialize()
  32103. ], Texture.prototype, "wAng", void 0);
  32104. __decorate([
  32105. BABYLON.serialize()
  32106. ], Texture.prototype, "uRotationCenter", void 0);
  32107. __decorate([
  32108. BABYLON.serialize()
  32109. ], Texture.prototype, "vRotationCenter", void 0);
  32110. __decorate([
  32111. BABYLON.serialize()
  32112. ], Texture.prototype, "wRotationCenter", void 0);
  32113. __decorate([
  32114. BABYLON.serialize()
  32115. ], Texture.prototype, "isBlocking", null);
  32116. return Texture;
  32117. }(BABYLON.BaseTexture));
  32118. BABYLON.Texture = Texture;
  32119. })(BABYLON || (BABYLON = {}));
  32120. //# sourceMappingURL=babylon.texture.js.map
  32121. var BABYLON;
  32122. (function (BABYLON) {
  32123. /**
  32124. * @hidden
  32125. **/
  32126. var _CreationDataStorage = /** @class */ (function () {
  32127. function _CreationDataStorage() {
  32128. }
  32129. return _CreationDataStorage;
  32130. }());
  32131. BABYLON._CreationDataStorage = _CreationDataStorage;
  32132. /**
  32133. * @hidden
  32134. **/
  32135. var _InstanceDataStorage = /** @class */ (function () {
  32136. function _InstanceDataStorage() {
  32137. this.visibleInstances = {};
  32138. this.renderIdForInstances = new Array();
  32139. this.batchCache = new _InstancesBatch();
  32140. this.instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  32141. }
  32142. return _InstanceDataStorage;
  32143. }());
  32144. /**
  32145. * @hidden
  32146. **/
  32147. var _InstancesBatch = /** @class */ (function () {
  32148. function _InstancesBatch() {
  32149. this.mustReturn = false;
  32150. this.visibleInstances = new Array();
  32151. this.renderSelf = new Array();
  32152. }
  32153. return _InstancesBatch;
  32154. }());
  32155. BABYLON._InstancesBatch = _InstancesBatch;
  32156. /**
  32157. * Class used to represent renderable models
  32158. */
  32159. var Mesh = /** @class */ (function (_super) {
  32160. __extends(Mesh, _super);
  32161. /**
  32162. * @constructor
  32163. * @param name The value used by scene.getMeshByName() to do a lookup.
  32164. * @param scene The scene to add this mesh to.
  32165. * @param parent The parent of this mesh, if it has one
  32166. * @param source An optional Mesh from which geometry is shared, cloned.
  32167. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  32168. * When false, achieved by calling a clone(), also passing False.
  32169. * This will make creation of children, recursive.
  32170. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  32171. */
  32172. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  32173. if (scene === void 0) { scene = null; }
  32174. if (parent === void 0) { parent = null; }
  32175. if (source === void 0) { source = null; }
  32176. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32177. var _this = _super.call(this, name, scene) || this;
  32178. // Members
  32179. /**
  32180. * Gets the delay loading state of the mesh (when delay loading is turned on)
  32181. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  32182. */
  32183. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32184. /**
  32185. * Gets the list of instances created from this mesh
  32186. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32187. */
  32188. _this.instances = new Array();
  32189. _this._LODLevels = new Array();
  32190. /** @hidden */
  32191. _this._instanceDataStorage = new _InstanceDataStorage();
  32192. // Use by builder only to know what orientation were the mesh build in.
  32193. /** @hidden */
  32194. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  32195. /**
  32196. * Use this property to change the original side orientation defined at construction time
  32197. */
  32198. _this.overrideMaterialSideOrientation = null;
  32199. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  32200. // Will be used to save a source mesh reference, If any
  32201. _this._source = null;
  32202. scene = _this.getScene();
  32203. if (source) {
  32204. // Geometry
  32205. if (source._geometry) {
  32206. source._geometry.applyToMesh(_this);
  32207. }
  32208. // Deep copy
  32209. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  32210. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  32211. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  32212. ], ["_poseMatrix"]);
  32213. // Source mesh
  32214. _this._source = source;
  32215. // Construction Params
  32216. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  32217. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  32218. _this._creationDataStorage = source._creationDataStorage;
  32219. // Animation ranges
  32220. if (_this._source._ranges) {
  32221. var ranges = _this._source._ranges;
  32222. for (var name in ranges) {
  32223. if (!ranges.hasOwnProperty(name)) {
  32224. continue;
  32225. }
  32226. if (!ranges[name]) {
  32227. continue;
  32228. }
  32229. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  32230. }
  32231. }
  32232. // Metadata
  32233. if (source.metadata && source.metadata.clone) {
  32234. _this.metadata = source.metadata.clone();
  32235. }
  32236. else {
  32237. _this.metadata = source.metadata;
  32238. }
  32239. // Tags
  32240. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  32241. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  32242. }
  32243. // Parent
  32244. _this.parent = source.parent;
  32245. // Pivot
  32246. _this.setPivotMatrix(source.getPivotMatrix());
  32247. _this.id = name + "." + source.id;
  32248. // Material
  32249. _this.material = source.material;
  32250. var index;
  32251. if (!doNotCloneChildren) {
  32252. // Children
  32253. var directDescendants = source.getDescendants(true);
  32254. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  32255. var child = directDescendants[index_1];
  32256. if (child.clone) {
  32257. child.clone(name + "." + child.name, _this);
  32258. }
  32259. }
  32260. }
  32261. // Physics clone
  32262. var physicsEngine = _this.getScene().getPhysicsEngine();
  32263. if (clonePhysicsImpostor && physicsEngine) {
  32264. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  32265. if (impostor) {
  32266. _this.physicsImpostor = impostor.clone(_this);
  32267. }
  32268. }
  32269. // Particles
  32270. for (index = 0; index < scene.particleSystems.length; index++) {
  32271. var system = scene.particleSystems[index];
  32272. if (system.emitter === source) {
  32273. system.clone(system.name, _this);
  32274. }
  32275. }
  32276. _this.refreshBoundingInfo();
  32277. _this.computeWorldMatrix(true);
  32278. }
  32279. // Parent
  32280. if (parent !== null) {
  32281. _this.parent = parent;
  32282. }
  32283. return _this;
  32284. }
  32285. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  32286. /**
  32287. * An event triggered before rendering the mesh
  32288. */
  32289. get: function () {
  32290. if (!this._onBeforeRenderObservable) {
  32291. this._onBeforeRenderObservable = new BABYLON.Observable();
  32292. }
  32293. return this._onBeforeRenderObservable;
  32294. },
  32295. enumerable: true,
  32296. configurable: true
  32297. });
  32298. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  32299. /**
  32300. * An event triggered after rendering the mesh
  32301. */
  32302. get: function () {
  32303. if (!this._onAfterRenderObservable) {
  32304. this._onAfterRenderObservable = new BABYLON.Observable();
  32305. }
  32306. return this._onAfterRenderObservable;
  32307. },
  32308. enumerable: true,
  32309. configurable: true
  32310. });
  32311. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  32312. /**
  32313. * An event triggered before drawing the mesh
  32314. */
  32315. get: function () {
  32316. if (!this._onBeforeDrawObservable) {
  32317. this._onBeforeDrawObservable = new BABYLON.Observable();
  32318. }
  32319. return this._onBeforeDrawObservable;
  32320. },
  32321. enumerable: true,
  32322. configurable: true
  32323. });
  32324. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  32325. /**
  32326. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  32327. */
  32328. set: function (callback) {
  32329. if (this._onBeforeDrawObserver) {
  32330. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  32331. }
  32332. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  32333. },
  32334. enumerable: true,
  32335. configurable: true
  32336. });
  32337. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  32338. /**
  32339. * Gets or sets the morph target manager
  32340. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  32341. */
  32342. get: function () {
  32343. return this._morphTargetManager;
  32344. },
  32345. set: function (value) {
  32346. if (this._morphTargetManager === value) {
  32347. return;
  32348. }
  32349. this._morphTargetManager = value;
  32350. this._syncGeometryWithMorphTargetManager();
  32351. },
  32352. enumerable: true,
  32353. configurable: true
  32354. });
  32355. Object.defineProperty(Mesh.prototype, "source", {
  32356. /**
  32357. * Gets the source mesh (the one used to clone this one from)
  32358. */
  32359. get: function () {
  32360. return this._source;
  32361. },
  32362. enumerable: true,
  32363. configurable: true
  32364. });
  32365. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  32366. /**
  32367. * Gets or sets a boolean indicating that this mesh does not use index buffer
  32368. */
  32369. get: function () {
  32370. return this._unIndexed;
  32371. },
  32372. set: function (value) {
  32373. if (this._unIndexed !== value) {
  32374. this._unIndexed = value;
  32375. this._markSubMeshesAsAttributesDirty();
  32376. }
  32377. },
  32378. enumerable: true,
  32379. configurable: true
  32380. });
  32381. // Methods
  32382. /**
  32383. * Gets the class name
  32384. * @returns the string "Mesh".
  32385. */
  32386. Mesh.prototype.getClassName = function () {
  32387. return "Mesh";
  32388. };
  32389. /**
  32390. * Returns a description of this mesh
  32391. * @param fullDetails define if full details about this mesh must be used
  32392. * @returns a descriptive string representing this mesh
  32393. */
  32394. Mesh.prototype.toString = function (fullDetails) {
  32395. var ret = _super.prototype.toString.call(this, fullDetails);
  32396. ret += ", n vertices: " + this.getTotalVertices();
  32397. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  32398. if (this.animations) {
  32399. for (var i = 0; i < this.animations.length; i++) {
  32400. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  32401. }
  32402. }
  32403. if (fullDetails) {
  32404. if (this._geometry) {
  32405. var ib = this.getIndices();
  32406. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32407. if (vb && ib) {
  32408. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  32409. }
  32410. }
  32411. else {
  32412. ret += ", flat shading: UNKNOWN";
  32413. }
  32414. }
  32415. return ret;
  32416. };
  32417. /** @hidden */
  32418. Mesh.prototype._unBindEffect = function () {
  32419. _super.prototype._unBindEffect.call(this);
  32420. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  32421. var instance = _a[_i];
  32422. instance._unBindEffect();
  32423. }
  32424. };
  32425. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  32426. /**
  32427. * Gets a boolean indicating if this mesh has LOD
  32428. */
  32429. get: function () {
  32430. return this._LODLevels.length > 0;
  32431. },
  32432. enumerable: true,
  32433. configurable: true
  32434. });
  32435. /**
  32436. * Gets the list of MeshLODLevel associated with the current mesh
  32437. * @returns an array of MeshLODLevel
  32438. */
  32439. Mesh.prototype.getLODLevels = function () {
  32440. return this._LODLevels;
  32441. };
  32442. Mesh.prototype._sortLODLevels = function () {
  32443. this._LODLevels.sort(function (a, b) {
  32444. if (a.distance < b.distance) {
  32445. return 1;
  32446. }
  32447. if (a.distance > b.distance) {
  32448. return -1;
  32449. }
  32450. return 0;
  32451. });
  32452. };
  32453. /**
  32454. * Add a mesh as LOD level triggered at the given distance.
  32455. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32456. * @param distance The distance from the center of the object to show this level
  32457. * @param mesh The mesh to be added as LOD level (can be null)
  32458. * @return This mesh (for chaining)
  32459. */
  32460. Mesh.prototype.addLODLevel = function (distance, mesh) {
  32461. if (mesh && mesh._masterMesh) {
  32462. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  32463. return this;
  32464. }
  32465. var level = new BABYLON.MeshLODLevel(distance, mesh);
  32466. this._LODLevels.push(level);
  32467. if (mesh) {
  32468. mesh._masterMesh = this;
  32469. }
  32470. this._sortLODLevels();
  32471. return this;
  32472. };
  32473. /**
  32474. * Returns the LOD level mesh at the passed distance or null if not found.
  32475. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32476. * @param distance The distance from the center of the object to show this level
  32477. * @returns a Mesh or `null`
  32478. */
  32479. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  32480. for (var index = 0; index < this._LODLevels.length; index++) {
  32481. var level = this._LODLevels[index];
  32482. if (level.distance === distance) {
  32483. return level.mesh;
  32484. }
  32485. }
  32486. return null;
  32487. };
  32488. /**
  32489. * Remove a mesh from the LOD array
  32490. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32491. * @param mesh defines the mesh to be removed
  32492. * @return This mesh (for chaining)
  32493. */
  32494. Mesh.prototype.removeLODLevel = function (mesh) {
  32495. for (var index = 0; index < this._LODLevels.length; index++) {
  32496. if (this._LODLevels[index].mesh === mesh) {
  32497. this._LODLevels.splice(index, 1);
  32498. if (mesh) {
  32499. mesh._masterMesh = null;
  32500. }
  32501. }
  32502. }
  32503. this._sortLODLevels();
  32504. return this;
  32505. };
  32506. /**
  32507. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  32508. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32509. * @param camera defines the camera to use to compute distance
  32510. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  32511. * @return This mesh (for chaining)
  32512. */
  32513. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  32514. if (!this._LODLevels || this._LODLevels.length === 0) {
  32515. return this;
  32516. }
  32517. var bSphere;
  32518. if (boundingSphere) {
  32519. bSphere = boundingSphere;
  32520. }
  32521. else {
  32522. var boundingInfo = this.getBoundingInfo();
  32523. bSphere = boundingInfo.boundingSphere;
  32524. }
  32525. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  32526. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  32527. if (this.onLODLevelSelection) {
  32528. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  32529. }
  32530. return this;
  32531. }
  32532. for (var index = 0; index < this._LODLevels.length; index++) {
  32533. var level = this._LODLevels[index];
  32534. if (level.distance < distanceToCamera) {
  32535. if (level.mesh) {
  32536. level.mesh._preActivate();
  32537. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  32538. }
  32539. if (this.onLODLevelSelection) {
  32540. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  32541. }
  32542. return level.mesh;
  32543. }
  32544. }
  32545. if (this.onLODLevelSelection) {
  32546. this.onLODLevelSelection(distanceToCamera, this, this);
  32547. }
  32548. return this;
  32549. };
  32550. Object.defineProperty(Mesh.prototype, "geometry", {
  32551. /**
  32552. * Gets the mesh internal Geometry object
  32553. */
  32554. get: function () {
  32555. return this._geometry;
  32556. },
  32557. enumerable: true,
  32558. configurable: true
  32559. });
  32560. /**
  32561. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  32562. * @returns the total number of vertices
  32563. */
  32564. Mesh.prototype.getTotalVertices = function () {
  32565. if (this._geometry === null || this._geometry === undefined) {
  32566. return 0;
  32567. }
  32568. return this._geometry.getTotalVertices();
  32569. };
  32570. /**
  32571. * Returns the content of an associated vertex buffer
  32572. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32573. * - BABYLON.VertexBuffer.PositionKind
  32574. * - BABYLON.VertexBuffer.UVKind
  32575. * - BABYLON.VertexBuffer.UV2Kind
  32576. * - BABYLON.VertexBuffer.UV3Kind
  32577. * - BABYLON.VertexBuffer.UV4Kind
  32578. * - BABYLON.VertexBuffer.UV5Kind
  32579. * - BABYLON.VertexBuffer.UV6Kind
  32580. * - BABYLON.VertexBuffer.ColorKind
  32581. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32582. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32583. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32584. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32585. * @param copyWhenShared defines a boolean indicating that if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one
  32586. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  32587. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  32588. */
  32589. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32590. if (!this._geometry) {
  32591. return null;
  32592. }
  32593. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  32594. };
  32595. /**
  32596. * Returns the mesh VertexBuffer object from the requested `kind`
  32597. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32598. * - BABYLON.VertexBuffer.PositionKind
  32599. * - BABYLON.VertexBuffer.UVKind
  32600. * - BABYLON.VertexBuffer.UV2Kind
  32601. * - BABYLON.VertexBuffer.UV3Kind
  32602. * - BABYLON.VertexBuffer.UV4Kind
  32603. * - BABYLON.VertexBuffer.UV5Kind
  32604. * - BABYLON.VertexBuffer.UV6Kind
  32605. * - BABYLON.VertexBuffer.ColorKind
  32606. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32607. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32608. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32609. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32610. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  32611. */
  32612. Mesh.prototype.getVertexBuffer = function (kind) {
  32613. if (!this._geometry) {
  32614. return null;
  32615. }
  32616. return this._geometry.getVertexBuffer(kind);
  32617. };
  32618. /**
  32619. * Tests if a specific vertex buffer is associated with this mesh
  32620. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32621. * - BABYLON.VertexBuffer.PositionKind
  32622. * - BABYLON.VertexBuffer.UVKind
  32623. * - BABYLON.VertexBuffer.UV2Kind
  32624. * - BABYLON.VertexBuffer.UV3Kind
  32625. * - BABYLON.VertexBuffer.UV4Kind
  32626. * - BABYLON.VertexBuffer.UV5Kind
  32627. * - BABYLON.VertexBuffer.UV6Kind
  32628. * - BABYLON.VertexBuffer.ColorKind
  32629. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32630. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32631. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32632. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32633. * @returns a boolean
  32634. */
  32635. Mesh.prototype.isVerticesDataPresent = function (kind) {
  32636. if (!this._geometry) {
  32637. if (this._delayInfo) {
  32638. return this._delayInfo.indexOf(kind) !== -1;
  32639. }
  32640. return false;
  32641. }
  32642. return this._geometry.isVerticesDataPresent(kind);
  32643. };
  32644. /**
  32645. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  32646. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32647. * - BABYLON.VertexBuffer.PositionKind
  32648. * - BABYLON.VertexBuffer.UVKind
  32649. * - BABYLON.VertexBuffer.UV2Kind
  32650. * - BABYLON.VertexBuffer.UV3Kind
  32651. * - BABYLON.VertexBuffer.UV4Kind
  32652. * - BABYLON.VertexBuffer.UV5Kind
  32653. * - BABYLON.VertexBuffer.UV6Kind
  32654. * - BABYLON.VertexBuffer.ColorKind
  32655. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32656. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32657. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32658. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32659. * @returns a boolean
  32660. */
  32661. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  32662. if (!this._geometry) {
  32663. if (this._delayInfo) {
  32664. return this._delayInfo.indexOf(kind) !== -1;
  32665. }
  32666. return false;
  32667. }
  32668. return this._geometry.isVertexBufferUpdatable(kind);
  32669. };
  32670. /**
  32671. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  32672. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32673. * - BABYLON.VertexBuffer.PositionKind
  32674. * - BABYLON.VertexBuffer.UVKind
  32675. * - BABYLON.VertexBuffer.UV2Kind
  32676. * - BABYLON.VertexBuffer.UV3Kind
  32677. * - BABYLON.VertexBuffer.UV4Kind
  32678. * - BABYLON.VertexBuffer.UV5Kind
  32679. * - BABYLON.VertexBuffer.UV6Kind
  32680. * - BABYLON.VertexBuffer.ColorKind
  32681. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32682. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32683. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32684. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32685. * @returns an array of strings
  32686. */
  32687. Mesh.prototype.getVerticesDataKinds = function () {
  32688. if (!this._geometry) {
  32689. var result = new Array();
  32690. if (this._delayInfo) {
  32691. this._delayInfo.forEach(function (kind, index, array) {
  32692. result.push(kind);
  32693. });
  32694. }
  32695. return result;
  32696. }
  32697. return this._geometry.getVerticesDataKinds();
  32698. };
  32699. /**
  32700. * Returns a positive integer : the total number of indices in this mesh geometry.
  32701. * @returns the numner of indices or zero if the mesh has no geometry.
  32702. */
  32703. Mesh.prototype.getTotalIndices = function () {
  32704. if (!this._geometry) {
  32705. return 0;
  32706. }
  32707. return this._geometry.getTotalIndices();
  32708. };
  32709. /**
  32710. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  32711. * @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.
  32712. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32713. * @returns the indices array or an empty array if the mesh has no geometry
  32714. */
  32715. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  32716. if (!this._geometry) {
  32717. return [];
  32718. }
  32719. return this._geometry.getIndices(copyWhenShared, forceCopy);
  32720. };
  32721. Object.defineProperty(Mesh.prototype, "isBlocked", {
  32722. get: function () {
  32723. return this._masterMesh !== null && this._masterMesh !== undefined;
  32724. },
  32725. enumerable: true,
  32726. configurable: true
  32727. });
  32728. /**
  32729. * Determine if the current mesh is ready to be rendered
  32730. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  32731. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  32732. * @returns true if all associated assets are ready (material, textures, shaders)
  32733. */
  32734. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  32735. if (completeCheck === void 0) { completeCheck = false; }
  32736. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  32737. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32738. return false;
  32739. }
  32740. if (!_super.prototype.isReady.call(this, completeCheck)) {
  32741. return false;
  32742. }
  32743. if (!this.subMeshes || this.subMeshes.length === 0) {
  32744. return true;
  32745. }
  32746. if (!completeCheck) {
  32747. return true;
  32748. }
  32749. var engine = this.getEngine();
  32750. var scene = this.getScene();
  32751. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32752. this.computeWorldMatrix();
  32753. var mat = this.material || scene.defaultMaterial;
  32754. if (mat) {
  32755. if (mat.storeEffectOnSubMeshes) {
  32756. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32757. var subMesh = _a[_i];
  32758. var effectiveMaterial = subMesh.getMaterial();
  32759. if (effectiveMaterial) {
  32760. if (effectiveMaterial.storeEffectOnSubMeshes) {
  32761. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32762. return false;
  32763. }
  32764. }
  32765. else {
  32766. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32767. return false;
  32768. }
  32769. }
  32770. }
  32771. }
  32772. }
  32773. else {
  32774. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32775. return false;
  32776. }
  32777. }
  32778. }
  32779. // Shadows
  32780. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32781. var light = _c[_b];
  32782. var generator = light.getShadowGenerator();
  32783. if (generator) {
  32784. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32785. var subMesh = _e[_d];
  32786. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32787. return false;
  32788. }
  32789. }
  32790. }
  32791. }
  32792. // LOD
  32793. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32794. var lod = _g[_f];
  32795. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32796. return false;
  32797. }
  32798. }
  32799. return true;
  32800. };
  32801. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32802. /**
  32803. * Gets a boolean indicating if the normals aren't to be recomputed on next mesh `positions` array update. This property is pertinent only for updatable parametric shapes.
  32804. */
  32805. get: function () {
  32806. return this._areNormalsFrozen;
  32807. },
  32808. enumerable: true,
  32809. configurable: true
  32810. });
  32811. /**
  32812. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It prevents the mesh normals from being recomputed on next `positions` array update.
  32813. * @returns the current mesh
  32814. */
  32815. Mesh.prototype.freezeNormals = function () {
  32816. this._areNormalsFrozen = true;
  32817. return this;
  32818. };
  32819. /**
  32820. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It reactivates the mesh normals computation if it was previously frozen
  32821. * @returns the current mesh
  32822. */
  32823. Mesh.prototype.unfreezeNormals = function () {
  32824. this._areNormalsFrozen = false;
  32825. return this;
  32826. };
  32827. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32828. /**
  32829. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32830. */
  32831. set: function (count) {
  32832. this._instanceDataStorage.overridenInstanceCount = count;
  32833. },
  32834. enumerable: true,
  32835. configurable: true
  32836. });
  32837. // Methods
  32838. /** @hidden */
  32839. Mesh.prototype._preActivate = function () {
  32840. var sceneRenderId = this.getScene().getRenderId();
  32841. if (this._preActivateId === sceneRenderId) {
  32842. return this;
  32843. }
  32844. this._preActivateId = sceneRenderId;
  32845. this._instanceDataStorage.visibleInstances = null;
  32846. return this;
  32847. };
  32848. /** @hidden */
  32849. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32850. if (this._instanceDataStorage.visibleInstances) {
  32851. this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
  32852. }
  32853. return this;
  32854. };
  32855. /** @hidden */
  32856. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32857. if (!this._instanceDataStorage.visibleInstances) {
  32858. this._instanceDataStorage.visibleInstances = {};
  32859. this._instanceDataStorage.visibleInstances.defaultRenderId = renderId;
  32860. this._instanceDataStorage.visibleInstances.selfDefaultRenderId = this._renderId;
  32861. }
  32862. if (!this._instanceDataStorage.visibleInstances[renderId]) {
  32863. this._instanceDataStorage.visibleInstances[renderId] = new Array();
  32864. }
  32865. this._instanceDataStorage.visibleInstances[renderId].push(instance);
  32866. return this;
  32867. };
  32868. /**
  32869. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32870. * This means the mesh underlying bounding box and sphere are recomputed.
  32871. * @returns the current mesh
  32872. */
  32873. Mesh.prototype.refreshBoundingInfo = function () {
  32874. return this._refreshBoundingInfo(false);
  32875. };
  32876. /** @hidden */
  32877. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32878. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32879. return this;
  32880. }
  32881. var data = this._getPositionData(applySkeleton);
  32882. if (data) {
  32883. var bias = this.geometry ? this.geometry.boundingBias : null;
  32884. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  32885. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32886. }
  32887. if (this.subMeshes) {
  32888. for (var index = 0; index < this.subMeshes.length; index++) {
  32889. this.subMeshes[index].refreshBoundingInfo();
  32890. }
  32891. }
  32892. this._updateBoundingInfo();
  32893. return this;
  32894. };
  32895. Mesh.prototype._getPositionData = function (applySkeleton) {
  32896. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32897. if (data && applySkeleton && this.skeleton) {
  32898. data = BABYLON.Tools.Slice(data);
  32899. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32900. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32901. if (matricesWeightsData && matricesIndicesData) {
  32902. var needExtras = this.numBoneInfluencers > 4;
  32903. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32904. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32905. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32906. var tempVector = BABYLON.Tmp.Vector3[0];
  32907. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32908. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32909. var matWeightIdx = 0;
  32910. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32911. finalMatrix.reset();
  32912. var inf;
  32913. var weight;
  32914. for (inf = 0; inf < 4; inf++) {
  32915. weight = matricesWeightsData[matWeightIdx + inf];
  32916. if (weight > 0) {
  32917. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32918. finalMatrix.addToSelf(tempMatrix);
  32919. }
  32920. }
  32921. if (needExtras) {
  32922. for (inf = 0; inf < 4; inf++) {
  32923. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32924. if (weight > 0) {
  32925. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32926. finalMatrix.addToSelf(tempMatrix);
  32927. }
  32928. }
  32929. }
  32930. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32931. tempVector.toArray(data, index);
  32932. }
  32933. }
  32934. }
  32935. return data;
  32936. };
  32937. /** @hidden */
  32938. Mesh.prototype._createGlobalSubMesh = function (force) {
  32939. var totalVertices = this.getTotalVertices();
  32940. if (!totalVertices || !this.getIndices()) {
  32941. return null;
  32942. }
  32943. // Check if we need to recreate the submeshes
  32944. if (this.subMeshes && this.subMeshes.length > 0) {
  32945. var ib = this.getIndices();
  32946. if (!ib) {
  32947. return null;
  32948. }
  32949. var totalIndices = ib.length;
  32950. var needToRecreate = false;
  32951. if (force) {
  32952. needToRecreate = true;
  32953. }
  32954. else {
  32955. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32956. var submesh = _a[_i];
  32957. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32958. needToRecreate = true;
  32959. break;
  32960. }
  32961. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32962. needToRecreate = true;
  32963. break;
  32964. }
  32965. }
  32966. }
  32967. if (!needToRecreate) {
  32968. return this.subMeshes[0];
  32969. }
  32970. }
  32971. this.releaseSubMeshes();
  32972. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32973. };
  32974. /**
  32975. * This function will subdivide the mesh into multiple submeshes
  32976. * @param count defines the expected number of submeshes
  32977. */
  32978. Mesh.prototype.subdivide = function (count) {
  32979. if (count < 1) {
  32980. return;
  32981. }
  32982. var totalIndices = this.getTotalIndices();
  32983. var subdivisionSize = (totalIndices / count) | 0;
  32984. var offset = 0;
  32985. // Ensure that subdivisionSize is a multiple of 3
  32986. while (subdivisionSize % 3 !== 0) {
  32987. subdivisionSize++;
  32988. }
  32989. this.releaseSubMeshes();
  32990. for (var index = 0; index < count; index++) {
  32991. if (offset >= totalIndices) {
  32992. break;
  32993. }
  32994. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32995. offset += subdivisionSize;
  32996. }
  32997. this.synchronizeInstances();
  32998. };
  32999. /**
  33000. * Copy a FloatArray into a specific associated vertex buffer
  33001. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  33002. * - BABYLON.VertexBuffer.PositionKind
  33003. * - BABYLON.VertexBuffer.UVKind
  33004. * - BABYLON.VertexBuffer.UV2Kind
  33005. * - BABYLON.VertexBuffer.UV3Kind
  33006. * - BABYLON.VertexBuffer.UV4Kind
  33007. * - BABYLON.VertexBuffer.UV5Kind
  33008. * - BABYLON.VertexBuffer.UV6Kind
  33009. * - BABYLON.VertexBuffer.ColorKind
  33010. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33011. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33012. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33013. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33014. * @param data defines the data source
  33015. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  33016. * @param stride defines the data stride size (can be null)
  33017. * @returns the current mesh
  33018. */
  33019. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  33020. if (updatable === void 0) { updatable = false; }
  33021. if (!this._geometry) {
  33022. var vertexData = new BABYLON.VertexData();
  33023. vertexData.set(data, kind);
  33024. var scene = this.getScene();
  33025. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  33026. }
  33027. else {
  33028. this._geometry.setVerticesData(kind, data, updatable, stride);
  33029. }
  33030. return this;
  33031. };
  33032. /**
  33033. * Flags an associated vertex buffer as updatable
  33034. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  33035. * - BABYLON.VertexBuffer.PositionKind
  33036. * - BABYLON.VertexBuffer.UVKind
  33037. * - BABYLON.VertexBuffer.UV2Kind
  33038. * - BABYLON.VertexBuffer.UV3Kind
  33039. * - BABYLON.VertexBuffer.UV4Kind
  33040. * - BABYLON.VertexBuffer.UV5Kind
  33041. * - BABYLON.VertexBuffer.UV6Kind
  33042. * - BABYLON.VertexBuffer.ColorKind
  33043. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33044. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33045. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33046. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33047. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  33048. */
  33049. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  33050. if (updatable === void 0) { updatable = true; }
  33051. var vb = this.getVertexBuffer(kind);
  33052. if (!vb || vb.isUpdatable() === updatable) {
  33053. return;
  33054. }
  33055. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  33056. };
  33057. /**
  33058. * Sets the mesh global Vertex Buffer
  33059. * @param buffer defines the buffer to use
  33060. * @returns the current mesh
  33061. */
  33062. Mesh.prototype.setVerticesBuffer = function (buffer) {
  33063. if (!this._geometry) {
  33064. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  33065. }
  33066. this._geometry.setVerticesBuffer(buffer);
  33067. return this;
  33068. };
  33069. /**
  33070. * Update a specific associated vertex buffer
  33071. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  33072. * - BABYLON.VertexBuffer.PositionKind
  33073. * - BABYLON.VertexBuffer.UVKind
  33074. * - BABYLON.VertexBuffer.UV2Kind
  33075. * - BABYLON.VertexBuffer.UV3Kind
  33076. * - BABYLON.VertexBuffer.UV4Kind
  33077. * - BABYLON.VertexBuffer.UV5Kind
  33078. * - BABYLON.VertexBuffer.UV6Kind
  33079. * - BABYLON.VertexBuffer.ColorKind
  33080. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33081. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33082. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33083. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33084. * @param data defines the data source
  33085. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  33086. * @param makeItUnique defines if the geometry associated with the mesh must be cloned to make the change only for this mesh (and not all meshes associated with the same geometry)
  33087. * @returns the current mesh
  33088. */
  33089. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  33090. if (!this._geometry) {
  33091. return this;
  33092. }
  33093. if (!makeItUnique) {
  33094. this._geometry.updateVerticesData(kind, data, updateExtends);
  33095. }
  33096. else {
  33097. this.makeGeometryUnique();
  33098. this.updateVerticesData(kind, data, updateExtends, false);
  33099. }
  33100. return this;
  33101. };
  33102. /**
  33103. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  33104. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  33105. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  33106. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  33107. * @returns the current mesh
  33108. */
  33109. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  33110. if (computeNormals === void 0) { computeNormals = true; }
  33111. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33112. if (!positions) {
  33113. return this;
  33114. }
  33115. positionFunction(positions);
  33116. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  33117. if (computeNormals) {
  33118. var indices = this.getIndices();
  33119. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33120. if (!normals) {
  33121. return this;
  33122. }
  33123. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  33124. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  33125. }
  33126. return this;
  33127. };
  33128. /**
  33129. * Creates a un-shared specific occurence of the geometry for the mesh.
  33130. * @returns the current mesh
  33131. */
  33132. Mesh.prototype.makeGeometryUnique = function () {
  33133. if (!this._geometry) {
  33134. return this;
  33135. }
  33136. var oldGeometry = this._geometry;
  33137. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  33138. oldGeometry.releaseForMesh(this, true);
  33139. geometry.applyToMesh(this);
  33140. return this;
  33141. };
  33142. /**
  33143. * Set the index buffer of this mesh
  33144. * @param indices defines the source data
  33145. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  33146. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  33147. * @returns the current mesh
  33148. */
  33149. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  33150. if (totalVertices === void 0) { totalVertices = null; }
  33151. if (updatable === void 0) { updatable = false; }
  33152. if (!this._geometry) {
  33153. var vertexData = new BABYLON.VertexData();
  33154. vertexData.indices = indices;
  33155. var scene = this.getScene();
  33156. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  33157. }
  33158. else {
  33159. this._geometry.setIndices(indices, totalVertices, updatable);
  33160. }
  33161. return this;
  33162. };
  33163. /**
  33164. * Update the current index buffer
  33165. * @param indices defines the source data
  33166. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  33167. * @returns the current mesh
  33168. */
  33169. Mesh.prototype.updateIndices = function (indices, offset) {
  33170. if (!this._geometry) {
  33171. return this;
  33172. }
  33173. this._geometry.updateIndices(indices, offset);
  33174. return this;
  33175. };
  33176. /**
  33177. * Invert the geometry to move from a right handed system to a left handed one.
  33178. * @returns the current mesh
  33179. */
  33180. Mesh.prototype.toLeftHanded = function () {
  33181. if (!this._geometry) {
  33182. return this;
  33183. }
  33184. this._geometry.toLeftHanded();
  33185. return this;
  33186. };
  33187. /** @hidden */
  33188. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  33189. if (!this._geometry) {
  33190. return this;
  33191. }
  33192. var engine = this.getScene().getEngine();
  33193. // Wireframe
  33194. var indexToBind;
  33195. if (this._unIndexed) {
  33196. indexToBind = null;
  33197. }
  33198. else {
  33199. switch (fillMode) {
  33200. case BABYLON.Material.PointFillMode:
  33201. indexToBind = null;
  33202. break;
  33203. case BABYLON.Material.WireFrameFillMode:
  33204. indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
  33205. break;
  33206. default:
  33207. case BABYLON.Material.TriangleFillMode:
  33208. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  33209. break;
  33210. }
  33211. }
  33212. // VBOs
  33213. this._geometry._bind(effect, indexToBind);
  33214. return this;
  33215. };
  33216. /** @hidden */
  33217. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  33218. if (alternate === void 0) { alternate = false; }
  33219. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33220. return this;
  33221. }
  33222. if (this._onBeforeDrawObservable) {
  33223. this._onBeforeDrawObservable.notifyObservers(this);
  33224. }
  33225. var scene = this.getScene();
  33226. var engine = scene.getEngine();
  33227. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  33228. // or triangles as points
  33229. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  33230. }
  33231. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  33232. // Triangles as wireframe
  33233. engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
  33234. }
  33235. else {
  33236. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  33237. }
  33238. if (scene._isAlternateRenderingEnabled && !alternate) {
  33239. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  33240. if (!effect || !scene.activeCamera) {
  33241. return this;
  33242. }
  33243. scene._switchToAlternateCameraConfiguration(true);
  33244. this._effectiveMaterial.bindView(effect);
  33245. this._effectiveMaterial.bindViewProjection(effect);
  33246. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  33247. this._draw(subMesh, fillMode, instancesCount, true);
  33248. engine.setViewport(scene.activeCamera.viewport);
  33249. scene._switchToAlternateCameraConfiguration(false);
  33250. this._effectiveMaterial.bindView(effect);
  33251. this._effectiveMaterial.bindViewProjection(effect);
  33252. }
  33253. return this;
  33254. };
  33255. /**
  33256. * Registers for this mesh a javascript function called just before the rendering process
  33257. * @param func defines the function to call before rendering this mesh
  33258. * @returns the current mesh
  33259. */
  33260. Mesh.prototype.registerBeforeRender = function (func) {
  33261. this.onBeforeRenderObservable.add(func);
  33262. return this;
  33263. };
  33264. /**
  33265. * Disposes a previously registered javascript function called before the rendering
  33266. * @param func defines the function to remove
  33267. * @returns the current mesh
  33268. */
  33269. Mesh.prototype.unregisterBeforeRender = function (func) {
  33270. this.onBeforeRenderObservable.removeCallback(func);
  33271. return this;
  33272. };
  33273. /**
  33274. * Registers for this mesh a javascript function called just after the rendering is complete
  33275. * @param func defines the function to call after rendering this mesh
  33276. * @returns the current mesh
  33277. */
  33278. Mesh.prototype.registerAfterRender = function (func) {
  33279. this.onAfterRenderObservable.add(func);
  33280. return this;
  33281. };
  33282. /**
  33283. * Disposes a previously registered javascript function called after the rendering.
  33284. * @param func defines the function to remove
  33285. * @returns the current mesh
  33286. */
  33287. Mesh.prototype.unregisterAfterRender = function (func) {
  33288. this.onAfterRenderObservable.removeCallback(func);
  33289. return this;
  33290. };
  33291. /** @hidden */
  33292. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  33293. var scene = this.getScene();
  33294. var batchCache = this._instanceDataStorage.batchCache;
  33295. batchCache.mustReturn = false;
  33296. batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  33297. batchCache.visibleInstances[subMeshId] = null;
  33298. if (this._instanceDataStorage.visibleInstances) {
  33299. var visibleInstances = this._instanceDataStorage.visibleInstances;
  33300. var currentRenderId = scene.getRenderId();
  33301. var defaultRenderId = (scene._isInIntermediateRendering() ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId);
  33302. batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
  33303. var selfRenderId = this._renderId;
  33304. if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  33305. batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
  33306. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  33307. selfRenderId = Math.max(visibleInstances.selfDefaultRenderId, currentRenderId);
  33308. }
  33309. var visibleInstancesForSubMesh = batchCache.visibleInstances[subMeshId];
  33310. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  33311. if (this._instanceDataStorage.renderIdForInstances[subMeshId] === currentRenderId) {
  33312. batchCache.mustReturn = true;
  33313. return batchCache;
  33314. }
  33315. if (currentRenderId !== selfRenderId) {
  33316. batchCache.renderSelf[subMeshId] = false;
  33317. }
  33318. }
  33319. this._instanceDataStorage.renderIdForInstances[subMeshId] = currentRenderId;
  33320. }
  33321. return batchCache;
  33322. };
  33323. /** @hidden */
  33324. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  33325. var visibleInstances = batch.visibleInstances[subMesh._id];
  33326. if (!visibleInstances) {
  33327. return this;
  33328. }
  33329. var matricesCount = visibleInstances.length + 1;
  33330. var bufferSize = matricesCount * 16 * 4;
  33331. var instanceStorage = this._instanceDataStorage;
  33332. var currentInstancesBufferSize = instanceStorage.instancesBufferSize;
  33333. var instancesBuffer = instanceStorage.instancesBuffer;
  33334. while (instanceStorage.instancesBufferSize < bufferSize) {
  33335. instanceStorage.instancesBufferSize *= 2;
  33336. }
  33337. if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33338. instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
  33339. }
  33340. var offset = 0;
  33341. var instancesCount = 0;
  33342. var world = this.getWorldMatrix();
  33343. if (batch.renderSelf[subMesh._id]) {
  33344. world.copyToArray(instanceStorage.instancesData, offset);
  33345. offset += 16;
  33346. instancesCount++;
  33347. }
  33348. if (visibleInstances) {
  33349. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  33350. var instance = visibleInstances[instanceIndex];
  33351. instance.getWorldMatrix().copyToArray(instanceStorage.instancesData, offset);
  33352. offset += 16;
  33353. instancesCount++;
  33354. }
  33355. }
  33356. if (!instancesBuffer || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33357. if (instancesBuffer) {
  33358. instancesBuffer.dispose();
  33359. }
  33360. instancesBuffer = new BABYLON.Buffer(engine, instanceStorage.instancesData, true, 16, false, true);
  33361. instanceStorage.instancesBuffer = instancesBuffer;
  33362. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  33363. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  33364. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  33365. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  33366. }
  33367. else {
  33368. instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
  33369. }
  33370. this._bind(subMesh, effect, fillMode);
  33371. this._draw(subMesh, fillMode, instancesCount);
  33372. engine.unbindInstanceAttributes();
  33373. return this;
  33374. };
  33375. /** @hidden */
  33376. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  33377. var scene = this.getScene();
  33378. var engine = scene.getEngine();
  33379. if (hardwareInstancedRendering) {
  33380. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  33381. }
  33382. else {
  33383. if (batch.renderSelf[subMesh._id]) {
  33384. // Draw
  33385. if (onBeforeDraw) {
  33386. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  33387. }
  33388. this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
  33389. }
  33390. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  33391. if (visibleInstancesForSubMesh) {
  33392. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  33393. var instance = visibleInstancesForSubMesh[instanceIndex];
  33394. // World
  33395. var world = instance.getWorldMatrix();
  33396. if (onBeforeDraw) {
  33397. onBeforeDraw(true, world, effectiveMaterial);
  33398. }
  33399. // Draw
  33400. this._draw(subMesh, fillMode);
  33401. }
  33402. }
  33403. }
  33404. return this;
  33405. };
  33406. /**
  33407. * 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
  33408. * @param subMesh defines the subMesh to render
  33409. * @param enableAlphaMode defines if alpha mode can be changed
  33410. * @returns the current mesh
  33411. */
  33412. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  33413. if (this._checkOcclusionQuery()) {
  33414. return this;
  33415. }
  33416. var scene = this.getScene();
  33417. // Managing instances
  33418. var batch = this._getInstancesRenderList(subMesh._id);
  33419. if (batch.mustReturn) {
  33420. return this;
  33421. }
  33422. // Checking geometry state
  33423. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33424. return this;
  33425. }
  33426. if (this._onBeforeRenderObservable) {
  33427. this._onBeforeRenderObservable.notifyObservers(this);
  33428. }
  33429. var engine = scene.getEngine();
  33430. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33431. // Material
  33432. var material = subMesh.getMaterial();
  33433. if (!material) {
  33434. return this;
  33435. }
  33436. this._effectiveMaterial = material;
  33437. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33438. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  33439. return this;
  33440. }
  33441. }
  33442. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  33443. return this;
  33444. }
  33445. // Alpha mode
  33446. if (enableAlphaMode) {
  33447. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  33448. }
  33449. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  33450. var step = _a[_i];
  33451. step.action(this, subMesh, batch);
  33452. }
  33453. var effect;
  33454. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33455. effect = subMesh.effect;
  33456. }
  33457. else {
  33458. effect = this._effectiveMaterial.getEffect();
  33459. }
  33460. if (!effect) {
  33461. return this;
  33462. }
  33463. var sideOrientation = this.overrideMaterialSideOrientation;
  33464. if (sideOrientation == null) {
  33465. sideOrientation = this._effectiveMaterial.sideOrientation;
  33466. if (this._getWorldMatrixDeterminant() < 0) {
  33467. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  33468. }
  33469. }
  33470. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  33471. if (this._effectiveMaterial.forceDepthWrite) {
  33472. engine.setDepthWrite(true);
  33473. }
  33474. // Bind
  33475. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  33476. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  33477. this._bind(subMesh, effect, fillMode);
  33478. }
  33479. var world = this.getWorldMatrix();
  33480. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33481. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  33482. }
  33483. else {
  33484. this._effectiveMaterial.bind(world, this);
  33485. }
  33486. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  33487. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  33488. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33489. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  33490. }
  33491. // Draw
  33492. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33493. // Unbind
  33494. this._effectiveMaterial.unbind();
  33495. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  33496. var step = _c[_b];
  33497. step.action(this, subMesh, batch);
  33498. }
  33499. if (this._onAfterRenderObservable) {
  33500. this._onAfterRenderObservable.notifyObservers(this);
  33501. }
  33502. return this;
  33503. };
  33504. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  33505. if (isInstance && effectiveMaterial) {
  33506. effectiveMaterial.bindOnlyWorldMatrix(world);
  33507. }
  33508. };
  33509. /**
  33510. * Renormalize the mesh and patch it up if there are no weights
  33511. * Similar to normalization by adding the weights compute the reciprocal and multiply all elements, this wil ensure that everything adds to 1.
  33512. * However in the case of zero weights then we set just a single influence to 1.
  33513. * We check in the function for extra's present and if so we use the normalizeSkinWeightsWithExtras rather than the FourWeights version.
  33514. */
  33515. Mesh.prototype.cleanMatrixWeights = function () {
  33516. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33517. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33518. this.normalizeSkinWeightsAndExtra();
  33519. }
  33520. else {
  33521. this.normalizeSkinFourWeights();
  33522. }
  33523. }
  33524. };
  33525. // faster 4 weight version.
  33526. Mesh.prototype.normalizeSkinFourWeights = function () {
  33527. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33528. var numWeights = matricesWeights.length;
  33529. for (var a = 0; a < numWeights; a += 4) {
  33530. // accumulate weights
  33531. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  33532. // check for invalid weight and just set it to 1.
  33533. if (t === 0) {
  33534. matricesWeights[a] = 1;
  33535. }
  33536. else {
  33537. // renormalize so everything adds to 1 use reciprical
  33538. var recip = 1 / t;
  33539. matricesWeights[a] *= recip;
  33540. matricesWeights[a + 1] *= recip;
  33541. matricesWeights[a + 2] *= recip;
  33542. matricesWeights[a + 3] *= recip;
  33543. }
  33544. }
  33545. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33546. };
  33547. // handle special case of extra verts. (in theory gltf can handle 12 influences)
  33548. Mesh.prototype.normalizeSkinWeightsAndExtra = function () {
  33549. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33550. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33551. var numWeights = matricesWeights.length;
  33552. for (var a = 0; a < numWeights; a += 4) {
  33553. // accumulate weights
  33554. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  33555. t += matricesWeightsExtra[a] + matricesWeightsExtra[a + 1] + matricesWeightsExtra[a + 2] + matricesWeightsExtra[a + 3];
  33556. // check for invalid weight and just set it to 1.
  33557. if (t === 0) {
  33558. matricesWeights[a] = 1;
  33559. }
  33560. else {
  33561. // renormalize so everything adds to 1 use reciprical
  33562. var recip = 1 / t;
  33563. matricesWeights[a] *= recip;
  33564. matricesWeights[a + 1] *= recip;
  33565. matricesWeights[a + 2] *= recip;
  33566. matricesWeights[a + 3] *= recip;
  33567. // same goes for extras
  33568. matricesWeightsExtra[a] *= recip;
  33569. matricesWeightsExtra[a + 1] *= recip;
  33570. matricesWeightsExtra[a + 2] *= recip;
  33571. matricesWeightsExtra[a + 3] *= recip;
  33572. }
  33573. }
  33574. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33575. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsExtra);
  33576. };
  33577. /**
  33578. * ValidateSkinning is used to determine that a mesh has valid skinning data along with skin metrics, if missing weights,
  33579. * or not normalized it is returned as invalid mesh the string can be used for console logs, or on screen messages to let
  33580. * the user know there was an issue with importing the mesh
  33581. * @returns a validation object with skinned, valid and report string
  33582. */
  33583. Mesh.prototype.validateSkinning = function () {
  33584. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33585. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33586. if (matricesWeights === null || this.skeleton == null) {
  33587. return { skinned: false, valid: true, report: "not skinned" };
  33588. }
  33589. var numWeights = matricesWeights.length;
  33590. var numberNotSorted = 0;
  33591. var missingWeights = 0;
  33592. var maxUsedWeights = 0;
  33593. var numberNotNormalized = 0;
  33594. var numInfluences = matricesWeightsExtra === null ? 4 : 8;
  33595. var usedWeightCounts = new Array();
  33596. for (var a = 0; a <= numInfluences; a++) {
  33597. usedWeightCounts[a] = 0;
  33598. }
  33599. var toleranceEpsilon = 0.001;
  33600. for (var a = 0; a < numWeights; a += 4) {
  33601. var lastWeight = matricesWeights[a];
  33602. var t = lastWeight;
  33603. var usedWeights = t === 0 ? 0 : 1;
  33604. for (var b = 1; b < numInfluences; b++) {
  33605. var d = b < 4 ? matricesWeights[a + b] : matricesWeightsExtra[a + b - 4];
  33606. if (d > lastWeight) {
  33607. numberNotSorted++;
  33608. }
  33609. if (d !== 0) {
  33610. usedWeights++;
  33611. }
  33612. t += d;
  33613. lastWeight = d;
  33614. }
  33615. // count the buffer weights usage
  33616. usedWeightCounts[usedWeights]++;
  33617. // max influences
  33618. if (usedWeights > maxUsedWeights) {
  33619. maxUsedWeights = usedWeights;
  33620. }
  33621. // check for invalid weight and just set it to 1.
  33622. if (t === 0) {
  33623. missingWeights++;
  33624. }
  33625. else {
  33626. // renormalize so everything adds to 1 use reciprical
  33627. var recip = 1 / t;
  33628. var tolerance = 0;
  33629. for (b = 0; b < numInfluences; b++) {
  33630. if (b < 4) {
  33631. tolerance += Math.abs(matricesWeights[a + b] - (matricesWeights[a + b] * recip));
  33632. }
  33633. else {
  33634. tolerance += Math.abs(matricesWeightsExtra[a + b - 4] - (matricesWeightsExtra[a + b - 4] * recip));
  33635. }
  33636. }
  33637. // arbitary epsilon value for dicdating not normalized
  33638. if (tolerance > toleranceEpsilon) {
  33639. numberNotNormalized++;
  33640. }
  33641. }
  33642. }
  33643. // validate bone indices are in range of the skeleton
  33644. var numBones = this.skeleton.bones.length;
  33645. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33646. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33647. var numBadBoneIndices = 0;
  33648. for (var a = 0; a < numWeights; a++) {
  33649. for (var b = 0; b < numInfluences; b++) {
  33650. var index = b < 4 ? matricesIndices[b] : matricesIndicesExtra[b - 4];
  33651. if (index >= numBones || index < 0) {
  33652. numBadBoneIndices++;
  33653. }
  33654. }
  33655. }
  33656. // log mesh stats
  33657. var output = "Number of Weights = " + numWeights / 4 + "\nMaximum influences = " + maxUsedWeights +
  33658. "\nMissing Weights = " + missingWeights + "\nNot Sorted = " + numberNotSorted +
  33659. "\nNot Normalized = " + numberNotNormalized + "\nWeightCounts = [" + usedWeightCounts + "]" +
  33660. "\nNumber of bones = " + numBones + "\nBad Bone Indices = " + numBadBoneIndices;
  33661. return { skinned: true, valid: missingWeights === 0 && numberNotNormalized === 0 && numBadBoneIndices === 0, report: output };
  33662. };
  33663. /** @hidden */
  33664. Mesh.prototype._checkDelayState = function () {
  33665. var scene = this.getScene();
  33666. if (this._geometry) {
  33667. this._geometry.load(scene);
  33668. }
  33669. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33670. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33671. this._queueLoad(scene);
  33672. }
  33673. return this;
  33674. };
  33675. Mesh.prototype._queueLoad = function (scene) {
  33676. var _this = this;
  33677. scene._addPendingData(this);
  33678. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  33679. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  33680. if (data instanceof ArrayBuffer) {
  33681. _this._delayLoadingFunction(data, _this);
  33682. }
  33683. else {
  33684. _this._delayLoadingFunction(JSON.parse(data), _this);
  33685. }
  33686. _this.instances.forEach(function (instance) {
  33687. instance._syncSubMeshes();
  33688. });
  33689. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33690. scene._removePendingData(_this);
  33691. }, function () { }, scene.database, getBinaryData);
  33692. return this;
  33693. };
  33694. /**
  33695. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  33696. * A mesh is in the frustum if its bounding box intersects the frustum
  33697. * @param frustumPlanes defines the frustum to test
  33698. * @returns true if the mesh is in the frustum planes
  33699. */
  33700. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  33701. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33702. return false;
  33703. }
  33704. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  33705. return false;
  33706. }
  33707. this._checkDelayState();
  33708. return true;
  33709. };
  33710. /**
  33711. * Sets the mesh material by the material or multiMaterial `id` property
  33712. * @param id is a string identifying the material or the multiMaterial
  33713. * @returns the current mesh
  33714. */
  33715. Mesh.prototype.setMaterialByID = function (id) {
  33716. var materials = this.getScene().materials;
  33717. var index;
  33718. for (index = materials.length - 1; index > -1; index--) {
  33719. if (materials[index].id === id) {
  33720. this.material = materials[index];
  33721. return this;
  33722. }
  33723. }
  33724. // Multi
  33725. var multiMaterials = this.getScene().multiMaterials;
  33726. for (index = multiMaterials.length - 1; index > -1; index--) {
  33727. if (multiMaterials[index].id === id) {
  33728. this.material = multiMaterials[index];
  33729. return this;
  33730. }
  33731. }
  33732. return this;
  33733. };
  33734. /**
  33735. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  33736. * @returns an array of IAnimatable
  33737. */
  33738. Mesh.prototype.getAnimatables = function () {
  33739. var results = new Array();
  33740. if (this.material) {
  33741. results.push(this.material);
  33742. }
  33743. if (this.skeleton) {
  33744. results.push(this.skeleton);
  33745. }
  33746. return results;
  33747. };
  33748. /**
  33749. * Modifies the mesh geometry according to the passed transformation matrix.
  33750. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  33751. * The mesh normals are modified using the same transformation.
  33752. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33753. * @param transform defines the transform matrix to use
  33754. * @see http://doc.babylonjs.com/resources/baking_transformations
  33755. * @returns the current mesh
  33756. */
  33757. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  33758. // Position
  33759. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33760. return this;
  33761. }
  33762. var submeshes = this.subMeshes.splice(0);
  33763. this._resetPointsArrayCache();
  33764. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33765. var temp = new Array();
  33766. var index;
  33767. for (index = 0; index < data.length; index += 3) {
  33768. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  33769. }
  33770. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  33771. // Normals
  33772. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33773. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33774. temp = [];
  33775. for (index = 0; index < data.length; index += 3) {
  33776. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  33777. }
  33778. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  33779. }
  33780. // flip faces?
  33781. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  33782. this.flipFaces();
  33783. }
  33784. // Restore submeshes
  33785. this.releaseSubMeshes();
  33786. this.subMeshes = submeshes;
  33787. return this;
  33788. };
  33789. /**
  33790. * Modifies the mesh geometry according to its own current World Matrix.
  33791. * The mesh World Matrix is then reset.
  33792. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  33793. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33794. * @see http://doc.babylonjs.com/resources/baking_transformations
  33795. * @returns the current mesh
  33796. */
  33797. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  33798. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  33799. this.scaling.copyFromFloats(1, 1, 1);
  33800. this.position.copyFromFloats(0, 0, 0);
  33801. this.rotation.copyFromFloats(0, 0, 0);
  33802. //only if quaternion is already set
  33803. if (this.rotationQuaternion) {
  33804. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  33805. }
  33806. this._worldMatrix = BABYLON.Matrix.Identity();
  33807. return this;
  33808. };
  33809. Object.defineProperty(Mesh.prototype, "_positions", {
  33810. // Cache
  33811. /** @hidden */
  33812. get: function () {
  33813. if (this._geometry) {
  33814. return this._geometry._positions;
  33815. }
  33816. return null;
  33817. },
  33818. enumerable: true,
  33819. configurable: true
  33820. });
  33821. /** @hidden */
  33822. Mesh.prototype._resetPointsArrayCache = function () {
  33823. if (this._geometry) {
  33824. this._geometry._resetPointsArrayCache();
  33825. }
  33826. return this;
  33827. };
  33828. /** @hidden */
  33829. Mesh.prototype._generatePointsArray = function () {
  33830. if (this._geometry) {
  33831. return this._geometry._generatePointsArray();
  33832. }
  33833. return false;
  33834. };
  33835. /**
  33836. * Returns a new Mesh object generated from the current mesh properties.
  33837. * This method must not get confused with createInstance()
  33838. * @param name is a string, the name given to the new mesh
  33839. * @param newParent can be any Node object (default `null`)
  33840. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  33841. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  33842. * @returns a new mesh
  33843. */
  33844. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  33845. if (name === void 0) { name = ""; }
  33846. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  33847. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  33848. };
  33849. /**
  33850. * Releases resources associated with this mesh.
  33851. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  33852. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  33853. */
  33854. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  33855. var _this = this;
  33856. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  33857. this.morphTargetManager = null;
  33858. if (this._geometry) {
  33859. this._geometry.releaseForMesh(this, true);
  33860. }
  33861. if (this._onBeforeDrawObservable) {
  33862. this._onBeforeDrawObservable.clear();
  33863. }
  33864. if (this._onBeforeRenderObservable) {
  33865. this._onBeforeRenderObservable.clear();
  33866. }
  33867. if (this._onAfterRenderObservable) {
  33868. this._onAfterRenderObservable.clear();
  33869. }
  33870. // Sources
  33871. var meshes = this.getScene().meshes;
  33872. meshes.forEach(function (abstractMesh) {
  33873. var mesh = abstractMesh;
  33874. if (mesh._source && mesh._source === _this) {
  33875. mesh._source = null;
  33876. }
  33877. });
  33878. this._source = null;
  33879. // Instances
  33880. if (this._instanceDataStorage.instancesBuffer) {
  33881. this._instanceDataStorage.instancesBuffer.dispose();
  33882. this._instanceDataStorage.instancesBuffer = null;
  33883. }
  33884. while (this.instances.length) {
  33885. this.instances[0].dispose();
  33886. }
  33887. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  33888. };
  33889. /**
  33890. * Modifies the mesh geometry according to a displacement map.
  33891. * 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.
  33892. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33893. * @param url is a string, the URL from the image file is to be downloaded.
  33894. * @param minHeight is the lower limit of the displacement.
  33895. * @param maxHeight is the upper limit of the displacement.
  33896. * @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.
  33897. * @param uvOffset is an optional vector2 used to offset UV.
  33898. * @param uvScale is an optional vector2 used to scale UV.
  33899. * @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.
  33900. * @returns the Mesh.
  33901. */
  33902. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  33903. var _this = this;
  33904. if (forceUpdate === void 0) { forceUpdate = false; }
  33905. var scene = this.getScene();
  33906. var onload = function (img) {
  33907. // Getting height map data
  33908. var canvas = document.createElement("canvas");
  33909. var context = canvas.getContext("2d");
  33910. var heightMapWidth = img.width;
  33911. var heightMapHeight = img.height;
  33912. canvas.width = heightMapWidth;
  33913. canvas.height = heightMapHeight;
  33914. context.drawImage(img, 0, 0);
  33915. // Create VertexData from map data
  33916. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33917. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33918. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  33919. //execute success callback, if set
  33920. if (onSuccess) {
  33921. onSuccess(_this);
  33922. }
  33923. };
  33924. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33925. return this;
  33926. };
  33927. /**
  33928. * Modifies the mesh geometry according to a displacementMap buffer.
  33929. * 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.
  33930. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33931. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  33932. * @param heightMapWidth is the width of the buffer image.
  33933. * @param heightMapHeight is the height of the buffer image.
  33934. * @param minHeight is the lower limit of the displacement.
  33935. * @param maxHeight is the upper limit of the displacement.
  33936. * @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.
  33937. * @param uvOffset is an optional vector2 used to offset UV.
  33938. * @param uvScale is an optional vector2 used to scale UV.
  33939. * @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.
  33940. * @returns the Mesh.
  33941. */
  33942. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  33943. if (forceUpdate === void 0) { forceUpdate = false; }
  33944. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33945. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33946. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33947. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33948. return this;
  33949. }
  33950. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  33951. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33952. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33953. var position = BABYLON.Vector3.Zero();
  33954. var normal = BABYLON.Vector3.Zero();
  33955. var uv = BABYLON.Vector2.Zero();
  33956. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33957. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33958. for (var index = 0; index < positions.length; index += 3) {
  33959. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33960. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33961. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33962. // Compute height
  33963. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33964. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33965. var pos = (u + v * heightMapWidth) * 4;
  33966. var r = buffer[pos] / 255.0;
  33967. var g = buffer[pos + 1] / 255.0;
  33968. var b = buffer[pos + 2] / 255.0;
  33969. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33970. normal.normalize();
  33971. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33972. position = position.add(normal);
  33973. position.toArray(positions, index);
  33974. }
  33975. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33976. if (forceUpdate) {
  33977. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33978. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33979. }
  33980. else {
  33981. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33982. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33983. }
  33984. return this;
  33985. };
  33986. /**
  33987. * Modify the mesh to get a flat shading rendering.
  33988. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33989. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33990. * @returns current mesh
  33991. */
  33992. Mesh.prototype.convertToFlatShadedMesh = function () {
  33993. var kinds = this.getVerticesDataKinds();
  33994. var vbs = {};
  33995. var data = {};
  33996. var newdata = {};
  33997. var updatableNormals = false;
  33998. var kindIndex;
  33999. var kind;
  34000. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34001. kind = kinds[kindIndex];
  34002. var vertexBuffer = this.getVertexBuffer(kind);
  34003. if (kind === BABYLON.VertexBuffer.NormalKind) {
  34004. updatableNormals = vertexBuffer.isUpdatable();
  34005. kinds.splice(kindIndex, 1);
  34006. kindIndex--;
  34007. continue;
  34008. }
  34009. vbs[kind] = vertexBuffer;
  34010. data[kind] = vbs[kind].getData();
  34011. newdata[kind] = [];
  34012. }
  34013. // Save previous submeshes
  34014. var previousSubmeshes = this.subMeshes.slice(0);
  34015. var indices = this.getIndices();
  34016. var totalIndices = this.getTotalIndices();
  34017. // Generating unique vertices per face
  34018. var index;
  34019. for (index = 0; index < totalIndices; index++) {
  34020. var vertexIndex = indices[index];
  34021. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34022. kind = kinds[kindIndex];
  34023. var stride = vbs[kind].getStrideSize();
  34024. for (var offset = 0; offset < stride; offset++) {
  34025. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  34026. }
  34027. }
  34028. }
  34029. // Updating faces & normal
  34030. var normals = [];
  34031. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  34032. for (index = 0; index < totalIndices; index += 3) {
  34033. indices[index] = index;
  34034. indices[index + 1] = index + 1;
  34035. indices[index + 2] = index + 2;
  34036. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  34037. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  34038. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  34039. var p1p2 = p1.subtract(p2);
  34040. var p3p2 = p3.subtract(p2);
  34041. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  34042. // Store same normals for every vertex
  34043. for (var localIndex = 0; localIndex < 3; localIndex++) {
  34044. normals.push(normal.x);
  34045. normals.push(normal.y);
  34046. normals.push(normal.z);
  34047. }
  34048. }
  34049. this.setIndices(indices);
  34050. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  34051. // Updating vertex buffers
  34052. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34053. kind = kinds[kindIndex];
  34054. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  34055. }
  34056. // Updating submeshes
  34057. this.releaseSubMeshes();
  34058. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  34059. var previousOne = previousSubmeshes[submeshIndex];
  34060. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  34061. }
  34062. this.synchronizeInstances();
  34063. return this;
  34064. };
  34065. /**
  34066. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  34067. * In other words, more vertices, no more indices and a single bigger VBO.
  34068. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  34069. * @returns current mesh
  34070. */
  34071. Mesh.prototype.convertToUnIndexedMesh = function () {
  34072. var kinds = this.getVerticesDataKinds();
  34073. var vbs = {};
  34074. var data = {};
  34075. var newdata = {};
  34076. var kindIndex;
  34077. var kind;
  34078. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34079. kind = kinds[kindIndex];
  34080. var vertexBuffer = this.getVertexBuffer(kind);
  34081. vbs[kind] = vertexBuffer;
  34082. data[kind] = vbs[kind].getData();
  34083. newdata[kind] = [];
  34084. }
  34085. // Save previous submeshes
  34086. var previousSubmeshes = this.subMeshes.slice(0);
  34087. var indices = this.getIndices();
  34088. var totalIndices = this.getTotalIndices();
  34089. // Generating unique vertices per face
  34090. var index;
  34091. for (index = 0; index < totalIndices; index++) {
  34092. var vertexIndex = indices[index];
  34093. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34094. kind = kinds[kindIndex];
  34095. var stride = vbs[kind].getStrideSize();
  34096. for (var offset = 0; offset < stride; offset++) {
  34097. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  34098. }
  34099. }
  34100. }
  34101. // Updating indices
  34102. for (index = 0; index < totalIndices; index += 3) {
  34103. indices[index] = index;
  34104. indices[index + 1] = index + 1;
  34105. indices[index + 2] = index + 2;
  34106. }
  34107. this.setIndices(indices);
  34108. // Updating vertex buffers
  34109. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34110. kind = kinds[kindIndex];
  34111. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  34112. }
  34113. // Updating submeshes
  34114. this.releaseSubMeshes();
  34115. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  34116. var previousOne = previousSubmeshes[submeshIndex];
  34117. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  34118. }
  34119. this._unIndexed = true;
  34120. this.synchronizeInstances();
  34121. return this;
  34122. };
  34123. /**
  34124. * Inverses facet orientations.
  34125. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  34126. * @param flipNormals will also inverts the normals
  34127. * @returns current mesh
  34128. */
  34129. Mesh.prototype.flipFaces = function (flipNormals) {
  34130. if (flipNormals === void 0) { flipNormals = false; }
  34131. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  34132. var i;
  34133. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  34134. for (i = 0; i < vertex_data.normals.length; i++) {
  34135. vertex_data.normals[i] *= -1;
  34136. }
  34137. }
  34138. if (vertex_data.indices) {
  34139. var temp;
  34140. for (i = 0; i < vertex_data.indices.length; i += 3) {
  34141. // reassign indices
  34142. temp = vertex_data.indices[i + 1];
  34143. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  34144. vertex_data.indices[i + 2] = temp;
  34145. }
  34146. }
  34147. vertex_data.applyToMesh(this);
  34148. return this;
  34149. };
  34150. // Instances
  34151. /**
  34152. * Creates a new InstancedMesh object from the mesh model.
  34153. * Warning : this method is not supported for Line mesh and LineSystem
  34154. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  34155. * @param name defines the name of the new instance
  34156. * @returns a new InstancedMesh
  34157. */
  34158. Mesh.prototype.createInstance = function (name) {
  34159. return new BABYLON.InstancedMesh(name, this);
  34160. };
  34161. /**
  34162. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  34163. * After this call, all the mesh instances have the same submeshes than the current mesh.
  34164. * @returns the current mesh
  34165. */
  34166. Mesh.prototype.synchronizeInstances = function () {
  34167. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  34168. var instance = this.instances[instanceIndex];
  34169. instance._syncSubMeshes();
  34170. }
  34171. return this;
  34172. };
  34173. /**
  34174. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  34175. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  34176. * This should be used together with the simplification to avoid disappearing triangles.
  34177. * @param successCallback an optional success callback to be called after the optimization finished.
  34178. * @returns the current mesh
  34179. */
  34180. Mesh.prototype.optimizeIndices = function (successCallback) {
  34181. var _this = this;
  34182. var indices = this.getIndices();
  34183. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34184. if (!positions || !indices) {
  34185. return this;
  34186. }
  34187. var vectorPositions = new Array();
  34188. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  34189. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  34190. }
  34191. var dupes = new Array();
  34192. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  34193. var realPos = vectorPositions.length - 1 - iteration;
  34194. var testedPosition = vectorPositions[realPos];
  34195. for (var j = 0; j < realPos; ++j) {
  34196. var againstPosition = vectorPositions[j];
  34197. if (testedPosition.equals(againstPosition)) {
  34198. dupes[realPos] = j;
  34199. break;
  34200. }
  34201. }
  34202. }, function () {
  34203. for (var i = 0; i < indices.length; ++i) {
  34204. indices[i] = dupes[indices[i]] || indices[i];
  34205. }
  34206. //indices are now reordered
  34207. var originalSubMeshes = _this.subMeshes.slice(0);
  34208. _this.setIndices(indices);
  34209. _this.subMeshes = originalSubMeshes;
  34210. if (successCallback) {
  34211. successCallback(_this);
  34212. }
  34213. });
  34214. return this;
  34215. };
  34216. /**
  34217. * Serialize current mesh
  34218. * @param serializationObject defines the object which will receive the serialization data
  34219. */
  34220. Mesh.prototype.serialize = function (serializationObject) {
  34221. serializationObject.name = this.name;
  34222. serializationObject.id = this.id;
  34223. serializationObject.type = this.getClassName();
  34224. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34225. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34226. }
  34227. serializationObject.position = this.position.asArray();
  34228. if (this.rotationQuaternion) {
  34229. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  34230. }
  34231. else if (this.rotation) {
  34232. serializationObject.rotation = this.rotation.asArray();
  34233. }
  34234. serializationObject.scaling = this.scaling.asArray();
  34235. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  34236. serializationObject.isEnabled = this.isEnabled(false);
  34237. serializationObject.isVisible = this.isVisible;
  34238. serializationObject.infiniteDistance = this.infiniteDistance;
  34239. serializationObject.pickable = this.isPickable;
  34240. serializationObject.receiveShadows = this.receiveShadows;
  34241. serializationObject.billboardMode = this.billboardMode;
  34242. serializationObject.visibility = this.visibility;
  34243. serializationObject.checkCollisions = this.checkCollisions;
  34244. serializationObject.isBlocker = this.isBlocker;
  34245. // Parent
  34246. if (this.parent) {
  34247. serializationObject.parentId = this.parent.id;
  34248. }
  34249. // Geometry
  34250. serializationObject.isUnIndexed = this.isUnIndexed;
  34251. var geometry = this._geometry;
  34252. if (geometry) {
  34253. var geometryId = geometry.id;
  34254. serializationObject.geometryId = geometryId;
  34255. // SubMeshes
  34256. serializationObject.subMeshes = [];
  34257. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  34258. var subMesh = this.subMeshes[subIndex];
  34259. serializationObject.subMeshes.push({
  34260. materialIndex: subMesh.materialIndex,
  34261. verticesStart: subMesh.verticesStart,
  34262. verticesCount: subMesh.verticesCount,
  34263. indexStart: subMesh.indexStart,
  34264. indexCount: subMesh.indexCount
  34265. });
  34266. }
  34267. }
  34268. // Material
  34269. if (this.material) {
  34270. serializationObject.materialId = this.material.id;
  34271. }
  34272. else {
  34273. this.material = null;
  34274. }
  34275. // Morph targets
  34276. if (this.morphTargetManager) {
  34277. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  34278. }
  34279. // Skeleton
  34280. if (this.skeleton) {
  34281. serializationObject.skeletonId = this.skeleton.id;
  34282. }
  34283. // Physics
  34284. //TODO implement correct serialization for physics impostors.
  34285. var impostor = this.getPhysicsImpostor();
  34286. if (impostor) {
  34287. serializationObject.physicsMass = impostor.getParam("mass");
  34288. serializationObject.physicsFriction = impostor.getParam("friction");
  34289. serializationObject.physicsRestitution = impostor.getParam("mass");
  34290. serializationObject.physicsImpostor = impostor.type;
  34291. }
  34292. // Metadata
  34293. if (this.metadata) {
  34294. serializationObject.metadata = this.metadata;
  34295. }
  34296. // Instances
  34297. serializationObject.instances = [];
  34298. for (var index = 0; index < this.instances.length; index++) {
  34299. var instance = this.instances[index];
  34300. if (instance.doNotSerialize) {
  34301. continue;
  34302. }
  34303. var serializationInstance = {
  34304. name: instance.name,
  34305. id: instance.id,
  34306. position: instance.position.asArray(),
  34307. scaling: instance.scaling.asArray()
  34308. };
  34309. if (instance.parent) {
  34310. serializationInstance.parentId = instance.parent.id;
  34311. }
  34312. if (instance.rotationQuaternion) {
  34313. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  34314. }
  34315. else if (instance.rotation) {
  34316. serializationInstance.rotation = instance.rotation.asArray();
  34317. }
  34318. serializationObject.instances.push(serializationInstance);
  34319. // Animations
  34320. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  34321. serializationInstance.ranges = instance.serializeAnimationRanges();
  34322. }
  34323. //
  34324. // Animations
  34325. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  34326. serializationObject.ranges = this.serializeAnimationRanges();
  34327. // Layer mask
  34328. serializationObject.layerMask = this.layerMask;
  34329. // Alpha
  34330. serializationObject.alphaIndex = this.alphaIndex;
  34331. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  34332. // Overlay
  34333. serializationObject.overlayAlpha = this.overlayAlpha;
  34334. serializationObject.overlayColor = this.overlayColor.asArray();
  34335. serializationObject.renderOverlay = this.renderOverlay;
  34336. // Fog
  34337. serializationObject.applyFog = this.applyFog;
  34338. // Action Manager
  34339. if (this.actionManager) {
  34340. serializationObject.actions = this.actionManager.serialize(this.name);
  34341. }
  34342. };
  34343. /** @hidden */
  34344. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  34345. if (!this.geometry) {
  34346. return;
  34347. }
  34348. this._markSubMeshesAsAttributesDirty();
  34349. var morphTargetManager = this._morphTargetManager;
  34350. if (morphTargetManager && morphTargetManager.vertexCount) {
  34351. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  34352. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  34353. this.morphTargetManager = null;
  34354. return;
  34355. }
  34356. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  34357. var morphTarget = morphTargetManager.getActiveTarget(index);
  34358. var positions = morphTarget.getPositions();
  34359. if (!positions) {
  34360. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  34361. return;
  34362. }
  34363. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  34364. var normals = morphTarget.getNormals();
  34365. if (normals) {
  34366. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  34367. }
  34368. var tangents = morphTarget.getTangents();
  34369. if (tangents) {
  34370. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  34371. }
  34372. }
  34373. }
  34374. else {
  34375. var index = 0;
  34376. // Positions
  34377. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  34378. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  34379. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  34380. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  34381. }
  34382. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  34383. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  34384. }
  34385. index++;
  34386. }
  34387. }
  34388. };
  34389. // Statics
  34390. /**
  34391. * Returns a new Mesh object parsed from the source provided.
  34392. * @param parsedMesh is the source
  34393. * @param scene defines the hosting scene
  34394. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  34395. * @returns a new Mesh
  34396. */
  34397. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  34398. var mesh;
  34399. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  34400. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  34401. }
  34402. else {
  34403. mesh = new Mesh(parsedMesh.name, scene);
  34404. }
  34405. mesh.id = parsedMesh.id;
  34406. if (BABYLON.Tags) {
  34407. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  34408. }
  34409. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  34410. if (parsedMesh.metadata !== undefined) {
  34411. mesh.metadata = parsedMesh.metadata;
  34412. }
  34413. if (parsedMesh.rotationQuaternion) {
  34414. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  34415. }
  34416. else if (parsedMesh.rotation) {
  34417. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  34418. }
  34419. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  34420. if (parsedMesh.localMatrix) {
  34421. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  34422. }
  34423. else if (parsedMesh.pivotMatrix) {
  34424. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  34425. }
  34426. mesh.setEnabled(parsedMesh.isEnabled);
  34427. mesh.isVisible = parsedMesh.isVisible;
  34428. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  34429. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  34430. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  34431. if (parsedMesh.applyFog !== undefined) {
  34432. mesh.applyFog = parsedMesh.applyFog;
  34433. }
  34434. if (parsedMesh.pickable !== undefined) {
  34435. mesh.isPickable = parsedMesh.pickable;
  34436. }
  34437. if (parsedMesh.alphaIndex !== undefined) {
  34438. mesh.alphaIndex = parsedMesh.alphaIndex;
  34439. }
  34440. mesh.receiveShadows = parsedMesh.receiveShadows;
  34441. mesh.billboardMode = parsedMesh.billboardMode;
  34442. if (parsedMesh.visibility !== undefined) {
  34443. mesh.visibility = parsedMesh.visibility;
  34444. }
  34445. mesh.checkCollisions = parsedMesh.checkCollisions;
  34446. if (parsedMesh.isBlocker !== undefined) {
  34447. mesh.isBlocker = parsedMesh.isBlocker;
  34448. }
  34449. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  34450. // freezeWorldMatrix
  34451. if (parsedMesh.freezeWorldMatrix) {
  34452. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  34453. }
  34454. // Parent
  34455. if (parsedMesh.parentId) {
  34456. mesh._waitingParentId = parsedMesh.parentId;
  34457. }
  34458. // Actions
  34459. if (parsedMesh.actions !== undefined) {
  34460. mesh._waitingActions = parsedMesh.actions;
  34461. }
  34462. // Overlay
  34463. if (parsedMesh.overlayAlpha !== undefined) {
  34464. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  34465. }
  34466. if (parsedMesh.overlayColor !== undefined) {
  34467. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  34468. }
  34469. if (parsedMesh.renderOverlay !== undefined) {
  34470. mesh.renderOverlay = parsedMesh.renderOverlay;
  34471. }
  34472. // Geometry
  34473. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  34474. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  34475. if (parsedMesh.delayLoadingFile) {
  34476. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34477. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  34478. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  34479. if (parsedMesh._binaryInfo) {
  34480. mesh._binaryInfo = parsedMesh._binaryInfo;
  34481. }
  34482. mesh._delayInfo = [];
  34483. if (parsedMesh.hasUVs) {
  34484. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  34485. }
  34486. if (parsedMesh.hasUVs2) {
  34487. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  34488. }
  34489. if (parsedMesh.hasUVs3) {
  34490. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  34491. }
  34492. if (parsedMesh.hasUVs4) {
  34493. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  34494. }
  34495. if (parsedMesh.hasUVs5) {
  34496. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  34497. }
  34498. if (parsedMesh.hasUVs6) {
  34499. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  34500. }
  34501. if (parsedMesh.hasColors) {
  34502. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  34503. }
  34504. if (parsedMesh.hasMatricesIndices) {
  34505. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34506. }
  34507. if (parsedMesh.hasMatricesWeights) {
  34508. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34509. }
  34510. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  34511. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  34512. mesh._checkDelayState();
  34513. }
  34514. }
  34515. else {
  34516. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  34517. }
  34518. // Material
  34519. if (parsedMesh.materialId) {
  34520. mesh.setMaterialByID(parsedMesh.materialId);
  34521. }
  34522. else {
  34523. mesh.material = null;
  34524. }
  34525. // Morph targets
  34526. if (parsedMesh.morphTargetManagerId > -1) {
  34527. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  34528. }
  34529. // Skeleton
  34530. if (parsedMesh.skeletonId > -1) {
  34531. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  34532. if (parsedMesh.numBoneInfluencers) {
  34533. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  34534. }
  34535. }
  34536. // Animations
  34537. if (parsedMesh.animations) {
  34538. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  34539. var parsedAnimation = parsedMesh.animations[animationIndex];
  34540. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34541. }
  34542. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  34543. }
  34544. if (parsedMesh.autoAnimate) {
  34545. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  34546. }
  34547. // Layer Mask
  34548. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  34549. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  34550. }
  34551. else {
  34552. mesh.layerMask = 0x0FFFFFFF;
  34553. }
  34554. // Physics
  34555. if (parsedMesh.physicsImpostor) {
  34556. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  34557. mass: parsedMesh.physicsMass,
  34558. friction: parsedMesh.physicsFriction,
  34559. restitution: parsedMesh.physicsRestitution
  34560. }, scene);
  34561. }
  34562. // Instances
  34563. if (parsedMesh.instances) {
  34564. for (var index = 0; index < parsedMesh.instances.length; index++) {
  34565. var parsedInstance = parsedMesh.instances[index];
  34566. var instance = mesh.createInstance(parsedInstance.name);
  34567. if (parsedInstance.id) {
  34568. instance.id = parsedInstance.id;
  34569. }
  34570. if (BABYLON.Tags) {
  34571. if (parsedInstance.tags) {
  34572. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  34573. }
  34574. else {
  34575. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  34576. }
  34577. }
  34578. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  34579. if (parsedInstance.parentId) {
  34580. instance._waitingParentId = parsedInstance.parentId;
  34581. }
  34582. if (parsedInstance.rotationQuaternion) {
  34583. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  34584. }
  34585. else if (parsedInstance.rotation) {
  34586. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  34587. }
  34588. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  34589. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  34590. instance.checkCollisions = parsedInstance.checkCollisions;
  34591. }
  34592. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  34593. instance.isPickable = parsedInstance.pickable;
  34594. }
  34595. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  34596. instance.showBoundingBox = parsedInstance.showBoundingBox;
  34597. }
  34598. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34599. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  34600. }
  34601. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34602. instance.alphaIndex = parsedInstance.alphaIndex;
  34603. }
  34604. // Physics
  34605. if (parsedInstance.physicsImpostor) {
  34606. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  34607. mass: parsedInstance.physicsMass,
  34608. friction: parsedInstance.physicsFriction,
  34609. restitution: parsedInstance.physicsRestitution
  34610. }, scene);
  34611. }
  34612. // Animation
  34613. if (parsedInstance.animations) {
  34614. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  34615. parsedAnimation = parsedInstance.animations[animationIndex];
  34616. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34617. }
  34618. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  34619. if (parsedInstance.autoAnimate) {
  34620. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  34621. }
  34622. }
  34623. }
  34624. }
  34625. return mesh;
  34626. };
  34627. /**
  34628. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  34629. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34630. * @param name defines the name of the mesh to create
  34631. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  34632. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  34633. * @param closePath creates a seam between the first and the last points of each path of the path array
  34634. * @param offset is taken in account only if the `pathArray` is containing a single path
  34635. * @param scene defines the hosting scene
  34636. * @param updatable defines if the mesh must be flagged as updatable
  34637. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34638. * @param instance defines an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#ribbon)
  34639. * @returns a new Mesh
  34640. */
  34641. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  34642. if (closeArray === void 0) { closeArray = false; }
  34643. if (updatable === void 0) { updatable = false; }
  34644. return BABYLON.MeshBuilder.CreateRibbon(name, {
  34645. pathArray: pathArray,
  34646. closeArray: closeArray,
  34647. closePath: closePath,
  34648. offset: offset,
  34649. updatable: updatable,
  34650. sideOrientation: sideOrientation,
  34651. instance: instance
  34652. }, scene);
  34653. };
  34654. /**
  34655. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  34656. * @param name defines the name of the mesh to create
  34657. * @param radius sets the radius size (float) of the polygon (default 0.5)
  34658. * @param tessellation sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc
  34659. * @param scene defines the hosting scene
  34660. * @param updatable defines if the mesh must be flagged as updatable
  34661. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34662. * @returns a new Mesh
  34663. */
  34664. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  34665. if (scene === void 0) { scene = null; }
  34666. var options = {
  34667. radius: radius,
  34668. tessellation: tessellation,
  34669. sideOrientation: sideOrientation,
  34670. updatable: updatable
  34671. };
  34672. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  34673. };
  34674. /**
  34675. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  34676. * @param name defines the name of the mesh to create
  34677. * @param size sets the size (float) of each box side (default 1)
  34678. * @param scene defines the hosting scene
  34679. * @param updatable defines if the mesh must be flagged as updatable
  34680. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34681. * @returns a new Mesh
  34682. */
  34683. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  34684. if (scene === void 0) { scene = null; }
  34685. var options = {
  34686. size: size,
  34687. sideOrientation: sideOrientation,
  34688. updatable: updatable
  34689. };
  34690. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  34691. };
  34692. /**
  34693. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  34694. * @param name defines the name of the mesh to create
  34695. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  34696. * @param diameter sets the diameter size (float) of the sphere (default 1)
  34697. * @param scene defines the hosting scene
  34698. * @param updatable defines if the mesh must be flagged as updatable
  34699. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34700. * @returns a new Mesh
  34701. */
  34702. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  34703. var options = {
  34704. segments: segments,
  34705. diameterX: diameter,
  34706. diameterY: diameter,
  34707. diameterZ: diameter,
  34708. sideOrientation: sideOrientation,
  34709. updatable: updatable
  34710. };
  34711. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  34712. };
  34713. /**
  34714. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  34715. * @param name defines the name of the mesh to create
  34716. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  34717. * @param diameterTop set the top cap diameter (floats, default 1)
  34718. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  34719. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  34720. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  34721. * @param scene defines the hosting scene
  34722. * @param updatable defines if the mesh must be flagged as updatable
  34723. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34724. * @returns a new Mesh
  34725. */
  34726. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  34727. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  34728. if (scene !== undefined) {
  34729. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  34730. updatable = scene;
  34731. }
  34732. scene = subdivisions;
  34733. subdivisions = 1;
  34734. }
  34735. var options = {
  34736. height: height,
  34737. diameterTop: diameterTop,
  34738. diameterBottom: diameterBottom,
  34739. tessellation: tessellation,
  34740. subdivisions: subdivisions,
  34741. sideOrientation: sideOrientation,
  34742. updatable: updatable
  34743. };
  34744. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  34745. };
  34746. // Torus (Code from SharpDX.org)
  34747. /**
  34748. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  34749. * @param name defines the name of the mesh to create
  34750. * @param diameter sets the diameter size (float) of the torus (default 1)
  34751. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  34752. * @param tessellation sets the number of torus sides (postive integer, default 16)
  34753. * @param scene defines the hosting scene
  34754. * @param updatable defines if the mesh must be flagged as updatable
  34755. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34756. * @returns a new Mesh
  34757. */
  34758. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  34759. var options = {
  34760. diameter: diameter,
  34761. thickness: thickness,
  34762. tessellation: tessellation,
  34763. sideOrientation: sideOrientation,
  34764. updatable: updatable
  34765. };
  34766. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  34767. };
  34768. /**
  34769. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  34770. * @param name defines the name of the mesh to create
  34771. * @param radius sets the global radius size (float) of the torus knot (default 2)
  34772. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  34773. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  34774. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  34775. * @param p the number of windings on X axis (positive integers, default 2)
  34776. * @param q the number of windings on Y axis (positive integers, default 3)
  34777. * @param scene defines the hosting scene
  34778. * @param updatable defines if the mesh must be flagged as updatable
  34779. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34780. * @returns a new Mesh
  34781. */
  34782. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  34783. var options = {
  34784. radius: radius,
  34785. tube: tube,
  34786. radialSegments: radialSegments,
  34787. tubularSegments: tubularSegments,
  34788. p: p,
  34789. q: q,
  34790. sideOrientation: sideOrientation,
  34791. updatable: updatable
  34792. };
  34793. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  34794. };
  34795. /**
  34796. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  34797. * @param name defines the name of the mesh to create
  34798. * @param points is an array successive Vector3
  34799. * @param scene defines the hosting scene
  34800. * @param updatable defines if the mesh must be flagged as updatable
  34801. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines).
  34802. * @returns a new Mesh
  34803. */
  34804. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  34805. if (scene === void 0) { scene = null; }
  34806. if (updatable === void 0) { updatable = false; }
  34807. if (instance === void 0) { instance = null; }
  34808. var options = {
  34809. points: points,
  34810. updatable: updatable,
  34811. instance: instance
  34812. };
  34813. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  34814. };
  34815. /**
  34816. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  34817. * @param name defines the name of the mesh to create
  34818. * @param points is an array successive Vector3
  34819. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  34820. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  34821. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  34822. * @param scene defines the hosting scene
  34823. * @param updatable defines if the mesh must be flagged as updatable
  34824. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines)
  34825. * @returns a new Mesh
  34826. */
  34827. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  34828. if (scene === void 0) { scene = null; }
  34829. var options = {
  34830. points: points,
  34831. dashSize: dashSize,
  34832. gapSize: gapSize,
  34833. dashNb: dashNb,
  34834. updatable: updatable,
  34835. instance: instance
  34836. };
  34837. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  34838. };
  34839. /**
  34840. * Creates a polygon mesh.
  34841. * Please consider using the same method from the MeshBuilder class instead.
  34842. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  34843. * 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.
  34844. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34845. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34846. * Remember you can only change the shape positions, not their number when updating a polygon.
  34847. */
  34848. /**
  34849. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  34850. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  34851. * @param name defines the name of the mesh to create
  34852. * @param shape is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors
  34853. * @param scene defines the hosting scene
  34854. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34855. * @param updatable defines if the mesh must be flagged as updatable
  34856. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34857. * @returns a new Mesh
  34858. */
  34859. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  34860. var options = {
  34861. shape: shape,
  34862. holes: holes,
  34863. updatable: updatable,
  34864. sideOrientation: sideOrientation
  34865. };
  34866. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  34867. };
  34868. /**
  34869. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  34870. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  34871. * @param name defines the name of the mesh to create
  34872. * @param shape is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors
  34873. * @param depth defines the height of extrusion
  34874. * @param scene defines the hosting scene
  34875. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34876. * @param updatable defines if the mesh must be flagged as updatable
  34877. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34878. * @returns a new Mesh
  34879. */
  34880. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  34881. var options = {
  34882. shape: shape,
  34883. holes: holes,
  34884. depth: depth,
  34885. updatable: updatable,
  34886. sideOrientation: sideOrientation
  34887. };
  34888. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  34889. };
  34890. /**
  34891. * Creates an extruded shape mesh.
  34892. * The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. Please consider using the same method from the MeshBuilder class instead
  34893. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34894. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34895. * @param name defines the name of the mesh to create
  34896. * @param shape is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis
  34897. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34898. * @param scale is the value to scale the shape
  34899. * @param rotation is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve
  34900. * @param cap sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  34901. * @param scene defines the hosting scene
  34902. * @param updatable defines if the mesh must be flagged as updatable
  34903. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34904. * @param instance is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#extruded-shape)
  34905. * @returns a new Mesh
  34906. */
  34907. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  34908. if (scene === void 0) { scene = null; }
  34909. var options = {
  34910. shape: shape,
  34911. path: path,
  34912. scale: scale,
  34913. rotation: rotation,
  34914. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34915. sideOrientation: sideOrientation,
  34916. instance: instance,
  34917. updatable: updatable
  34918. };
  34919. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  34920. };
  34921. /**
  34922. * Creates an custom extruded shape mesh.
  34923. * The custom extrusion is a parametric shape.
  34924. * It has no predefined shape. Its final shape will depend on the input parameters.
  34925. * Please consider using the same method from the MeshBuilder class instead
  34926. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34927. * @param name defines the name of the mesh to create
  34928. * @param shape is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis
  34929. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34930. * @param scaleFunction is a custom Javascript function called on each path point
  34931. * @param rotationFunction is a custom Javascript function called on each path point
  34932. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  34933. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  34934. * @param cap sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  34935. * @param scene defines the hosting scene
  34936. * @param updatable defines if the mesh must be flagged as updatable
  34937. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34938. * @param instance is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters (http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#extruded-shape)
  34939. * @returns a new Mesh
  34940. */
  34941. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34942. var options = {
  34943. shape: shape,
  34944. path: path,
  34945. scaleFunction: scaleFunction,
  34946. rotationFunction: rotationFunction,
  34947. ribbonCloseArray: ribbonCloseArray,
  34948. ribbonClosePath: ribbonClosePath,
  34949. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34950. sideOrientation: sideOrientation,
  34951. instance: instance,
  34952. updatable: updatable
  34953. };
  34954. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34955. };
  34956. /**
  34957. * Creates lathe mesh.
  34958. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34959. * Please consider using the same method from the MeshBuilder class instead
  34960. * @param name defines the name of the mesh to create
  34961. * @param shape is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  34962. * @param radius is the radius value of the lathe
  34963. * @param tessellation is the side number of the lathe.
  34964. * @param scene defines the hosting scene
  34965. * @param updatable defines if the mesh must be flagged as updatable
  34966. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34967. * @returns a new Mesh
  34968. */
  34969. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34970. var options = {
  34971. shape: shape,
  34972. radius: radius,
  34973. tessellation: tessellation,
  34974. sideOrientation: sideOrientation,
  34975. updatable: updatable
  34976. };
  34977. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34978. };
  34979. /**
  34980. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  34981. * @param name defines the name of the mesh to create
  34982. * @param size sets the size (float) of both sides of the plane at once (default 1)
  34983. * @param scene defines the hosting scene
  34984. * @param updatable defines if the mesh must be flagged as updatable
  34985. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34986. * @returns a new Mesh
  34987. */
  34988. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34989. var options = {
  34990. size: size,
  34991. width: size,
  34992. height: size,
  34993. sideOrientation: sideOrientation,
  34994. updatable: updatable
  34995. };
  34996. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34997. };
  34998. /**
  34999. * Creates a ground mesh.
  35000. * Please consider using the same method from the MeshBuilder class instead
  35001. * @param name defines the name of the mesh to create
  35002. * @param width set the width of the ground
  35003. * @param height set the height of the ground
  35004. * @param subdivisions sets the number of subdivisions per side
  35005. * @param scene defines the hosting scene
  35006. * @param updatable defines if the mesh must be flagged as updatable
  35007. * @returns a new Mesh
  35008. */
  35009. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  35010. var options = {
  35011. width: width,
  35012. height: height,
  35013. subdivisions: subdivisions,
  35014. updatable: updatable
  35015. };
  35016. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  35017. };
  35018. /**
  35019. * Creates a tiled ground mesh.
  35020. * Please consider using the same method from the MeshBuilder class instead
  35021. * @param name defines the name of the mesh to create
  35022. * @param xmin set the ground minimum X coordinate
  35023. * @param zmin set the ground minimum Y coordinate
  35024. * @param xmax set the ground maximum X coordinate
  35025. * @param zmax set the ground maximum Z coordinate
  35026. * @param subdivisions is an object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  35027. * @param precision is an object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  35028. * @param scene defines the hosting scene
  35029. * @param updatable defines if the mesh must be flagged as updatable
  35030. * @returns a new Mesh
  35031. */
  35032. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  35033. var options = {
  35034. xmin: xmin,
  35035. zmin: zmin,
  35036. xmax: xmax,
  35037. zmax: zmax,
  35038. subdivisions: subdivisions,
  35039. precision: precision,
  35040. updatable: updatable
  35041. };
  35042. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  35043. };
  35044. /**
  35045. * Creates a ground mesh from a height map.
  35046. * Please consider using the same method from the MeshBuilder class instead
  35047. * @see http://doc.babylonjs.com/babylon101/height_map
  35048. * @param name defines the name of the mesh to create
  35049. * @param url sets the URL of the height map image resource
  35050. * @param width set the ground width size
  35051. * @param height set the ground height size
  35052. * @param subdivisions sets the number of subdivision per side
  35053. * @param minHeight is the minimum altitude on the ground
  35054. * @param maxHeight is the maximum altitude on the ground
  35055. * @param scene defines the hosting scene
  35056. * @param updatable defines if the mesh must be flagged as updatable
  35057. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  35058. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  35059. * @returns a new Mesh
  35060. */
  35061. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  35062. var options = {
  35063. width: width,
  35064. height: height,
  35065. subdivisions: subdivisions,
  35066. minHeight: minHeight,
  35067. maxHeight: maxHeight,
  35068. updatable: updatable,
  35069. onReady: onReady,
  35070. alphaFilter: alphaFilter
  35071. };
  35072. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  35073. };
  35074. /**
  35075. * Creates a tube mesh.
  35076. * The tube is a parametric shape.
  35077. * It has no predefined shape. Its final shape will depend on the input parameters.
  35078. * Please consider using the same method from the MeshBuilder class instead
  35079. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  35080. * @param name defines the name of the mesh to create
  35081. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  35082. * @param radius sets the tube radius size
  35083. * @param tessellation is the number of sides on the tubular surface
  35084. * @param radiusFunction is a custom function. If it is not null, it overwrittes the parameter `radius`. This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path
  35085. * @param cap sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  35086. * @param scene defines the hosting scene
  35087. * @param updatable defines if the mesh must be flagged as updatable
  35088. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35089. * @param instance is an instance of an existing Tube object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#tube)
  35090. * @returns a new Mesh
  35091. */
  35092. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  35093. var options = {
  35094. path: path,
  35095. radius: radius,
  35096. tessellation: tessellation,
  35097. radiusFunction: radiusFunction,
  35098. arc: 1,
  35099. cap: cap,
  35100. updatable: updatable,
  35101. sideOrientation: sideOrientation,
  35102. instance: instance
  35103. };
  35104. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  35105. };
  35106. /**
  35107. * Creates a polyhedron mesh.
  35108. * Please consider using the same method from the MeshBuilder class instead.
  35109. * * 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
  35110. * * The parameter `size` (positive float, default 1) sets the polygon size
  35111. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  35112. * * 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`
  35113. * * 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
  35114. * * 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)`)
  35115. * * 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
  35116. * * 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
  35117. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35118. * * 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
  35119. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  35120. * @param name defines the name of the mesh to create
  35121. * @param options defines the options used to create the mesh
  35122. * @param scene defines the hosting scene
  35123. * @returns a new Mesh
  35124. */
  35125. Mesh.CreatePolyhedron = function (name, options, scene) {
  35126. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  35127. };
  35128. /**
  35129. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  35130. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  35131. * * 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`)
  35132. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  35133. * * 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
  35134. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35135. * * 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
  35136. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  35137. * @param name defines the name of the mesh
  35138. * @param options defines the options used to create the mesh
  35139. * @param scene defines the hosting scene
  35140. * @returns a new Mesh
  35141. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  35142. */
  35143. Mesh.CreateIcoSphere = function (name, options, scene) {
  35144. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  35145. };
  35146. /**
  35147. * Creates a decal mesh.
  35148. * Please consider using the same method from the MeshBuilder class instead.
  35149. * A decal is a mesh usually applied as a model onto the surface of another mesh
  35150. * @param name defines the name of the mesh
  35151. * @param sourceMesh defines the mesh receiving the decal
  35152. * @param position sets the position of the decal in world coordinates
  35153. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  35154. * @param size sets the decal scaling
  35155. * @param angle sets the angle to rotate the decal
  35156. * @returns a new Mesh
  35157. */
  35158. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  35159. var options = {
  35160. position: position,
  35161. normal: normal,
  35162. size: size,
  35163. angle: angle
  35164. };
  35165. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  35166. };
  35167. // Skeletons
  35168. /**
  35169. * Prepare internal position array for software CPU skinning
  35170. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  35171. */
  35172. Mesh.prototype.setPositionsForCPUSkinning = function () {
  35173. if (!this._sourcePositions) {
  35174. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35175. if (!source) {
  35176. return this._sourcePositions;
  35177. }
  35178. this._sourcePositions = new Float32Array(source);
  35179. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35180. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  35181. }
  35182. }
  35183. return this._sourcePositions;
  35184. };
  35185. /**
  35186. * Prepare internal normal array for software CPU skinning
  35187. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  35188. */
  35189. Mesh.prototype.setNormalsForCPUSkinning = function () {
  35190. if (!this._sourceNormals) {
  35191. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35192. if (!source) {
  35193. return this._sourceNormals;
  35194. }
  35195. this._sourceNormals = new Float32Array(source);
  35196. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35197. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  35198. }
  35199. }
  35200. return this._sourceNormals;
  35201. };
  35202. /**
  35203. * Updates the vertex buffer by applying transformation from the bones
  35204. * @param skeleton defines the skeleton to apply to current mesh
  35205. * @returns the current mesh
  35206. */
  35207. Mesh.prototype.applySkeleton = function (skeleton) {
  35208. if (!this.geometry) {
  35209. return this;
  35210. }
  35211. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  35212. return this;
  35213. }
  35214. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  35215. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35216. return this;
  35217. }
  35218. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35219. return this;
  35220. }
  35221. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35222. return this;
  35223. }
  35224. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35225. return this;
  35226. }
  35227. if (!this._sourcePositions) {
  35228. var submeshes = this.subMeshes.slice();
  35229. this.setPositionsForCPUSkinning();
  35230. this.subMeshes = submeshes;
  35231. }
  35232. if (!this._sourceNormals) {
  35233. this.setNormalsForCPUSkinning();
  35234. }
  35235. // positionsData checks for not being Float32Array will only pass at most once
  35236. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35237. if (!positionsData) {
  35238. return this;
  35239. }
  35240. if (!(positionsData instanceof Float32Array)) {
  35241. positionsData = new Float32Array(positionsData);
  35242. }
  35243. // normalsData checks for not being Float32Array will only pass at most once
  35244. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35245. if (!normalsData) {
  35246. return this;
  35247. }
  35248. if (!(normalsData instanceof Float32Array)) {
  35249. normalsData = new Float32Array(normalsData);
  35250. }
  35251. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35252. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  35253. if (!matricesWeightsData || !matricesIndicesData) {
  35254. return this;
  35255. }
  35256. var needExtras = this.numBoneInfluencers > 4;
  35257. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  35258. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  35259. var skeletonMatrices = skeleton.getTransformMatrices(this);
  35260. var tempVector3 = BABYLON.Vector3.Zero();
  35261. var finalMatrix = new BABYLON.Matrix();
  35262. var tempMatrix = new BABYLON.Matrix();
  35263. var matWeightIdx = 0;
  35264. var inf;
  35265. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  35266. var weight;
  35267. for (inf = 0; inf < 4; inf++) {
  35268. weight = matricesWeightsData[matWeightIdx + inf];
  35269. if (weight > 0) {
  35270. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35271. finalMatrix.addToSelf(tempMatrix);
  35272. }
  35273. }
  35274. if (needExtras) {
  35275. for (inf = 0; inf < 4; inf++) {
  35276. weight = matricesWeightsExtraData[matWeightIdx + inf];
  35277. if (weight > 0) {
  35278. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35279. finalMatrix.addToSelf(tempMatrix);
  35280. }
  35281. }
  35282. }
  35283. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  35284. tempVector3.toArray(positionsData, index);
  35285. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  35286. tempVector3.toArray(normalsData, index);
  35287. finalMatrix.reset();
  35288. }
  35289. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  35290. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  35291. return this;
  35292. };
  35293. // Tools
  35294. /**
  35295. * Returns an object containing a min and max Vector3 which are the minimum and maximum vectors of each mesh bounding box from the passed array, in the world coordinates
  35296. * @param meshes defines the list of meshes to scan
  35297. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  35298. */
  35299. Mesh.MinMax = function (meshes) {
  35300. var minVector = null;
  35301. var maxVector = null;
  35302. meshes.forEach(function (mesh, index, array) {
  35303. var boundingInfo = mesh.getBoundingInfo();
  35304. var boundingBox = boundingInfo.boundingBox;
  35305. if (!minVector || !maxVector) {
  35306. minVector = boundingBox.minimumWorld;
  35307. maxVector = boundingBox.maximumWorld;
  35308. }
  35309. else {
  35310. minVector.minimizeInPlace(boundingBox.minimumWorld);
  35311. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  35312. }
  35313. });
  35314. if (!minVector || !maxVector) {
  35315. return {
  35316. min: BABYLON.Vector3.Zero(),
  35317. max: BABYLON.Vector3.Zero()
  35318. };
  35319. }
  35320. return {
  35321. min: minVector,
  35322. max: maxVector
  35323. };
  35324. };
  35325. /**
  35326. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  35327. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  35328. * @returns a vector3
  35329. */
  35330. Mesh.Center = function (meshesOrMinMaxVector) {
  35331. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  35332. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  35333. };
  35334. /**
  35335. * Merge the array of meshes into a single mesh for performance reasons.
  35336. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  35337. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  35338. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  35339. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  35340. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  35341. * @returns a new mesh
  35342. */
  35343. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  35344. if (disposeSource === void 0) { disposeSource = true; }
  35345. var index;
  35346. if (!allow32BitsIndices) {
  35347. var totalVertices = 0;
  35348. // Counting vertices
  35349. for (index = 0; index < meshes.length; index++) {
  35350. if (meshes[index]) {
  35351. totalVertices += meshes[index].getTotalVertices();
  35352. if (totalVertices > 65536) {
  35353. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  35354. return null;
  35355. }
  35356. }
  35357. }
  35358. }
  35359. // Merge
  35360. var vertexData = null;
  35361. var otherVertexData;
  35362. var indiceArray = new Array();
  35363. var source = null;
  35364. for (index = 0; index < meshes.length; index++) {
  35365. if (meshes[index]) {
  35366. var wm = meshes[index].computeWorldMatrix(true);
  35367. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  35368. otherVertexData.transform(wm);
  35369. if (vertexData) {
  35370. vertexData.merge(otherVertexData, allow32BitsIndices);
  35371. }
  35372. else {
  35373. vertexData = otherVertexData;
  35374. source = meshes[index];
  35375. }
  35376. if (subdivideWithSubMeshes) {
  35377. indiceArray.push(meshes[index].getTotalIndices());
  35378. }
  35379. }
  35380. }
  35381. source = source;
  35382. if (!meshSubclass) {
  35383. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  35384. }
  35385. vertexData.applyToMesh(meshSubclass);
  35386. // Setting properties
  35387. meshSubclass.material = source.material;
  35388. meshSubclass.checkCollisions = source.checkCollisions;
  35389. // Cleaning
  35390. if (disposeSource) {
  35391. for (index = 0; index < meshes.length; index++) {
  35392. if (meshes[index]) {
  35393. meshes[index].dispose();
  35394. }
  35395. }
  35396. }
  35397. // Subdivide
  35398. if (subdivideWithSubMeshes) {
  35399. //-- removal of global submesh
  35400. meshSubclass.releaseSubMeshes();
  35401. index = 0;
  35402. var offset = 0;
  35403. //-- apply subdivision according to index table
  35404. while (index < indiceArray.length) {
  35405. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  35406. offset += indiceArray[index];
  35407. index++;
  35408. }
  35409. }
  35410. return meshSubclass;
  35411. };
  35412. // Consts
  35413. /**
  35414. * Mesh side orientation : usually the external or front surface
  35415. */
  35416. Mesh.FRONTSIDE = 0;
  35417. /**
  35418. * Mesh side orientation : usually the internal or back surface
  35419. */
  35420. Mesh.BACKSIDE = 1;
  35421. /**
  35422. * Mesh side orientation : both internal and external or front and back surfaces
  35423. */
  35424. Mesh.DOUBLESIDE = 2;
  35425. /**
  35426. * Mesh side orientation : by default, `FRONTSIDE`
  35427. */
  35428. Mesh.DEFAULTSIDE = 0;
  35429. /**
  35430. * Mesh cap setting : no cap
  35431. */
  35432. Mesh.NO_CAP = 0;
  35433. /**
  35434. * Mesh cap setting : one cap at the beginning of the mesh
  35435. */
  35436. Mesh.CAP_START = 1;
  35437. /**
  35438. * Mesh cap setting : one cap at the end of the mesh
  35439. */
  35440. Mesh.CAP_END = 2;
  35441. /**
  35442. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  35443. */
  35444. Mesh.CAP_ALL = 3;
  35445. return Mesh;
  35446. }(BABYLON.AbstractMesh));
  35447. BABYLON.Mesh = Mesh;
  35448. })(BABYLON || (BABYLON = {}));
  35449. //# sourceMappingURL=babylon.mesh.js.map
  35450. var BABYLON;
  35451. (function (BABYLON) {
  35452. /**
  35453. * Base class for submeshes
  35454. */
  35455. var BaseSubMesh = /** @class */ (function () {
  35456. function BaseSubMesh() {
  35457. }
  35458. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  35459. /**
  35460. * Gets associated effect
  35461. */
  35462. get: function () {
  35463. return this._materialEffect;
  35464. },
  35465. enumerable: true,
  35466. configurable: true
  35467. });
  35468. /**
  35469. * Sets associated effect (effect used to render this submesh)
  35470. * @param effect defines the effect to associate with
  35471. * @param defines defines the set of defines used to compile this effect
  35472. */
  35473. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  35474. if (defines === void 0) { defines = null; }
  35475. if (this._materialEffect === effect) {
  35476. if (!effect) {
  35477. this._materialDefines = null;
  35478. }
  35479. return;
  35480. }
  35481. this._materialDefines = defines;
  35482. this._materialEffect = effect;
  35483. };
  35484. return BaseSubMesh;
  35485. }());
  35486. BABYLON.BaseSubMesh = BaseSubMesh;
  35487. /**
  35488. * Defines a subdivision inside a mesh
  35489. */
  35490. var SubMesh = /** @class */ (function (_super) {
  35491. __extends(SubMesh, _super);
  35492. /**
  35493. * Creates a new submesh
  35494. * @param materialIndex defines the material index to use
  35495. * @param verticesStart defines vertex index start
  35496. * @param verticesCount defines vertices count
  35497. * @param indexStart defines index start
  35498. * @param indexCount defines indices count
  35499. * @param mesh defines the parent mesh
  35500. * @param renderingMesh defines an optional rendering mesh
  35501. * @param createBoundingBox defines if bounding box should be created for this submesh
  35502. */
  35503. function SubMesh(
  35504. /** the material index to use */
  35505. materialIndex,
  35506. /** vertex index start */
  35507. verticesStart,
  35508. /** vertices count */
  35509. verticesCount,
  35510. /** index start */
  35511. indexStart,
  35512. /** indices count */
  35513. indexCount, mesh, renderingMesh, createBoundingBox) {
  35514. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35515. var _this = _super.call(this) || this;
  35516. _this.materialIndex = materialIndex;
  35517. _this.verticesStart = verticesStart;
  35518. _this.verticesCount = verticesCount;
  35519. _this.indexStart = indexStart;
  35520. _this.indexCount = indexCount;
  35521. /** @hidden */
  35522. _this._renderId = 0;
  35523. _this._mesh = mesh;
  35524. _this._renderingMesh = renderingMesh || mesh;
  35525. mesh.subMeshes.push(_this);
  35526. _this._trianglePlanes = [];
  35527. _this._id = mesh.subMeshes.length - 1;
  35528. if (createBoundingBox) {
  35529. _this.refreshBoundingInfo();
  35530. mesh.computeWorldMatrix(true);
  35531. }
  35532. return _this;
  35533. }
  35534. /**
  35535. * Add a new submesh to a mesh
  35536. * @param materialIndex defines the material index to use
  35537. * @param verticesStart defines vertex index start
  35538. * @param verticesCount defines vertices count
  35539. * @param indexStart defines index start
  35540. * @param indexCount defines indices count
  35541. * @param mesh defines the parent mesh
  35542. * @param renderingMesh defines an optional rendering mesh
  35543. * @param createBoundingBox defines if bounding box should be created for this submesh
  35544. * @returns the new submesh
  35545. */
  35546. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  35547. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35548. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  35549. };
  35550. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  35551. /**
  35552. * Returns true if this submesh covers the entire parent mesh
  35553. * @ignorenaming
  35554. */
  35555. get: function () {
  35556. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  35557. },
  35558. enumerable: true,
  35559. configurable: true
  35560. });
  35561. /**
  35562. * Returns the submesh BoudingInfo object
  35563. * @returns current bounding info (or mesh's one if the submesh is global)
  35564. */
  35565. SubMesh.prototype.getBoundingInfo = function () {
  35566. if (this.IsGlobal) {
  35567. return this._mesh.getBoundingInfo();
  35568. }
  35569. return this._boundingInfo;
  35570. };
  35571. /**
  35572. * Sets the submesh BoundingInfo
  35573. * @param boundingInfo defines the new bounding info to use
  35574. * @returns the SubMesh
  35575. */
  35576. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  35577. this._boundingInfo = boundingInfo;
  35578. return this;
  35579. };
  35580. /**
  35581. * Returns the mesh of the current submesh
  35582. * @return the parent mesh
  35583. */
  35584. SubMesh.prototype.getMesh = function () {
  35585. return this._mesh;
  35586. };
  35587. /**
  35588. * Returns the rendering mesh of the submesh
  35589. * @returns the rendering mesh (could be different from parent mesh)
  35590. */
  35591. SubMesh.prototype.getRenderingMesh = function () {
  35592. return this._renderingMesh;
  35593. };
  35594. /**
  35595. * Returns the submesh material
  35596. * @returns null or the current material
  35597. */
  35598. SubMesh.prototype.getMaterial = function () {
  35599. var rootMaterial = this._renderingMesh.material;
  35600. if (rootMaterial === null || rootMaterial === undefined) {
  35601. return this._mesh.getScene().defaultMaterial;
  35602. }
  35603. else if (rootMaterial.getSubMaterial) {
  35604. var multiMaterial = rootMaterial;
  35605. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  35606. if (this._currentMaterial !== effectiveMaterial) {
  35607. this._currentMaterial = effectiveMaterial;
  35608. this._materialDefines = null;
  35609. }
  35610. return effectiveMaterial;
  35611. }
  35612. return rootMaterial;
  35613. };
  35614. // Methods
  35615. /**
  35616. * Sets a new updated BoundingInfo object to the submesh
  35617. * @returns the SubMesh
  35618. */
  35619. SubMesh.prototype.refreshBoundingInfo = function () {
  35620. this._lastColliderWorldVertices = null;
  35621. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  35622. return this;
  35623. }
  35624. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35625. if (!data) {
  35626. this._boundingInfo = this._mesh.getBoundingInfo();
  35627. return this;
  35628. }
  35629. var indices = this._renderingMesh.getIndices();
  35630. var extend;
  35631. //is this the only submesh?
  35632. if (this.indexStart === 0 && this.indexCount === indices.length) {
  35633. var boundingInfo = this._renderingMesh.getBoundingInfo();
  35634. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  35635. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  35636. }
  35637. else {
  35638. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  35639. }
  35640. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  35641. return this;
  35642. };
  35643. /** @hidden */
  35644. SubMesh.prototype._checkCollision = function (collider) {
  35645. var boundingInfo = this.getBoundingInfo();
  35646. return boundingInfo._checkCollision(collider);
  35647. };
  35648. /**
  35649. * Updates the submesh BoundingInfo
  35650. * @param world defines the world matrix to use to update the bounding info
  35651. * @returns the submesh
  35652. */
  35653. SubMesh.prototype.updateBoundingInfo = function (world) {
  35654. var boundingInfo = this.getBoundingInfo();
  35655. if (!boundingInfo) {
  35656. this.refreshBoundingInfo();
  35657. boundingInfo = this.getBoundingInfo();
  35658. }
  35659. boundingInfo.update(world);
  35660. return this;
  35661. };
  35662. /**
  35663. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  35664. * @param frustumPlanes defines the frustum planes
  35665. * @returns true if the submesh is intersecting with the frustum
  35666. */
  35667. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  35668. var boundingInfo = this.getBoundingInfo();
  35669. if (!boundingInfo) {
  35670. return false;
  35671. }
  35672. return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy);
  35673. };
  35674. /**
  35675. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
  35676. * @param frustumPlanes defines the frustum planes
  35677. * @returns true if the submesh is inside the frustum
  35678. */
  35679. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  35680. var boundingInfo = this.getBoundingInfo();
  35681. if (!boundingInfo) {
  35682. return false;
  35683. }
  35684. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  35685. };
  35686. /**
  35687. * Renders the submesh
  35688. * @param enableAlphaMode defines if alpha needs to be used
  35689. * @returns the submesh
  35690. */
  35691. SubMesh.prototype.render = function (enableAlphaMode) {
  35692. this._renderingMesh.render(this, enableAlphaMode);
  35693. return this;
  35694. };
  35695. /**
  35696. * @hidden
  35697. */
  35698. SubMesh.prototype._getLinesIndexBuffer = function (indices, engine) {
  35699. if (!this._linesIndexBuffer) {
  35700. var linesIndices = [];
  35701. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35702. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  35703. }
  35704. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  35705. this._linesIndexCount = linesIndices.length;
  35706. }
  35707. return this._linesIndexBuffer;
  35708. };
  35709. /**
  35710. * Checks if the submesh intersects with a ray
  35711. * @param ray defines the ray to test
  35712. * @returns true is the passed ray intersects the submesh bounding box
  35713. */
  35714. SubMesh.prototype.canIntersects = function (ray) {
  35715. var boundingInfo = this.getBoundingInfo();
  35716. if (!boundingInfo) {
  35717. return false;
  35718. }
  35719. return ray.intersectsBox(boundingInfo.boundingBox);
  35720. };
  35721. /**
  35722. * Intersects current submesh with a ray
  35723. * @param ray defines the ray to test
  35724. * @param positions defines mesh's positions array
  35725. * @param indices defines mesh's indices array
  35726. * @param fastCheck defines if only bounding info should be used
  35727. * @returns intersection info or null if no intersection
  35728. */
  35729. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  35730. var material = this.getMaterial();
  35731. if (!material) {
  35732. return null;
  35733. }
  35734. switch (material.fillMode) {
  35735. case BABYLON.Material.PointListDrawMode:
  35736. case BABYLON.Material.LineListDrawMode:
  35737. case BABYLON.Material.LineLoopDrawMode:
  35738. case BABYLON.Material.LineStripDrawMode:
  35739. case BABYLON.Material.TriangleFanDrawMode:
  35740. case BABYLON.Material.TriangleStripDrawMode:
  35741. return null;
  35742. }
  35743. // LineMesh first as it's also a Mesh...
  35744. if (BABYLON.LinesMesh) {
  35745. var mesh = this._mesh instanceof BABYLON.InstancedMesh ? this._mesh.sourceMesh : this._mesh;
  35746. if (mesh instanceof BABYLON.LinesMesh) {
  35747. var linesMesh = mesh;
  35748. return this._intersectLines(ray, positions, indices, linesMesh.intersectionThreshold, fastCheck);
  35749. }
  35750. }
  35751. return this._intersectTriangles(ray, positions, indices, fastCheck);
  35752. };
  35753. /** @hidden */
  35754. SubMesh.prototype._intersectLines = function (ray, positions, indices, intersectionThreshold, fastCheck) {
  35755. var intersectInfo = null;
  35756. // Line test
  35757. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  35758. var p0 = positions[indices[index]];
  35759. var p1 = positions[indices[index + 1]];
  35760. var length = ray.intersectionSegment(p0, p1, intersectionThreshold);
  35761. if (length < 0) {
  35762. continue;
  35763. }
  35764. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  35765. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  35766. if (fastCheck) {
  35767. break;
  35768. }
  35769. }
  35770. }
  35771. return intersectInfo;
  35772. };
  35773. /** @hidden */
  35774. SubMesh.prototype._intersectTriangles = function (ray, positions, indices, fastCheck) {
  35775. var intersectInfo = null;
  35776. // Triangles test
  35777. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35778. var p0 = positions[indices[index]];
  35779. var p1 = positions[indices[index + 1]];
  35780. var p2 = positions[indices[index + 2]];
  35781. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  35782. if (currentIntersectInfo) {
  35783. if (currentIntersectInfo.distance < 0) {
  35784. continue;
  35785. }
  35786. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  35787. intersectInfo = currentIntersectInfo;
  35788. intersectInfo.faceId = index / 3;
  35789. if (fastCheck) {
  35790. break;
  35791. }
  35792. }
  35793. }
  35794. }
  35795. return intersectInfo;
  35796. };
  35797. /** @hidden */
  35798. SubMesh.prototype._rebuild = function () {
  35799. if (this._linesIndexBuffer) {
  35800. this._linesIndexBuffer = null;
  35801. }
  35802. };
  35803. // Clone
  35804. /**
  35805. * Creates a new submesh from the passed mesh
  35806. * @param newMesh defines the new hosting mesh
  35807. * @param newRenderingMesh defines an optional rendering mesh
  35808. * @returns the new submesh
  35809. */
  35810. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  35811. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  35812. if (!this.IsGlobal) {
  35813. var boundingInfo = this.getBoundingInfo();
  35814. if (!boundingInfo) {
  35815. return result;
  35816. }
  35817. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  35818. }
  35819. return result;
  35820. };
  35821. // Dispose
  35822. /**
  35823. * Release associated resources
  35824. */
  35825. SubMesh.prototype.dispose = function () {
  35826. if (this._linesIndexBuffer) {
  35827. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  35828. this._linesIndexBuffer = null;
  35829. }
  35830. // Remove from mesh
  35831. var index = this._mesh.subMeshes.indexOf(this);
  35832. this._mesh.subMeshes.splice(index, 1);
  35833. };
  35834. // Statics
  35835. /**
  35836. * Creates a new submesh from indices data
  35837. * @param materialIndex the index of the main mesh material
  35838. * @param startIndex the index where to start the copy in the mesh indices array
  35839. * @param indexCount the number of indices to copy then from the startIndex
  35840. * @param mesh the main mesh to create the submesh from
  35841. * @param renderingMesh the optional rendering mesh
  35842. * @returns a new submesh
  35843. */
  35844. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  35845. var minVertexIndex = Number.MAX_VALUE;
  35846. var maxVertexIndex = -Number.MAX_VALUE;
  35847. renderingMesh = (renderingMesh || mesh);
  35848. var indices = renderingMesh.getIndices();
  35849. for (var index = startIndex; index < startIndex + indexCount; index++) {
  35850. var vertexIndex = indices[index];
  35851. if (vertexIndex < minVertexIndex) {
  35852. minVertexIndex = vertexIndex;
  35853. }
  35854. if (vertexIndex > maxVertexIndex) {
  35855. maxVertexIndex = vertexIndex;
  35856. }
  35857. }
  35858. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  35859. };
  35860. return SubMesh;
  35861. }(BaseSubMesh));
  35862. BABYLON.SubMesh = SubMesh;
  35863. })(BABYLON || (BABYLON = {}));
  35864. //# sourceMappingURL=babylon.subMesh.js.map
  35865. var __assign = (this && this.__assign) || function () {
  35866. __assign = Object.assign || function(t) {
  35867. for (var s, i = 1, n = arguments.length; i < n; i++) {
  35868. s = arguments[i];
  35869. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  35870. t[p] = s[p];
  35871. }
  35872. return t;
  35873. };
  35874. return __assign.apply(this, arguments);
  35875. };
  35876. var BABYLON;
  35877. (function (BABYLON) {
  35878. /**
  35879. * Manages the defines for the Material
  35880. */
  35881. var MaterialDefines = /** @class */ (function () {
  35882. function MaterialDefines() {
  35883. this._isDirty = true;
  35884. /** @hidden */
  35885. this._areLightsDirty = true;
  35886. /** @hidden */
  35887. this._areAttributesDirty = true;
  35888. /** @hidden */
  35889. this._areTexturesDirty = true;
  35890. /** @hidden */
  35891. this._areFresnelDirty = true;
  35892. /** @hidden */
  35893. this._areMiscDirty = true;
  35894. /** @hidden */
  35895. this._areImageProcessingDirty = true;
  35896. /** @hidden */
  35897. this._normals = false;
  35898. /** @hidden */
  35899. this._uvs = false;
  35900. /** @hidden */
  35901. this._needNormals = false;
  35902. /** @hidden */
  35903. this._needUVs = false;
  35904. }
  35905. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  35906. /**
  35907. * Specifies if the material needs to be re-calculated
  35908. */
  35909. get: function () {
  35910. return this._isDirty;
  35911. },
  35912. enumerable: true,
  35913. configurable: true
  35914. });
  35915. /**
  35916. * Marks the material to indicate that it has been re-calculated
  35917. */
  35918. MaterialDefines.prototype.markAsProcessed = function () {
  35919. this._isDirty = false;
  35920. this._areAttributesDirty = false;
  35921. this._areTexturesDirty = false;
  35922. this._areFresnelDirty = false;
  35923. this._areLightsDirty = false;
  35924. this._areMiscDirty = false;
  35925. this._areImageProcessingDirty = false;
  35926. };
  35927. /**
  35928. * Marks the material to indicate that it needs to be re-calculated
  35929. */
  35930. MaterialDefines.prototype.markAsUnprocessed = function () {
  35931. this._isDirty = true;
  35932. };
  35933. /**
  35934. * Marks the material to indicate all of its defines need to be re-calculated
  35935. */
  35936. MaterialDefines.prototype.markAllAsDirty = function () {
  35937. this._areTexturesDirty = true;
  35938. this._areAttributesDirty = true;
  35939. this._areLightsDirty = true;
  35940. this._areFresnelDirty = true;
  35941. this._areMiscDirty = true;
  35942. this._areImageProcessingDirty = true;
  35943. this._isDirty = true;
  35944. };
  35945. /**
  35946. * Marks the material to indicate that image processing needs to be re-calculated
  35947. */
  35948. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  35949. this._areImageProcessingDirty = true;
  35950. this._isDirty = true;
  35951. };
  35952. /**
  35953. * Marks the material to indicate the lights need to be re-calculated
  35954. */
  35955. MaterialDefines.prototype.markAsLightDirty = function () {
  35956. this._areLightsDirty = true;
  35957. this._isDirty = true;
  35958. };
  35959. /**
  35960. * Marks the attribute state as changed
  35961. */
  35962. MaterialDefines.prototype.markAsAttributesDirty = function () {
  35963. this._areAttributesDirty = true;
  35964. this._isDirty = true;
  35965. };
  35966. /**
  35967. * Marks the texture state as changed
  35968. */
  35969. MaterialDefines.prototype.markAsTexturesDirty = function () {
  35970. this._areTexturesDirty = true;
  35971. this._isDirty = true;
  35972. };
  35973. /**
  35974. * Marks the fresnel state as changed
  35975. */
  35976. MaterialDefines.prototype.markAsFresnelDirty = function () {
  35977. this._areFresnelDirty = true;
  35978. this._isDirty = true;
  35979. };
  35980. /**
  35981. * Marks the misc state as changed
  35982. */
  35983. MaterialDefines.prototype.markAsMiscDirty = function () {
  35984. this._areMiscDirty = true;
  35985. this._isDirty = true;
  35986. };
  35987. /**
  35988. * Rebuilds the material defines
  35989. */
  35990. MaterialDefines.prototype.rebuild = function () {
  35991. if (this._keys) {
  35992. delete this._keys;
  35993. }
  35994. this._keys = [];
  35995. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  35996. var key = _a[_i];
  35997. if (key[0] === "_") {
  35998. continue;
  35999. }
  36000. this._keys.push(key);
  36001. }
  36002. };
  36003. /**
  36004. * Specifies if two material defines are equal
  36005. * @param other - A material define instance to compare to
  36006. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  36007. */
  36008. MaterialDefines.prototype.isEqual = function (other) {
  36009. if (this._keys.length !== other._keys.length) {
  36010. return false;
  36011. }
  36012. for (var index = 0; index < this._keys.length; index++) {
  36013. var prop = this._keys[index];
  36014. if (this[prop] !== other[prop]) {
  36015. return false;
  36016. }
  36017. }
  36018. return true;
  36019. };
  36020. /**
  36021. * Clones this instance's defines to another instance
  36022. * @param other - material defines to clone values to
  36023. */
  36024. MaterialDefines.prototype.cloneTo = function (other) {
  36025. if (this._keys.length !== other._keys.length) {
  36026. other._keys = this._keys.slice(0);
  36027. }
  36028. for (var index = 0; index < this._keys.length; index++) {
  36029. var prop = this._keys[index];
  36030. other[prop] = this[prop];
  36031. }
  36032. };
  36033. /**
  36034. * Resets the material define values
  36035. */
  36036. MaterialDefines.prototype.reset = function () {
  36037. for (var index = 0; index < this._keys.length; index++) {
  36038. var prop = this._keys[index];
  36039. var type = typeof this[prop];
  36040. switch (type) {
  36041. case "number":
  36042. this[prop] = 0;
  36043. break;
  36044. case "string":
  36045. this[prop] = "";
  36046. break;
  36047. default:
  36048. this[prop] = false;
  36049. break;
  36050. }
  36051. }
  36052. };
  36053. /**
  36054. * Converts the material define values to a string
  36055. * @returns - String of material define information
  36056. */
  36057. MaterialDefines.prototype.toString = function () {
  36058. var result = "";
  36059. for (var index = 0; index < this._keys.length; index++) {
  36060. var prop = this._keys[index];
  36061. var value = this[prop];
  36062. var type = typeof value;
  36063. switch (type) {
  36064. case "number":
  36065. case "string":
  36066. result += "#define " + prop + " " + value + "\n";
  36067. break;
  36068. default:
  36069. if (value) {
  36070. result += "#define " + prop + "\n";
  36071. }
  36072. break;
  36073. }
  36074. }
  36075. return result;
  36076. };
  36077. return MaterialDefines;
  36078. }());
  36079. BABYLON.MaterialDefines = MaterialDefines;
  36080. /**
  36081. * Base class for the main features of a material in Babylon.js
  36082. */
  36083. var Material = /** @class */ (function () {
  36084. /**
  36085. * Creates a material instance
  36086. * @param name defines the name of the material
  36087. * @param scene defines the scene to reference
  36088. * @param doNotAdd specifies if the material should be added to the scene
  36089. */
  36090. function Material(name, scene, doNotAdd) {
  36091. /**
  36092. * Specifies if the ready state should be checked on each call
  36093. */
  36094. this.checkReadyOnEveryCall = false;
  36095. /**
  36096. * Specifies if the ready state should be checked once
  36097. */
  36098. this.checkReadyOnlyOnce = false;
  36099. /**
  36100. * The state of the material
  36101. */
  36102. this.state = "";
  36103. /**
  36104. * The alpha value of the material
  36105. */
  36106. this._alpha = 1.0;
  36107. /**
  36108. * Specifies if back face culling is enabled
  36109. */
  36110. this._backFaceCulling = true;
  36111. /**
  36112. * Specifies if the material should be serialized
  36113. */
  36114. this.doNotSerialize = false;
  36115. /**
  36116. * Specifies if the effect should be stored on sub meshes
  36117. */
  36118. this.storeEffectOnSubMeshes = false;
  36119. /**
  36120. * An event triggered when the material is disposed
  36121. */
  36122. this.onDisposeObservable = new BABYLON.Observable();
  36123. /**
  36124. * Stores the value of the alpha mode
  36125. */
  36126. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  36127. /**
  36128. * Stores the state of the need depth pre-pass value
  36129. */
  36130. this._needDepthPrePass = false;
  36131. /**
  36132. * Specifies if depth writing should be disabled
  36133. */
  36134. this.disableDepthWrite = false;
  36135. /**
  36136. * Specifies if depth writing should be forced
  36137. */
  36138. this.forceDepthWrite = false;
  36139. /**
  36140. * Specifies if there should be a separate pass for culling
  36141. */
  36142. this.separateCullingPass = false;
  36143. /**
  36144. * Stores the state specifing if fog should be enabled
  36145. */
  36146. this._fogEnabled = true;
  36147. /**
  36148. * Stores the size of points
  36149. */
  36150. this.pointSize = 1.0;
  36151. /**
  36152. * Stores the z offset value
  36153. */
  36154. this.zOffset = 0;
  36155. /**
  36156. * @hidden
  36157. * Specifies if the material was previously ready
  36158. */
  36159. this._wasPreviouslyReady = false;
  36160. /**
  36161. * Stores the fill mode state
  36162. */
  36163. this._fillMode = Material.TriangleFillMode;
  36164. this.name = name;
  36165. this.id = name || BABYLON.Tools.RandomId();
  36166. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  36167. this.uniqueId = this._scene.getUniqueId();
  36168. if (this._scene.useRightHandedSystem) {
  36169. this.sideOrientation = Material.ClockWiseSideOrientation;
  36170. }
  36171. else {
  36172. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  36173. }
  36174. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  36175. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  36176. if (!doNotAdd) {
  36177. this._scene.materials.push(this);
  36178. this._scene.onNewMaterialAddedObservable.notifyObservers(this);
  36179. }
  36180. }
  36181. Object.defineProperty(Material, "TriangleFillMode", {
  36182. /**
  36183. * Returns the triangle fill mode
  36184. */
  36185. get: function () {
  36186. return Material._TriangleFillMode;
  36187. },
  36188. enumerable: true,
  36189. configurable: true
  36190. });
  36191. Object.defineProperty(Material, "WireFrameFillMode", {
  36192. /**
  36193. * Returns the wireframe mode
  36194. */
  36195. get: function () {
  36196. return Material._WireFrameFillMode;
  36197. },
  36198. enumerable: true,
  36199. configurable: true
  36200. });
  36201. Object.defineProperty(Material, "PointFillMode", {
  36202. /**
  36203. * Returns the point fill mode
  36204. */
  36205. get: function () {
  36206. return Material._PointFillMode;
  36207. },
  36208. enumerable: true,
  36209. configurable: true
  36210. });
  36211. Object.defineProperty(Material, "PointListDrawMode", {
  36212. /**
  36213. * Returns the point list draw mode
  36214. */
  36215. get: function () {
  36216. return Material._PointListDrawMode;
  36217. },
  36218. enumerable: true,
  36219. configurable: true
  36220. });
  36221. Object.defineProperty(Material, "LineListDrawMode", {
  36222. /**
  36223. * Returns the line list draw mode
  36224. */
  36225. get: function () {
  36226. return Material._LineListDrawMode;
  36227. },
  36228. enumerable: true,
  36229. configurable: true
  36230. });
  36231. Object.defineProperty(Material, "LineLoopDrawMode", {
  36232. /**
  36233. * Returns the line loop draw mode
  36234. */
  36235. get: function () {
  36236. return Material._LineLoopDrawMode;
  36237. },
  36238. enumerable: true,
  36239. configurable: true
  36240. });
  36241. Object.defineProperty(Material, "LineStripDrawMode", {
  36242. /**
  36243. * Returns the line strip draw mode
  36244. */
  36245. get: function () {
  36246. return Material._LineStripDrawMode;
  36247. },
  36248. enumerable: true,
  36249. configurable: true
  36250. });
  36251. Object.defineProperty(Material, "TriangleStripDrawMode", {
  36252. /**
  36253. * Returns the triangle strip draw mode
  36254. */
  36255. get: function () {
  36256. return Material._TriangleStripDrawMode;
  36257. },
  36258. enumerable: true,
  36259. configurable: true
  36260. });
  36261. Object.defineProperty(Material, "TriangleFanDrawMode", {
  36262. /**
  36263. * Returns the triangle fan draw mode
  36264. */
  36265. get: function () {
  36266. return Material._TriangleFanDrawMode;
  36267. },
  36268. enumerable: true,
  36269. configurable: true
  36270. });
  36271. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  36272. /**
  36273. * Returns the clock-wise side orientation
  36274. */
  36275. get: function () {
  36276. return Material._ClockWiseSideOrientation;
  36277. },
  36278. enumerable: true,
  36279. configurable: true
  36280. });
  36281. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  36282. /**
  36283. * Returns the counter clock-wise side orientation
  36284. */
  36285. get: function () {
  36286. return Material._CounterClockWiseSideOrientation;
  36287. },
  36288. enumerable: true,
  36289. configurable: true
  36290. });
  36291. Object.defineProperty(Material.prototype, "alpha", {
  36292. /**
  36293. * Gets the alpha value of the material
  36294. */
  36295. get: function () {
  36296. return this._alpha;
  36297. },
  36298. /**
  36299. * Sets the alpha value of the material
  36300. */
  36301. set: function (value) {
  36302. if (this._alpha === value) {
  36303. return;
  36304. }
  36305. this._alpha = value;
  36306. this.markAsDirty(Material.MiscDirtyFlag);
  36307. },
  36308. enumerable: true,
  36309. configurable: true
  36310. });
  36311. Object.defineProperty(Material.prototype, "backFaceCulling", {
  36312. /**
  36313. * Gets the back-face culling state
  36314. */
  36315. get: function () {
  36316. return this._backFaceCulling;
  36317. },
  36318. /**
  36319. * Sets the back-face culling state
  36320. */
  36321. set: function (value) {
  36322. if (this._backFaceCulling === value) {
  36323. return;
  36324. }
  36325. this._backFaceCulling = value;
  36326. this.markAsDirty(Material.TextureDirtyFlag);
  36327. },
  36328. enumerable: true,
  36329. configurable: true
  36330. });
  36331. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  36332. /**
  36333. * Gets a boolean indicating that current material needs to register RTT
  36334. */
  36335. get: function () {
  36336. return false;
  36337. },
  36338. enumerable: true,
  36339. configurable: true
  36340. });
  36341. Object.defineProperty(Material.prototype, "onDispose", {
  36342. /**
  36343. * Called during a dispose event
  36344. */
  36345. set: function (callback) {
  36346. if (this._onDisposeObserver) {
  36347. this.onDisposeObservable.remove(this._onDisposeObserver);
  36348. }
  36349. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  36350. },
  36351. enumerable: true,
  36352. configurable: true
  36353. });
  36354. Object.defineProperty(Material.prototype, "onBindObservable", {
  36355. /**
  36356. * An event triggered when the material is bound
  36357. */
  36358. get: function () {
  36359. if (!this._onBindObservable) {
  36360. this._onBindObservable = new BABYLON.Observable();
  36361. }
  36362. return this._onBindObservable;
  36363. },
  36364. enumerable: true,
  36365. configurable: true
  36366. });
  36367. Object.defineProperty(Material.prototype, "onBind", {
  36368. /**
  36369. * Called during a bind event
  36370. */
  36371. set: function (callback) {
  36372. if (this._onBindObserver) {
  36373. this.onBindObservable.remove(this._onBindObserver);
  36374. }
  36375. this._onBindObserver = this.onBindObservable.add(callback);
  36376. },
  36377. enumerable: true,
  36378. configurable: true
  36379. });
  36380. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  36381. /**
  36382. * An event triggered when the material is unbound
  36383. */
  36384. get: function () {
  36385. if (!this._onUnBindObservable) {
  36386. this._onUnBindObservable = new BABYLON.Observable();
  36387. }
  36388. return this._onUnBindObservable;
  36389. },
  36390. enumerable: true,
  36391. configurable: true
  36392. });
  36393. Object.defineProperty(Material.prototype, "alphaMode", {
  36394. /**
  36395. * Gets the value of the alpha mode
  36396. */
  36397. get: function () {
  36398. return this._alphaMode;
  36399. },
  36400. /**
  36401. * Sets the value of the alpha mode.
  36402. *
  36403. * | Value | Type | Description |
  36404. * | --- | --- | --- |
  36405. * | 0 | ALPHA_DISABLE | |
  36406. * | 1 | ALPHA_ADD | |
  36407. * | 2 | ALPHA_COMBINE | |
  36408. * | 3 | ALPHA_SUBTRACT | |
  36409. * | 4 | ALPHA_MULTIPLY | |
  36410. * | 5 | ALPHA_MAXIMIZED | |
  36411. * | 6 | ALPHA_ONEONE | |
  36412. * | 7 | ALPHA_PREMULTIPLIED | |
  36413. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  36414. * | 9 | ALPHA_INTERPOLATE | |
  36415. * | 10 | ALPHA_SCREENMODE | |
  36416. *
  36417. */
  36418. set: function (value) {
  36419. if (this._alphaMode === value) {
  36420. return;
  36421. }
  36422. this._alphaMode = value;
  36423. this.markAsDirty(Material.TextureDirtyFlag);
  36424. },
  36425. enumerable: true,
  36426. configurable: true
  36427. });
  36428. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  36429. /**
  36430. * Gets the depth pre-pass value
  36431. */
  36432. get: function () {
  36433. return this._needDepthPrePass;
  36434. },
  36435. /**
  36436. * Sets the need depth pre-pass value
  36437. */
  36438. set: function (value) {
  36439. if (this._needDepthPrePass === value) {
  36440. return;
  36441. }
  36442. this._needDepthPrePass = value;
  36443. if (this._needDepthPrePass) {
  36444. this.checkReadyOnEveryCall = true;
  36445. }
  36446. },
  36447. enumerable: true,
  36448. configurable: true
  36449. });
  36450. Object.defineProperty(Material.prototype, "fogEnabled", {
  36451. /**
  36452. * Gets the value of the fog enabled state
  36453. */
  36454. get: function () {
  36455. return this._fogEnabled;
  36456. },
  36457. /**
  36458. * Sets the state for enabling fog
  36459. */
  36460. set: function (value) {
  36461. if (this._fogEnabled === value) {
  36462. return;
  36463. }
  36464. this._fogEnabled = value;
  36465. this.markAsDirty(Material.MiscDirtyFlag);
  36466. },
  36467. enumerable: true,
  36468. configurable: true
  36469. });
  36470. Object.defineProperty(Material.prototype, "wireframe", {
  36471. /**
  36472. * Gets a value specifying if wireframe mode is enabled
  36473. */
  36474. get: function () {
  36475. switch (this._fillMode) {
  36476. case Material.WireFrameFillMode:
  36477. case Material.LineListDrawMode:
  36478. case Material.LineLoopDrawMode:
  36479. case Material.LineStripDrawMode:
  36480. return true;
  36481. }
  36482. return this._scene.forceWireframe;
  36483. },
  36484. /**
  36485. * Sets the state of wireframe mode
  36486. */
  36487. set: function (value) {
  36488. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  36489. },
  36490. enumerable: true,
  36491. configurable: true
  36492. });
  36493. Object.defineProperty(Material.prototype, "pointsCloud", {
  36494. /**
  36495. * Gets the value specifying if point clouds are enabled
  36496. */
  36497. get: function () {
  36498. switch (this._fillMode) {
  36499. case Material.PointFillMode:
  36500. case Material.PointListDrawMode:
  36501. return true;
  36502. }
  36503. return this._scene.forcePointsCloud;
  36504. },
  36505. /**
  36506. * Sets the state of point cloud mode
  36507. */
  36508. set: function (value) {
  36509. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  36510. },
  36511. enumerable: true,
  36512. configurable: true
  36513. });
  36514. Object.defineProperty(Material.prototype, "fillMode", {
  36515. /**
  36516. * Gets the material fill mode
  36517. */
  36518. get: function () {
  36519. return this._fillMode;
  36520. },
  36521. /**
  36522. * Sets the material fill mode
  36523. */
  36524. set: function (value) {
  36525. if (this._fillMode === value) {
  36526. return;
  36527. }
  36528. this._fillMode = value;
  36529. this.markAsDirty(Material.MiscDirtyFlag);
  36530. },
  36531. enumerable: true,
  36532. configurable: true
  36533. });
  36534. /**
  36535. * Returns a string representation of the current material
  36536. * @param fullDetails defines a boolean indicating which levels of logging is desired
  36537. * @returns a string with material information
  36538. */
  36539. Material.prototype.toString = function (fullDetails) {
  36540. var ret = "Name: " + this.name;
  36541. if (fullDetails) {
  36542. }
  36543. return ret;
  36544. };
  36545. /**
  36546. * Gets the class name of the material
  36547. * @returns a string with the class name of the material
  36548. */
  36549. Material.prototype.getClassName = function () {
  36550. return "Material";
  36551. };
  36552. Object.defineProperty(Material.prototype, "isFrozen", {
  36553. /**
  36554. * Specifies if updates for the material been locked
  36555. */
  36556. get: function () {
  36557. return this.checkReadyOnlyOnce;
  36558. },
  36559. enumerable: true,
  36560. configurable: true
  36561. });
  36562. /**
  36563. * Locks updates for the material
  36564. */
  36565. Material.prototype.freeze = function () {
  36566. this.checkReadyOnlyOnce = true;
  36567. };
  36568. /**
  36569. * Unlocks updates for the material
  36570. */
  36571. Material.prototype.unfreeze = function () {
  36572. this.checkReadyOnlyOnce = false;
  36573. };
  36574. /**
  36575. * Specifies if the material is ready to be used
  36576. * @param mesh defines the mesh to check
  36577. * @param useInstances specifies if instances should be used
  36578. * @returns a boolean indicating if the material is ready to be used
  36579. */
  36580. Material.prototype.isReady = function (mesh, useInstances) {
  36581. return true;
  36582. };
  36583. /**
  36584. * Specifies that the submesh is ready to be used
  36585. * @param mesh defines the mesh to check
  36586. * @param subMesh defines which submesh to check
  36587. * @param useInstances specifies that instances should be used
  36588. * @returns a boolean indicating that the submesh is ready or not
  36589. */
  36590. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36591. return false;
  36592. };
  36593. /**
  36594. * Returns the material effect
  36595. * @returns the effect associated with the material
  36596. */
  36597. Material.prototype.getEffect = function () {
  36598. return this._effect;
  36599. };
  36600. /**
  36601. * Returns the current scene
  36602. * @returns a Scene
  36603. */
  36604. Material.prototype.getScene = function () {
  36605. return this._scene;
  36606. };
  36607. /**
  36608. * Specifies if the material will require alpha blending
  36609. * @returns a boolean specifying if alpha blending is needed
  36610. */
  36611. Material.prototype.needAlphaBlending = function () {
  36612. return (this.alpha < 1.0);
  36613. };
  36614. /**
  36615. * Specifies if the mesh will require alpha blending
  36616. * @param mesh defines the mesh to check
  36617. * @returns a boolean specifying if alpha blending is needed for the mesh
  36618. */
  36619. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  36620. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  36621. };
  36622. /**
  36623. * Specifies if this material should be rendered in alpha test mode
  36624. * @returns a boolean specifying if an alpha test is needed.
  36625. */
  36626. Material.prototype.needAlphaTesting = function () {
  36627. return false;
  36628. };
  36629. /**
  36630. * Gets the texture used for the alpha test
  36631. * @returns the texture to use for alpha testing
  36632. */
  36633. Material.prototype.getAlphaTestTexture = function () {
  36634. return null;
  36635. };
  36636. /**
  36637. * Marks the material to indicate that it needs to be re-calculated
  36638. */
  36639. Material.prototype.markDirty = function () {
  36640. this._wasPreviouslyReady = false;
  36641. };
  36642. /** @hidden */
  36643. Material.prototype._preBind = function (effect, overrideOrientation) {
  36644. if (overrideOrientation === void 0) { overrideOrientation = null; }
  36645. var engine = this._scene.getEngine();
  36646. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  36647. var reverse = orientation === Material.ClockWiseSideOrientation;
  36648. engine.enableEffect(effect ? effect : this._effect);
  36649. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  36650. return reverse;
  36651. };
  36652. /**
  36653. * Binds the material to the mesh
  36654. * @param world defines the world transformation matrix
  36655. * @param mesh defines the mesh to bind the material to
  36656. */
  36657. Material.prototype.bind = function (world, mesh) {
  36658. };
  36659. /**
  36660. * Binds the submesh to the material
  36661. * @param world defines the world transformation matrix
  36662. * @param mesh defines the mesh containing the submesh
  36663. * @param subMesh defines the submesh to bind the material to
  36664. */
  36665. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36666. };
  36667. /**
  36668. * Binds the world matrix to the material
  36669. * @param world defines the world transformation matrix
  36670. */
  36671. Material.prototype.bindOnlyWorldMatrix = function (world) {
  36672. };
  36673. /**
  36674. * Binds the scene's uniform buffer to the effect.
  36675. * @param effect defines the effect to bind to the scene uniform buffer
  36676. * @param sceneUbo defines the uniform buffer storing scene data
  36677. */
  36678. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  36679. sceneUbo.bindToEffect(effect, "Scene");
  36680. };
  36681. /**
  36682. * Binds the view matrix to the effect
  36683. * @param effect defines the effect to bind the view matrix to
  36684. */
  36685. Material.prototype.bindView = function (effect) {
  36686. if (!this._useUBO) {
  36687. effect.setMatrix("view", this.getScene().getViewMatrix());
  36688. }
  36689. else {
  36690. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36691. }
  36692. };
  36693. /**
  36694. * Binds the view projection matrix to the effect
  36695. * @param effect defines the effect to bind the view projection matrix to
  36696. */
  36697. Material.prototype.bindViewProjection = function (effect) {
  36698. if (!this._useUBO) {
  36699. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  36700. }
  36701. else {
  36702. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36703. }
  36704. };
  36705. /**
  36706. * Specifies if material alpha testing should be turned on for the mesh
  36707. * @param mesh defines the mesh to check
  36708. */
  36709. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  36710. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  36711. };
  36712. /**
  36713. * Processes to execute after binding the material to a mesh
  36714. * @param mesh defines the rendered mesh
  36715. */
  36716. Material.prototype._afterBind = function (mesh) {
  36717. this._scene._cachedMaterial = this;
  36718. if (mesh) {
  36719. this._scene._cachedVisibility = mesh.visibility;
  36720. }
  36721. else {
  36722. this._scene._cachedVisibility = 1;
  36723. }
  36724. if (this._onBindObservable && mesh) {
  36725. this._onBindObservable.notifyObservers(mesh);
  36726. }
  36727. if (this.disableDepthWrite) {
  36728. var engine = this._scene.getEngine();
  36729. this._cachedDepthWriteState = engine.getDepthWrite();
  36730. engine.setDepthWrite(false);
  36731. }
  36732. };
  36733. /**
  36734. * Unbinds the material from the mesh
  36735. */
  36736. Material.prototype.unbind = function () {
  36737. if (this._onUnBindObservable) {
  36738. this._onUnBindObservable.notifyObservers(this);
  36739. }
  36740. if (this.disableDepthWrite) {
  36741. var engine = this._scene.getEngine();
  36742. engine.setDepthWrite(this._cachedDepthWriteState);
  36743. }
  36744. };
  36745. /**
  36746. * Gets the active textures from the material
  36747. * @returns an array of textures
  36748. */
  36749. Material.prototype.getActiveTextures = function () {
  36750. return [];
  36751. };
  36752. /**
  36753. * Specifies if the material uses a texture
  36754. * @param texture defines the texture to check against the material
  36755. * @returns a boolean specifying if the material uses the texture
  36756. */
  36757. Material.prototype.hasTexture = function (texture) {
  36758. return false;
  36759. };
  36760. /**
  36761. * Makes a duplicate of the material, and gives it a new name
  36762. * @param name defines the new name for the duplicated material
  36763. * @returns the cloned material
  36764. */
  36765. Material.prototype.clone = function (name) {
  36766. return null;
  36767. };
  36768. /**
  36769. * Gets the meshes bound to the material
  36770. * @returns an array of meshes bound to the material
  36771. */
  36772. Material.prototype.getBindedMeshes = function () {
  36773. var result = new Array();
  36774. for (var index = 0; index < this._scene.meshes.length; index++) {
  36775. var mesh = this._scene.meshes[index];
  36776. if (mesh.material === this) {
  36777. result.push(mesh);
  36778. }
  36779. }
  36780. return result;
  36781. };
  36782. /**
  36783. * Force shader compilation
  36784. * @param mesh defines the mesh associated with this material
  36785. * @param onCompiled defines a function to execute once the material is compiled
  36786. * @param options defines the options to configure the compilation
  36787. */
  36788. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  36789. var _this = this;
  36790. var localOptions = __assign({ clipPlane: false }, options);
  36791. var subMesh = new BABYLON.BaseSubMesh();
  36792. var scene = this.getScene();
  36793. var checkReady = function () {
  36794. if (!_this._scene || !_this._scene.getEngine()) {
  36795. return;
  36796. }
  36797. if (subMesh._materialDefines) {
  36798. subMesh._materialDefines._renderId = -1;
  36799. }
  36800. var clipPlaneState = scene.clipPlane;
  36801. if (localOptions.clipPlane) {
  36802. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  36803. }
  36804. if (_this.storeEffectOnSubMeshes) {
  36805. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  36806. if (onCompiled) {
  36807. onCompiled(_this);
  36808. }
  36809. }
  36810. else {
  36811. setTimeout(checkReady, 16);
  36812. }
  36813. }
  36814. else {
  36815. if (_this.isReady(mesh)) {
  36816. if (onCompiled) {
  36817. onCompiled(_this);
  36818. }
  36819. }
  36820. else {
  36821. setTimeout(checkReady, 16);
  36822. }
  36823. }
  36824. if (localOptions.clipPlane) {
  36825. scene.clipPlane = clipPlaneState;
  36826. }
  36827. };
  36828. checkReady();
  36829. };
  36830. /**
  36831. * Force shader compilation
  36832. * @param mesh defines the mesh that will use this material
  36833. * @param options defines additional options for compiling the shaders
  36834. * @returns a promise that resolves when the compilation completes
  36835. */
  36836. Material.prototype.forceCompilationAsync = function (mesh, options) {
  36837. var _this = this;
  36838. return new Promise(function (resolve) {
  36839. _this.forceCompilation(mesh, function () {
  36840. resolve();
  36841. }, options);
  36842. });
  36843. };
  36844. /**
  36845. * Marks a define in the material to indicate that it needs to be re-computed
  36846. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  36847. */
  36848. Material.prototype.markAsDirty = function (flag) {
  36849. if (flag & Material.TextureDirtyFlag) {
  36850. this._markAllSubMeshesAsTexturesDirty();
  36851. }
  36852. if (flag & Material.LightDirtyFlag) {
  36853. this._markAllSubMeshesAsLightsDirty();
  36854. }
  36855. if (flag & Material.FresnelDirtyFlag) {
  36856. this._markAllSubMeshesAsFresnelDirty();
  36857. }
  36858. if (flag & Material.AttributesDirtyFlag) {
  36859. this._markAllSubMeshesAsAttributesDirty();
  36860. }
  36861. if (flag & Material.MiscDirtyFlag) {
  36862. this._markAllSubMeshesAsMiscDirty();
  36863. }
  36864. this.getScene().resetCachedMaterial();
  36865. };
  36866. /**
  36867. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  36868. * @param func defines a function which checks material defines against the submeshes
  36869. */
  36870. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  36871. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  36872. var mesh = _a[_i];
  36873. if (!mesh.subMeshes) {
  36874. continue;
  36875. }
  36876. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  36877. var subMesh = _c[_b];
  36878. if (subMesh.getMaterial() !== this) {
  36879. continue;
  36880. }
  36881. if (!subMesh._materialDefines) {
  36882. continue;
  36883. }
  36884. func(subMesh._materialDefines);
  36885. }
  36886. }
  36887. };
  36888. /**
  36889. * Indicates that image processing needs to be re-calculated for all submeshes
  36890. */
  36891. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  36892. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  36893. };
  36894. /**
  36895. * Indicates that textures need to be re-calculated for all submeshes
  36896. */
  36897. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  36898. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  36899. };
  36900. /**
  36901. * Indicates that fresnel needs to be re-calculated for all submeshes
  36902. */
  36903. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  36904. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  36905. };
  36906. /**
  36907. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  36908. */
  36909. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  36910. this._markAllSubMeshesAsDirty(function (defines) {
  36911. defines.markAsFresnelDirty();
  36912. defines.markAsMiscDirty();
  36913. });
  36914. };
  36915. /**
  36916. * Indicates that lights need to be re-calculated for all submeshes
  36917. */
  36918. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  36919. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  36920. };
  36921. /**
  36922. * Indicates that attributes need to be re-calculated for all submeshes
  36923. */
  36924. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  36925. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  36926. };
  36927. /**
  36928. * Indicates that misc needs to be re-calculated for all submeshes
  36929. */
  36930. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  36931. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  36932. };
  36933. /**
  36934. * Indicates that textures and misc need to be re-calculated for all submeshes
  36935. */
  36936. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  36937. this._markAllSubMeshesAsDirty(function (defines) {
  36938. defines.markAsTexturesDirty();
  36939. defines.markAsMiscDirty();
  36940. });
  36941. };
  36942. /**
  36943. * Disposes the material
  36944. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  36945. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  36946. */
  36947. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36948. // Animations
  36949. this.getScene().stopAnimation(this);
  36950. this.getScene().freeProcessedMaterials();
  36951. // Remove from scene
  36952. var index = this._scene.materials.indexOf(this);
  36953. if (index >= 0) {
  36954. this._scene.materials.splice(index, 1);
  36955. }
  36956. this._scene.onMaterialRemovedObservable.notifyObservers(this);
  36957. // Remove from meshes
  36958. for (index = 0; index < this._scene.meshes.length; index++) {
  36959. var mesh = this._scene.meshes[index];
  36960. if (mesh.material === this) {
  36961. mesh.material = null;
  36962. if (mesh.geometry) {
  36963. var geometry = (mesh.geometry);
  36964. if (this.storeEffectOnSubMeshes) {
  36965. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  36966. var subMesh = _a[_i];
  36967. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  36968. if (forceDisposeEffect && subMesh._materialEffect) {
  36969. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  36970. }
  36971. }
  36972. }
  36973. else {
  36974. geometry._releaseVertexArrayObject(this._effect);
  36975. }
  36976. }
  36977. }
  36978. }
  36979. this._uniformBuffer.dispose();
  36980. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  36981. if (forceDisposeEffect && this._effect) {
  36982. if (!this.storeEffectOnSubMeshes) {
  36983. this._scene.getEngine()._releaseEffect(this._effect);
  36984. }
  36985. this._effect = null;
  36986. }
  36987. // Callback
  36988. this.onDisposeObservable.notifyObservers(this);
  36989. this.onDisposeObservable.clear();
  36990. if (this._onBindObservable) {
  36991. this._onBindObservable.clear();
  36992. }
  36993. if (this._onUnBindObservable) {
  36994. this._onUnBindObservable.clear();
  36995. }
  36996. };
  36997. /**
  36998. * Serializes this material
  36999. * @returns the serialized material object
  37000. */
  37001. Material.prototype.serialize = function () {
  37002. return BABYLON.SerializationHelper.Serialize(this);
  37003. };
  37004. /**
  37005. * Creates a MultiMaterial from parsed MultiMaterial data.
  37006. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  37007. * @param scene defines the hosting scene
  37008. * @returns a new MultiMaterial
  37009. */
  37010. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  37011. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  37012. multiMaterial.id = parsedMultiMaterial.id;
  37013. if (BABYLON.Tags) {
  37014. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  37015. }
  37016. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  37017. var subMatId = parsedMultiMaterial.materials[matIndex];
  37018. if (subMatId) {
  37019. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  37020. }
  37021. else {
  37022. multiMaterial.subMaterials.push(null);
  37023. }
  37024. }
  37025. return multiMaterial;
  37026. };
  37027. /**
  37028. * Creates a material from parsed material data
  37029. * @param parsedMaterial defines parsed material data
  37030. * @param scene defines the hosting scene
  37031. * @param rootUrl defines the root URL to use to load textures
  37032. * @returns a new material
  37033. */
  37034. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  37035. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  37036. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  37037. }
  37038. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  37039. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  37040. if (!BABYLON.LegacyPBRMaterial) {
  37041. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  37042. return;
  37043. }
  37044. }
  37045. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  37046. return materialType.Parse(parsedMaterial, scene, rootUrl);
  37047. };
  37048. // Triangle views
  37049. Material._TriangleFillMode = 0;
  37050. Material._WireFrameFillMode = 1;
  37051. Material._PointFillMode = 2;
  37052. // Draw modes
  37053. Material._PointListDrawMode = 3;
  37054. Material._LineListDrawMode = 4;
  37055. Material._LineLoopDrawMode = 5;
  37056. Material._LineStripDrawMode = 6;
  37057. Material._TriangleStripDrawMode = 7;
  37058. Material._TriangleFanDrawMode = 8;
  37059. /**
  37060. * Stores the clock-wise side orientation
  37061. */
  37062. Material._ClockWiseSideOrientation = 0;
  37063. /**
  37064. * Stores the counter clock-wise side orientation
  37065. */
  37066. Material._CounterClockWiseSideOrientation = 1;
  37067. /**
  37068. * The dirty texture flag value
  37069. */
  37070. Material.TextureDirtyFlag = 1;
  37071. /**
  37072. * The dirty light flag value
  37073. */
  37074. Material.LightDirtyFlag = 2;
  37075. /**
  37076. * The dirty fresnel flag value
  37077. */
  37078. Material.FresnelDirtyFlag = 4;
  37079. /**
  37080. * The dirty attribute flag value
  37081. */
  37082. Material.AttributesDirtyFlag = 8;
  37083. /**
  37084. * The dirty misc flag value
  37085. */
  37086. Material.MiscDirtyFlag = 16;
  37087. /**
  37088. * The all dirty flag value
  37089. */
  37090. Material.AllDirtyFlag = 31;
  37091. __decorate([
  37092. BABYLON.serialize()
  37093. ], Material.prototype, "id", void 0);
  37094. __decorate([
  37095. BABYLON.serialize()
  37096. ], Material.prototype, "uniqueId", void 0);
  37097. __decorate([
  37098. BABYLON.serialize()
  37099. ], Material.prototype, "name", void 0);
  37100. __decorate([
  37101. BABYLON.serialize()
  37102. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  37103. __decorate([
  37104. BABYLON.serialize()
  37105. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  37106. __decorate([
  37107. BABYLON.serialize()
  37108. ], Material.prototype, "state", void 0);
  37109. __decorate([
  37110. BABYLON.serialize("alpha")
  37111. ], Material.prototype, "_alpha", void 0);
  37112. __decorate([
  37113. BABYLON.serialize("backFaceCulling")
  37114. ], Material.prototype, "_backFaceCulling", void 0);
  37115. __decorate([
  37116. BABYLON.serialize()
  37117. ], Material.prototype, "sideOrientation", void 0);
  37118. __decorate([
  37119. BABYLON.serialize("alphaMode")
  37120. ], Material.prototype, "_alphaMode", void 0);
  37121. __decorate([
  37122. BABYLON.serialize()
  37123. ], Material.prototype, "_needDepthPrePass", void 0);
  37124. __decorate([
  37125. BABYLON.serialize()
  37126. ], Material.prototype, "disableDepthWrite", void 0);
  37127. __decorate([
  37128. BABYLON.serialize()
  37129. ], Material.prototype, "forceDepthWrite", void 0);
  37130. __decorate([
  37131. BABYLON.serialize()
  37132. ], Material.prototype, "separateCullingPass", void 0);
  37133. __decorate([
  37134. BABYLON.serialize("fogEnabled")
  37135. ], Material.prototype, "_fogEnabled", void 0);
  37136. __decorate([
  37137. BABYLON.serialize()
  37138. ], Material.prototype, "pointSize", void 0);
  37139. __decorate([
  37140. BABYLON.serialize()
  37141. ], Material.prototype, "zOffset", void 0);
  37142. __decorate([
  37143. BABYLON.serialize()
  37144. ], Material.prototype, "wireframe", null);
  37145. __decorate([
  37146. BABYLON.serialize()
  37147. ], Material.prototype, "pointsCloud", null);
  37148. __decorate([
  37149. BABYLON.serialize()
  37150. ], Material.prototype, "fillMode", null);
  37151. return Material;
  37152. }());
  37153. BABYLON.Material = Material;
  37154. })(BABYLON || (BABYLON = {}));
  37155. //# sourceMappingURL=babylon.material.js.map
  37156. var BABYLON;
  37157. (function (BABYLON) {
  37158. /**
  37159. * Uniform buffer objects.
  37160. *
  37161. * Handles blocks of uniform on the GPU.
  37162. *
  37163. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37164. *
  37165. * For more information, please refer to :
  37166. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37167. */
  37168. var UniformBuffer = /** @class */ (function () {
  37169. /**
  37170. * Instantiates a new Uniform buffer objects.
  37171. *
  37172. * Handles blocks of uniform on the GPU.
  37173. *
  37174. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37175. *
  37176. * For more information, please refer to :
  37177. * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37178. * @param engine Define the engine the buffer is associated with
  37179. * @param data Define the data contained in the buffer
  37180. * @param dynamic Define if the buffer is updatable
  37181. */
  37182. function UniformBuffer(engine, data, dynamic) {
  37183. this._engine = engine;
  37184. this._noUBO = !engine.supportsUniformBuffers;
  37185. this._dynamic = dynamic;
  37186. this._data = data || [];
  37187. this._uniformLocations = {};
  37188. this._uniformSizes = {};
  37189. this._uniformLocationPointer = 0;
  37190. this._needSync = false;
  37191. if (this._noUBO) {
  37192. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  37193. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  37194. this.updateFloat = this._updateFloatForEffect;
  37195. this.updateFloat2 = this._updateFloat2ForEffect;
  37196. this.updateFloat3 = this._updateFloat3ForEffect;
  37197. this.updateFloat4 = this._updateFloat4ForEffect;
  37198. this.updateMatrix = this._updateMatrixForEffect;
  37199. this.updateVector3 = this._updateVector3ForEffect;
  37200. this.updateVector4 = this._updateVector4ForEffect;
  37201. this.updateColor3 = this._updateColor3ForEffect;
  37202. this.updateColor4 = this._updateColor4ForEffect;
  37203. }
  37204. else {
  37205. this._engine._uniformBuffers.push(this);
  37206. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  37207. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  37208. this.updateFloat = this._updateFloatForUniform;
  37209. this.updateFloat2 = this._updateFloat2ForUniform;
  37210. this.updateFloat3 = this._updateFloat3ForUniform;
  37211. this.updateFloat4 = this._updateFloat4ForUniform;
  37212. this.updateMatrix = this._updateMatrixForUniform;
  37213. this.updateVector3 = this._updateVector3ForUniform;
  37214. this.updateVector4 = this._updateVector4ForUniform;
  37215. this.updateColor3 = this._updateColor3ForUniform;
  37216. this.updateColor4 = this._updateColor4ForUniform;
  37217. }
  37218. }
  37219. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  37220. /**
  37221. * Indicates if the buffer is using the WebGL2 UBO implementation,
  37222. * or just falling back on setUniformXXX calls.
  37223. */
  37224. get: function () {
  37225. return !this._noUBO;
  37226. },
  37227. enumerable: true,
  37228. configurable: true
  37229. });
  37230. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  37231. /**
  37232. * Indicates if the WebGL underlying uniform buffer is in sync
  37233. * with the javascript cache data.
  37234. */
  37235. get: function () {
  37236. return !this._needSync;
  37237. },
  37238. enumerable: true,
  37239. configurable: true
  37240. });
  37241. /**
  37242. * Indicates if the WebGL underlying uniform buffer is dynamic.
  37243. * Also, a dynamic UniformBuffer will disable cache verification and always
  37244. * update the underlying WebGL uniform buffer to the GPU.
  37245. * @returns if Dynamic, otherwise false
  37246. */
  37247. UniformBuffer.prototype.isDynamic = function () {
  37248. return this._dynamic !== undefined;
  37249. };
  37250. /**
  37251. * The data cache on JS side.
  37252. * @returns the underlying data as a float array
  37253. */
  37254. UniformBuffer.prototype.getData = function () {
  37255. return this._bufferData;
  37256. };
  37257. /**
  37258. * The underlying WebGL Uniform buffer.
  37259. * @returns the webgl buffer
  37260. */
  37261. UniformBuffer.prototype.getBuffer = function () {
  37262. return this._buffer;
  37263. };
  37264. /**
  37265. * std140 layout specifies how to align data within an UBO structure.
  37266. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  37267. * for specs.
  37268. */
  37269. UniformBuffer.prototype._fillAlignment = function (size) {
  37270. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  37271. // and 4x4 matrices
  37272. // TODO : change if other types are used
  37273. var alignment;
  37274. if (size <= 2) {
  37275. alignment = size;
  37276. }
  37277. else {
  37278. alignment = 4;
  37279. }
  37280. if ((this._uniformLocationPointer % alignment) !== 0) {
  37281. var oldPointer = this._uniformLocationPointer;
  37282. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  37283. var diff = this._uniformLocationPointer - oldPointer;
  37284. for (var i = 0; i < diff; i++) {
  37285. this._data.push(0);
  37286. }
  37287. }
  37288. };
  37289. /**
  37290. * Adds an uniform in the buffer.
  37291. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  37292. * for the layout to be correct !
  37293. * @param name Name of the uniform, as used in the uniform block in the shader.
  37294. * @param size Data size, or data directly.
  37295. */
  37296. UniformBuffer.prototype.addUniform = function (name, size) {
  37297. if (this._noUBO) {
  37298. return;
  37299. }
  37300. if (this._uniformLocations[name] !== undefined) {
  37301. // Already existing uniform
  37302. return;
  37303. }
  37304. // This function must be called in the order of the shader layout !
  37305. // size can be the size of the uniform, or data directly
  37306. var data;
  37307. if (size instanceof Array) {
  37308. data = size;
  37309. size = data.length;
  37310. }
  37311. else {
  37312. size = size;
  37313. data = [];
  37314. // Fill with zeros
  37315. for (var i = 0; i < size; i++) {
  37316. data.push(0);
  37317. }
  37318. }
  37319. this._fillAlignment(size);
  37320. this._uniformSizes[name] = size;
  37321. this._uniformLocations[name] = this._uniformLocationPointer;
  37322. this._uniformLocationPointer += size;
  37323. for (var i = 0; i < size; i++) {
  37324. this._data.push(data[i]);
  37325. }
  37326. this._needSync = true;
  37327. };
  37328. /**
  37329. * Adds a Matrix 4x4 to the uniform buffer.
  37330. * @param name Name of the uniform, as used in the uniform block in the shader.
  37331. * @param mat A 4x4 matrix.
  37332. */
  37333. UniformBuffer.prototype.addMatrix = function (name, mat) {
  37334. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  37335. };
  37336. /**
  37337. * Adds a vec2 to the uniform buffer.
  37338. * @param name Name of the uniform, as used in the uniform block in the shader.
  37339. * @param x Define the x component value of the vec2
  37340. * @param y Define the y component value of the vec2
  37341. */
  37342. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  37343. var temp = [x, y];
  37344. this.addUniform(name, temp);
  37345. };
  37346. /**
  37347. * Adds a vec3 to the uniform buffer.
  37348. * @param name Name of the uniform, as used in the uniform block in the shader.
  37349. * @param x Define the x component value of the vec3
  37350. * @param y Define the y component value of the vec3
  37351. * @param z Define the z component value of the vec3
  37352. */
  37353. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  37354. var temp = [x, y, z];
  37355. this.addUniform(name, temp);
  37356. };
  37357. /**
  37358. * Adds a vec3 to the uniform buffer.
  37359. * @param name Name of the uniform, as used in the uniform block in the shader.
  37360. * @param color Define the vec3 from a Color
  37361. */
  37362. UniformBuffer.prototype.addColor3 = function (name, color) {
  37363. var temp = new Array();
  37364. color.toArray(temp);
  37365. this.addUniform(name, temp);
  37366. };
  37367. /**
  37368. * Adds a vec4 to the uniform buffer.
  37369. * @param name Name of the uniform, as used in the uniform block in the shader.
  37370. * @param color Define the rgb components from a Color
  37371. * @param alpha Define the a component of the vec4
  37372. */
  37373. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  37374. var temp = new Array();
  37375. color.toArray(temp);
  37376. temp.push(alpha);
  37377. this.addUniform(name, temp);
  37378. };
  37379. /**
  37380. * Adds a vec3 to the uniform buffer.
  37381. * @param name Name of the uniform, as used in the uniform block in the shader.
  37382. * @param vector Define the vec3 components from a Vector
  37383. */
  37384. UniformBuffer.prototype.addVector3 = function (name, vector) {
  37385. var temp = new Array();
  37386. vector.toArray(temp);
  37387. this.addUniform(name, temp);
  37388. };
  37389. /**
  37390. * Adds a Matrix 3x3 to the uniform buffer.
  37391. * @param name Name of the uniform, as used in the uniform block in the shader.
  37392. */
  37393. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  37394. this.addUniform(name, 12);
  37395. };
  37396. /**
  37397. * Adds a Matrix 2x2 to the uniform buffer.
  37398. * @param name Name of the uniform, as used in the uniform block in the shader.
  37399. */
  37400. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  37401. this.addUniform(name, 8);
  37402. };
  37403. /**
  37404. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  37405. */
  37406. UniformBuffer.prototype.create = function () {
  37407. if (this._noUBO) {
  37408. return;
  37409. }
  37410. if (this._buffer) {
  37411. return; // nothing to do
  37412. }
  37413. // See spec, alignment must be filled as a vec4
  37414. this._fillAlignment(4);
  37415. this._bufferData = new Float32Array(this._data);
  37416. this._rebuild();
  37417. this._needSync = true;
  37418. };
  37419. /** @hidden */
  37420. UniformBuffer.prototype._rebuild = function () {
  37421. if (this._noUBO) {
  37422. return;
  37423. }
  37424. if (this._dynamic) {
  37425. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  37426. }
  37427. else {
  37428. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  37429. }
  37430. };
  37431. /**
  37432. * Updates the WebGL Uniform Buffer on the GPU.
  37433. * If the `dynamic` flag is set to true, no cache comparison is done.
  37434. * Otherwise, the buffer will be updated only if the cache differs.
  37435. */
  37436. UniformBuffer.prototype.update = function () {
  37437. if (!this._buffer) {
  37438. this.create();
  37439. return;
  37440. }
  37441. if (!this._dynamic && !this._needSync) {
  37442. return;
  37443. }
  37444. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  37445. this._needSync = false;
  37446. };
  37447. /**
  37448. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  37449. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37450. * @param data Define the flattened data
  37451. * @param size Define the size of the data.
  37452. */
  37453. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  37454. var location = this._uniformLocations[uniformName];
  37455. if (location === undefined) {
  37456. if (this._buffer) {
  37457. // Cannot add an uniform if the buffer is already created
  37458. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  37459. return;
  37460. }
  37461. this.addUniform(uniformName, size);
  37462. location = this._uniformLocations[uniformName];
  37463. }
  37464. if (!this._buffer) {
  37465. this.create();
  37466. }
  37467. if (!this._dynamic) {
  37468. // Cache for static uniform buffers
  37469. var changed = false;
  37470. for (var i = 0; i < size; i++) {
  37471. if (this._bufferData[location + i] !== data[i]) {
  37472. changed = true;
  37473. this._bufferData[location + i] = data[i];
  37474. }
  37475. }
  37476. this._needSync = this._needSync || changed;
  37477. }
  37478. else {
  37479. // No cache for dynamic
  37480. for (var i = 0; i < size; i++) {
  37481. this._bufferData[location + i] = data[i];
  37482. }
  37483. }
  37484. };
  37485. // Update methods
  37486. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  37487. // To match std140, matrix must be realigned
  37488. for (var i = 0; i < 3; i++) {
  37489. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  37490. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  37491. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  37492. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  37493. }
  37494. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  37495. };
  37496. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  37497. this._currentEffect.setMatrix3x3(name, matrix);
  37498. };
  37499. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  37500. this._currentEffect.setMatrix2x2(name, matrix);
  37501. };
  37502. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  37503. // To match std140, matrix must be realigned
  37504. for (var i = 0; i < 2; i++) {
  37505. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  37506. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  37507. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  37508. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  37509. }
  37510. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  37511. };
  37512. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  37513. this._currentEffect.setFloat(name, x);
  37514. };
  37515. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  37516. UniformBuffer._tempBuffer[0] = x;
  37517. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  37518. };
  37519. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  37520. if (suffix === void 0) { suffix = ""; }
  37521. this._currentEffect.setFloat2(name + suffix, x, y);
  37522. };
  37523. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  37524. if (suffix === void 0) { suffix = ""; }
  37525. UniformBuffer._tempBuffer[0] = x;
  37526. UniformBuffer._tempBuffer[1] = y;
  37527. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  37528. };
  37529. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  37530. if (suffix === void 0) { suffix = ""; }
  37531. this._currentEffect.setFloat3(name + suffix, x, y, z);
  37532. };
  37533. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  37534. if (suffix === void 0) { suffix = ""; }
  37535. UniformBuffer._tempBuffer[0] = x;
  37536. UniformBuffer._tempBuffer[1] = y;
  37537. UniformBuffer._tempBuffer[2] = z;
  37538. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37539. };
  37540. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  37541. if (suffix === void 0) { suffix = ""; }
  37542. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  37543. };
  37544. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  37545. if (suffix === void 0) { suffix = ""; }
  37546. UniformBuffer._tempBuffer[0] = x;
  37547. UniformBuffer._tempBuffer[1] = y;
  37548. UniformBuffer._tempBuffer[2] = z;
  37549. UniformBuffer._tempBuffer[3] = w;
  37550. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37551. };
  37552. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  37553. this._currentEffect.setMatrix(name, mat);
  37554. };
  37555. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  37556. this.updateUniform(name, mat.toArray(), 16);
  37557. };
  37558. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  37559. this._currentEffect.setVector3(name, vector);
  37560. };
  37561. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  37562. vector.toArray(UniformBuffer._tempBuffer);
  37563. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37564. };
  37565. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  37566. this._currentEffect.setVector4(name, vector);
  37567. };
  37568. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  37569. vector.toArray(UniformBuffer._tempBuffer);
  37570. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37571. };
  37572. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  37573. if (suffix === void 0) { suffix = ""; }
  37574. this._currentEffect.setColor3(name + suffix, color);
  37575. };
  37576. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  37577. if (suffix === void 0) { suffix = ""; }
  37578. color.toArray(UniformBuffer._tempBuffer);
  37579. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37580. };
  37581. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  37582. if (suffix === void 0) { suffix = ""; }
  37583. this._currentEffect.setColor4(name + suffix, color, alpha);
  37584. };
  37585. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  37586. if (suffix === void 0) { suffix = ""; }
  37587. color.toArray(UniformBuffer._tempBuffer);
  37588. UniformBuffer._tempBuffer[3] = alpha;
  37589. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37590. };
  37591. /**
  37592. * Sets a sampler uniform on the effect.
  37593. * @param name Define the name of the sampler.
  37594. * @param texture Define the texture to set in the sampler
  37595. */
  37596. UniformBuffer.prototype.setTexture = function (name, texture) {
  37597. this._currentEffect.setTexture(name, texture);
  37598. };
  37599. /**
  37600. * Directly updates the value of the uniform in the cache AND on the GPU.
  37601. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37602. * @param data Define the flattened data
  37603. */
  37604. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  37605. this.updateUniform(uniformName, data, data.length);
  37606. this.update();
  37607. };
  37608. /**
  37609. * Binds this uniform buffer to an effect.
  37610. * @param effect Define the effect to bind the buffer to
  37611. * @param name Name of the uniform block in the shader.
  37612. */
  37613. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  37614. this._currentEffect = effect;
  37615. if (this._noUBO || !this._buffer) {
  37616. return;
  37617. }
  37618. effect.bindUniformBuffer(this._buffer, name);
  37619. };
  37620. /**
  37621. * Disposes the uniform buffer.
  37622. */
  37623. UniformBuffer.prototype.dispose = function () {
  37624. if (this._noUBO) {
  37625. return;
  37626. }
  37627. var index = this._engine._uniformBuffers.indexOf(this);
  37628. if (index !== -1) {
  37629. this._engine._uniformBuffers.splice(index, 1);
  37630. }
  37631. if (!this._buffer) {
  37632. return;
  37633. }
  37634. if (this._engine._releaseBuffer(this._buffer)) {
  37635. this._buffer = null;
  37636. }
  37637. };
  37638. // Pool for avoiding memory leaks
  37639. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  37640. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  37641. return UniformBuffer;
  37642. }());
  37643. BABYLON.UniformBuffer = UniformBuffer;
  37644. })(BABYLON || (BABYLON = {}));
  37645. //# sourceMappingURL=babylon.uniformBuffer.js.map
  37646. var BABYLON;
  37647. (function (BABYLON) {
  37648. /**
  37649. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  37650. */
  37651. var VertexData = /** @class */ (function () {
  37652. function VertexData() {
  37653. }
  37654. /**
  37655. * Uses the passed data array to set the set the values for the specified kind of data
  37656. * @param data a linear array of floating numbers
  37657. * @param kind the type of data that is being set, eg positions, colors etc
  37658. */
  37659. VertexData.prototype.set = function (data, kind) {
  37660. switch (kind) {
  37661. case BABYLON.VertexBuffer.PositionKind:
  37662. this.positions = data;
  37663. break;
  37664. case BABYLON.VertexBuffer.NormalKind:
  37665. this.normals = data;
  37666. break;
  37667. case BABYLON.VertexBuffer.TangentKind:
  37668. this.tangents = data;
  37669. break;
  37670. case BABYLON.VertexBuffer.UVKind:
  37671. this.uvs = data;
  37672. break;
  37673. case BABYLON.VertexBuffer.UV2Kind:
  37674. this.uvs2 = data;
  37675. break;
  37676. case BABYLON.VertexBuffer.UV3Kind:
  37677. this.uvs3 = data;
  37678. break;
  37679. case BABYLON.VertexBuffer.UV4Kind:
  37680. this.uvs4 = data;
  37681. break;
  37682. case BABYLON.VertexBuffer.UV5Kind:
  37683. this.uvs5 = data;
  37684. break;
  37685. case BABYLON.VertexBuffer.UV6Kind:
  37686. this.uvs6 = data;
  37687. break;
  37688. case BABYLON.VertexBuffer.ColorKind:
  37689. this.colors = data;
  37690. break;
  37691. case BABYLON.VertexBuffer.MatricesIndicesKind:
  37692. this.matricesIndices = data;
  37693. break;
  37694. case BABYLON.VertexBuffer.MatricesWeightsKind:
  37695. this.matricesWeights = data;
  37696. break;
  37697. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  37698. this.matricesIndicesExtra = data;
  37699. break;
  37700. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  37701. this.matricesWeightsExtra = data;
  37702. break;
  37703. }
  37704. };
  37705. /**
  37706. * Associates the vertexData to the passed Mesh.
  37707. * Sets it as updatable or not (default `false`)
  37708. * @param mesh the mesh the vertexData is applied to
  37709. * @param updatable when used and having the value true allows new data to update the vertexData
  37710. * @returns the VertexData
  37711. */
  37712. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  37713. this._applyTo(mesh, updatable);
  37714. return this;
  37715. };
  37716. /**
  37717. * Associates the vertexData to the passed Geometry.
  37718. * Sets it as updatable or not (default `false`)
  37719. * @param geometry the geometry the vertexData is applied to
  37720. * @param updatable when used and having the value true allows new data to update the vertexData
  37721. * @returns VertexData
  37722. */
  37723. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  37724. this._applyTo(geometry, updatable);
  37725. return this;
  37726. };
  37727. /**
  37728. * Updates the associated mesh
  37729. * @param mesh the mesh to be updated
  37730. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  37731. * @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
  37732. * @returns VertexData
  37733. */
  37734. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  37735. this._update(mesh);
  37736. return this;
  37737. };
  37738. /**
  37739. * Updates the associated geometry
  37740. * @param geometry the geometry to be updated
  37741. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  37742. * @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
  37743. * @returns VertexData.
  37744. */
  37745. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  37746. this._update(geometry);
  37747. return this;
  37748. };
  37749. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  37750. if (updatable === void 0) { updatable = false; }
  37751. if (this.positions) {
  37752. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  37753. }
  37754. if (this.normals) {
  37755. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  37756. }
  37757. if (this.tangents) {
  37758. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  37759. }
  37760. if (this.uvs) {
  37761. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  37762. }
  37763. if (this.uvs2) {
  37764. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  37765. }
  37766. if (this.uvs3) {
  37767. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  37768. }
  37769. if (this.uvs4) {
  37770. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  37771. }
  37772. if (this.uvs5) {
  37773. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  37774. }
  37775. if (this.uvs6) {
  37776. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  37777. }
  37778. if (this.colors) {
  37779. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  37780. }
  37781. if (this.matricesIndices) {
  37782. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  37783. }
  37784. if (this.matricesWeights) {
  37785. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  37786. }
  37787. if (this.matricesIndicesExtra) {
  37788. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  37789. }
  37790. if (this.matricesWeightsExtra) {
  37791. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  37792. }
  37793. if (this.indices) {
  37794. meshOrGeometry.setIndices(this.indices, null, updatable);
  37795. }
  37796. else {
  37797. meshOrGeometry.setIndices([], null);
  37798. }
  37799. return this;
  37800. };
  37801. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  37802. if (this.positions) {
  37803. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  37804. }
  37805. if (this.normals) {
  37806. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  37807. }
  37808. if (this.tangents) {
  37809. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  37810. }
  37811. if (this.uvs) {
  37812. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  37813. }
  37814. if (this.uvs2) {
  37815. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  37816. }
  37817. if (this.uvs3) {
  37818. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  37819. }
  37820. if (this.uvs4) {
  37821. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  37822. }
  37823. if (this.uvs5) {
  37824. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  37825. }
  37826. if (this.uvs6) {
  37827. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  37828. }
  37829. if (this.colors) {
  37830. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  37831. }
  37832. if (this.matricesIndices) {
  37833. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  37834. }
  37835. if (this.matricesWeights) {
  37836. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  37837. }
  37838. if (this.matricesIndicesExtra) {
  37839. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  37840. }
  37841. if (this.matricesWeightsExtra) {
  37842. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  37843. }
  37844. if (this.indices) {
  37845. meshOrGeometry.setIndices(this.indices, null);
  37846. }
  37847. return this;
  37848. };
  37849. /**
  37850. * Transforms each position and each normal of the vertexData according to the passed Matrix
  37851. * @param matrix the transforming matrix
  37852. * @returns the VertexData
  37853. */
  37854. VertexData.prototype.transform = function (matrix) {
  37855. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  37856. var transformed = BABYLON.Vector3.Zero();
  37857. var index;
  37858. if (this.positions) {
  37859. var position = BABYLON.Vector3.Zero();
  37860. for (index = 0; index < this.positions.length; index += 3) {
  37861. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  37862. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  37863. this.positions[index] = transformed.x;
  37864. this.positions[index + 1] = transformed.y;
  37865. this.positions[index + 2] = transformed.z;
  37866. }
  37867. }
  37868. if (this.normals) {
  37869. var normal = BABYLON.Vector3.Zero();
  37870. for (index = 0; index < this.normals.length; index += 3) {
  37871. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  37872. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  37873. this.normals[index] = transformed.x;
  37874. this.normals[index + 1] = transformed.y;
  37875. this.normals[index + 2] = transformed.z;
  37876. }
  37877. }
  37878. if (this.tangents) {
  37879. var tangent = BABYLON.Vector4.Zero();
  37880. var tangentTransformed = BABYLON.Vector4.Zero();
  37881. for (index = 0; index < this.tangents.length; index += 4) {
  37882. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  37883. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  37884. this.tangents[index] = tangentTransformed.x;
  37885. this.tangents[index + 1] = tangentTransformed.y;
  37886. this.tangents[index + 2] = tangentTransformed.z;
  37887. this.tangents[index + 3] = tangentTransformed.w;
  37888. }
  37889. }
  37890. if (flip && this.indices) {
  37891. for (index = 0; index < this.indices.length; index += 3) {
  37892. var tmp = this.indices[index + 1];
  37893. this.indices[index + 1] = this.indices[index + 2];
  37894. this.indices[index + 2] = tmp;
  37895. }
  37896. }
  37897. return this;
  37898. };
  37899. /**
  37900. * Merges the passed VertexData into the current one
  37901. * @param other the VertexData to be merged into the current one
  37902. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  37903. * @returns the modified VertexData
  37904. */
  37905. VertexData.prototype.merge = function (other, use32BitsIndices) {
  37906. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  37907. this._validate();
  37908. other._validate();
  37909. if (!this.normals !== !other.normals ||
  37910. !this.tangents !== !other.tangents ||
  37911. !this.uvs !== !other.uvs ||
  37912. !this.uvs2 !== !other.uvs2 ||
  37913. !this.uvs3 !== !other.uvs3 ||
  37914. !this.uvs4 !== !other.uvs4 ||
  37915. !this.uvs5 !== !other.uvs5 ||
  37916. !this.uvs6 !== !other.uvs6 ||
  37917. !this.colors !== !other.colors ||
  37918. !this.matricesIndices !== !other.matricesIndices ||
  37919. !this.matricesWeights !== !other.matricesWeights ||
  37920. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  37921. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  37922. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  37923. }
  37924. if (other.indices) {
  37925. if (!this.indices) {
  37926. this.indices = [];
  37927. }
  37928. var offset = this.positions ? this.positions.length / 3 : 0;
  37929. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  37930. if (isSrcTypedArray) {
  37931. var len = this.indices.length + other.indices.length;
  37932. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  37933. temp.set(this.indices);
  37934. var decal = this.indices.length;
  37935. for (var index = 0; index < other.indices.length; index++) {
  37936. temp[decal + index] = other.indices[index] + offset;
  37937. }
  37938. this.indices = temp;
  37939. }
  37940. else {
  37941. for (var index = 0; index < other.indices.length; index++) {
  37942. this.indices.push(other.indices[index] + offset);
  37943. }
  37944. }
  37945. }
  37946. this.positions = this._mergeElement(this.positions, other.positions);
  37947. this.normals = this._mergeElement(this.normals, other.normals);
  37948. this.tangents = this._mergeElement(this.tangents, other.tangents);
  37949. this.uvs = this._mergeElement(this.uvs, other.uvs);
  37950. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  37951. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  37952. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  37953. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  37954. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  37955. this.colors = this._mergeElement(this.colors, other.colors);
  37956. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  37957. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  37958. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  37959. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  37960. return this;
  37961. };
  37962. VertexData.prototype._mergeElement = function (source, other) {
  37963. if (!source) {
  37964. return other;
  37965. }
  37966. if (!other) {
  37967. return source;
  37968. }
  37969. var len = other.length + source.length;
  37970. var isSrcTypedArray = source instanceof Float32Array;
  37971. var isOthTypedArray = other instanceof Float32Array;
  37972. // use non-loop method when the source is Float32Array
  37973. if (isSrcTypedArray) {
  37974. var ret32 = new Float32Array(len);
  37975. ret32.set(source);
  37976. ret32.set(other, source.length);
  37977. return ret32;
  37978. // source is number[], when other is also use concat
  37979. }
  37980. else if (!isOthTypedArray) {
  37981. return source.concat(other);
  37982. // source is a number[], but other is a Float32Array, loop required
  37983. }
  37984. else {
  37985. var ret = source.slice(0); // copy source to a separate array
  37986. for (var i = 0, len = other.length; i < len; i++) {
  37987. ret.push(other[i]);
  37988. }
  37989. return ret;
  37990. }
  37991. };
  37992. VertexData.prototype._validate = function () {
  37993. if (!this.positions) {
  37994. throw new Error("Positions are required");
  37995. }
  37996. var getElementCount = function (kind, values) {
  37997. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  37998. if ((values.length % stride) !== 0) {
  37999. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  38000. }
  38001. return values.length / stride;
  38002. };
  38003. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  38004. var validateElementCount = function (kind, values) {
  38005. var elementCount = getElementCount(kind, values);
  38006. if (elementCount !== positionsElementCount) {
  38007. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  38008. }
  38009. };
  38010. if (this.normals) {
  38011. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  38012. }
  38013. if (this.tangents) {
  38014. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  38015. }
  38016. if (this.uvs) {
  38017. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  38018. }
  38019. if (this.uvs2) {
  38020. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  38021. }
  38022. if (this.uvs3) {
  38023. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  38024. }
  38025. if (this.uvs4) {
  38026. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  38027. }
  38028. if (this.uvs5) {
  38029. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  38030. }
  38031. if (this.uvs6) {
  38032. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  38033. }
  38034. if (this.colors) {
  38035. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  38036. }
  38037. if (this.matricesIndices) {
  38038. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  38039. }
  38040. if (this.matricesWeights) {
  38041. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  38042. }
  38043. if (this.matricesIndicesExtra) {
  38044. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  38045. }
  38046. if (this.matricesWeightsExtra) {
  38047. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  38048. }
  38049. };
  38050. /**
  38051. * Serializes the VertexData
  38052. * @returns a serialized object
  38053. */
  38054. VertexData.prototype.serialize = function () {
  38055. var serializationObject = this.serialize();
  38056. if (this.positions) {
  38057. serializationObject.positions = this.positions;
  38058. }
  38059. if (this.normals) {
  38060. serializationObject.normals = this.normals;
  38061. }
  38062. if (this.tangents) {
  38063. serializationObject.tangents = this.tangents;
  38064. }
  38065. if (this.uvs) {
  38066. serializationObject.uvs = this.uvs;
  38067. }
  38068. if (this.uvs2) {
  38069. serializationObject.uvs2 = this.uvs2;
  38070. }
  38071. if (this.uvs3) {
  38072. serializationObject.uvs3 = this.uvs3;
  38073. }
  38074. if (this.uvs4) {
  38075. serializationObject.uvs4 = this.uvs4;
  38076. }
  38077. if (this.uvs5) {
  38078. serializationObject.uvs5 = this.uvs5;
  38079. }
  38080. if (this.uvs6) {
  38081. serializationObject.uvs6 = this.uvs6;
  38082. }
  38083. if (this.colors) {
  38084. serializationObject.colors = this.colors;
  38085. }
  38086. if (this.matricesIndices) {
  38087. serializationObject.matricesIndices = this.matricesIndices;
  38088. serializationObject.matricesIndices._isExpanded = true;
  38089. }
  38090. if (this.matricesWeights) {
  38091. serializationObject.matricesWeights = this.matricesWeights;
  38092. }
  38093. if (this.matricesIndicesExtra) {
  38094. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  38095. serializationObject.matricesIndicesExtra._isExpanded = true;
  38096. }
  38097. if (this.matricesWeightsExtra) {
  38098. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  38099. }
  38100. serializationObject.indices = this.indices;
  38101. return serializationObject;
  38102. };
  38103. // Statics
  38104. /**
  38105. * Extracts the vertexData from a mesh
  38106. * @param mesh the mesh from which to extract the VertexData
  38107. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  38108. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  38109. * @returns the object VertexData associated to the passed mesh
  38110. */
  38111. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  38112. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  38113. };
  38114. /**
  38115. * Extracts the vertexData from the geometry
  38116. * @param geometry the geometry from which to extract the VertexData
  38117. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  38118. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  38119. * @returns the object VertexData associated to the passed mesh
  38120. */
  38121. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  38122. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  38123. };
  38124. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  38125. var result = new VertexData();
  38126. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38127. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  38128. }
  38129. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38130. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  38131. }
  38132. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38133. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  38134. }
  38135. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38136. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  38137. }
  38138. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38139. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  38140. }
  38141. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38142. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  38143. }
  38144. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38145. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  38146. }
  38147. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38148. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  38149. }
  38150. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38151. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  38152. }
  38153. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38154. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  38155. }
  38156. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38157. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  38158. }
  38159. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38160. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  38161. }
  38162. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  38163. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  38164. }
  38165. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  38166. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  38167. }
  38168. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  38169. return result;
  38170. };
  38171. /**
  38172. * Creates the VertexData for a Ribbon
  38173. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  38174. * * pathArray array of paths, each of which an array of successive Vector3
  38175. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  38176. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  38177. * * 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
  38178. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38179. * * 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)
  38180. * * 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)
  38181. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  38182. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  38183. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  38184. * @returns the VertexData of the ribbon
  38185. */
  38186. VertexData.CreateRibbon = function (options) {
  38187. var pathArray = options.pathArray;
  38188. var closeArray = options.closeArray || false;
  38189. var closePath = options.closePath || false;
  38190. var invertUV = options.invertUV || false;
  38191. var defaultOffset = Math.floor(pathArray[0].length / 2);
  38192. var offset = options.offset || defaultOffset;
  38193. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  38194. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38195. var customUV = options.uvs;
  38196. var customColors = options.colors;
  38197. var positions = [];
  38198. var indices = [];
  38199. var normals = [];
  38200. var uvs = [];
  38201. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  38202. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  38203. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  38204. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  38205. var minlg; // minimal length among all paths from pathArray
  38206. var lg = []; // array of path lengths : nb of vertex per path
  38207. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  38208. var p; // path iterator
  38209. var i; // point iterator
  38210. var j; // point iterator
  38211. // if single path in pathArray
  38212. if (pathArray.length < 2) {
  38213. var ar1 = [];
  38214. var ar2 = [];
  38215. for (i = 0; i < pathArray[0].length - offset; i++) {
  38216. ar1.push(pathArray[0][i]);
  38217. ar2.push(pathArray[0][i + offset]);
  38218. }
  38219. pathArray = [ar1, ar2];
  38220. }
  38221. // positions and horizontal distances (u)
  38222. var idc = 0;
  38223. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  38224. var path;
  38225. var l;
  38226. minlg = pathArray[0].length;
  38227. var vectlg;
  38228. var dist;
  38229. for (p = 0; p < pathArray.length; p++) {
  38230. uTotalDistance[p] = 0;
  38231. us[p] = [0];
  38232. path = pathArray[p];
  38233. l = path.length;
  38234. minlg = (minlg < l) ? minlg : l;
  38235. j = 0;
  38236. while (j < l) {
  38237. positions.push(path[j].x, path[j].y, path[j].z);
  38238. if (j > 0) {
  38239. vectlg = path[j].subtract(path[j - 1]).length();
  38240. dist = vectlg + uTotalDistance[p];
  38241. us[p].push(dist);
  38242. uTotalDistance[p] = dist;
  38243. }
  38244. j++;
  38245. }
  38246. if (closePath) { // an extra hidden vertex is added in the "positions" array
  38247. j--;
  38248. positions.push(path[0].x, path[0].y, path[0].z);
  38249. vectlg = path[j].subtract(path[0]).length();
  38250. dist = vectlg + uTotalDistance[p];
  38251. us[p].push(dist);
  38252. uTotalDistance[p] = dist;
  38253. }
  38254. lg[p] = l + closePathCorr;
  38255. idx[p] = idc;
  38256. idc += (l + closePathCorr);
  38257. }
  38258. // vertical distances (v)
  38259. var path1;
  38260. var path2;
  38261. var vertex1 = null;
  38262. var vertex2 = null;
  38263. for (i = 0; i < minlg + closePathCorr; i++) {
  38264. vTotalDistance[i] = 0;
  38265. vs[i] = [0];
  38266. for (p = 0; p < pathArray.length - 1; p++) {
  38267. path1 = pathArray[p];
  38268. path2 = pathArray[p + 1];
  38269. if (i === minlg) { // closePath
  38270. vertex1 = path1[0];
  38271. vertex2 = path2[0];
  38272. }
  38273. else {
  38274. vertex1 = path1[i];
  38275. vertex2 = path2[i];
  38276. }
  38277. vectlg = vertex2.subtract(vertex1).length();
  38278. dist = vectlg + vTotalDistance[i];
  38279. vs[i].push(dist);
  38280. vTotalDistance[i] = dist;
  38281. }
  38282. if (closeArray && vertex2 && vertex1) {
  38283. path1 = pathArray[p];
  38284. path2 = pathArray[0];
  38285. if (i === minlg) { // closePath
  38286. vertex2 = path2[0];
  38287. }
  38288. vectlg = vertex2.subtract(vertex1).length();
  38289. dist = vectlg + vTotalDistance[i];
  38290. vTotalDistance[i] = dist;
  38291. }
  38292. }
  38293. // uvs
  38294. var u;
  38295. var v;
  38296. if (customUV) {
  38297. for (p = 0; p < customUV.length; p++) {
  38298. uvs.push(customUV[p].x, customUV[p].y);
  38299. }
  38300. }
  38301. else {
  38302. for (p = 0; p < pathArray.length; p++) {
  38303. for (i = 0; i < minlg + closePathCorr; i++) {
  38304. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  38305. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  38306. if (invertUV) {
  38307. uvs.push(v, u);
  38308. }
  38309. else {
  38310. uvs.push(u, v);
  38311. }
  38312. }
  38313. }
  38314. }
  38315. // indices
  38316. p = 0; // path index
  38317. var pi = 0; // positions array index
  38318. var l1 = lg[p] - 1; // path1 length
  38319. var l2 = lg[p + 1] - 1; // path2 length
  38320. var min = (l1 < l2) ? l1 : l2; // current path stop index
  38321. var shft = idx[1] - idx[0]; // shift
  38322. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  38323. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  38324. // 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
  38325. indices.push(pi, pi + shft, pi + 1);
  38326. indices.push(pi + shft + 1, pi + 1, pi + shft);
  38327. pi += 1;
  38328. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  38329. p++;
  38330. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  38331. shft = idx[0] - idx[p];
  38332. l1 = lg[p] - 1;
  38333. l2 = lg[0] - 1;
  38334. }
  38335. else {
  38336. shft = idx[p + 1] - idx[p];
  38337. l1 = lg[p] - 1;
  38338. l2 = lg[p + 1] - 1;
  38339. }
  38340. pi = idx[p];
  38341. min = (l1 < l2) ? l1 + pi : l2 + pi;
  38342. }
  38343. }
  38344. // normals
  38345. VertexData.ComputeNormals(positions, indices, normals);
  38346. if (closePath) { // update both the first and last vertex normals to their average value
  38347. var indexFirst = 0;
  38348. var indexLast = 0;
  38349. for (p = 0; p < pathArray.length; p++) {
  38350. indexFirst = idx[p] * 3;
  38351. if (p + 1 < pathArray.length) {
  38352. indexLast = (idx[p + 1] - 1) * 3;
  38353. }
  38354. else {
  38355. indexLast = normals.length - 3;
  38356. }
  38357. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  38358. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  38359. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  38360. normals[indexLast] = normals[indexFirst];
  38361. normals[indexLast + 1] = normals[indexFirst + 1];
  38362. normals[indexLast + 2] = normals[indexFirst + 2];
  38363. }
  38364. }
  38365. // sides
  38366. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38367. // Colors
  38368. var colors = null;
  38369. if (customColors) {
  38370. colors = new Float32Array(customColors.length * 4);
  38371. for (var c = 0; c < customColors.length; c++) {
  38372. colors[c * 4] = customColors[c].r;
  38373. colors[c * 4 + 1] = customColors[c].g;
  38374. colors[c * 4 + 2] = customColors[c].b;
  38375. colors[c * 4 + 3] = customColors[c].a;
  38376. }
  38377. }
  38378. // Result
  38379. var vertexData = new VertexData();
  38380. var positions32 = new Float32Array(positions);
  38381. var normals32 = new Float32Array(normals);
  38382. var uvs32 = new Float32Array(uvs);
  38383. vertexData.indices = indices;
  38384. vertexData.positions = positions32;
  38385. vertexData.normals = normals32;
  38386. vertexData.uvs = uvs32;
  38387. if (colors) {
  38388. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  38389. }
  38390. if (closePath) {
  38391. vertexData._idx = idx;
  38392. }
  38393. return vertexData;
  38394. };
  38395. /**
  38396. * Creates the VertexData for a box
  38397. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38398. * * size sets the width, height and depth of the box to the value of size, optional default 1
  38399. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  38400. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  38401. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  38402. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  38403. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  38404. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38405. * * 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)
  38406. * * 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)
  38407. * @returns the VertexData of the box
  38408. */
  38409. VertexData.CreateBox = function (options) {
  38410. var normalsSource = [
  38411. new BABYLON.Vector3(0, 0, 1),
  38412. new BABYLON.Vector3(0, 0, -1),
  38413. new BABYLON.Vector3(1, 0, 0),
  38414. new BABYLON.Vector3(-1, 0, 0),
  38415. new BABYLON.Vector3(0, 1, 0),
  38416. new BABYLON.Vector3(0, -1, 0)
  38417. ];
  38418. var indices = [];
  38419. var positions = [];
  38420. var normals = [];
  38421. var uvs = [];
  38422. var width = options.width || options.size || 1;
  38423. var height = options.height || options.size || 1;
  38424. var depth = options.depth || options.size || 1;
  38425. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38426. var faceUV = options.faceUV || new Array(6);
  38427. var faceColors = options.faceColors;
  38428. var colors = [];
  38429. // default face colors and UV if undefined
  38430. for (var f = 0; f < 6; f++) {
  38431. if (faceUV[f] === undefined) {
  38432. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38433. }
  38434. if (faceColors && faceColors[f] === undefined) {
  38435. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38436. }
  38437. }
  38438. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  38439. // Create each face in turn.
  38440. for (var index = 0; index < normalsSource.length; index++) {
  38441. var normal = normalsSource[index];
  38442. // Get two vectors perpendicular to the face normal and to each other.
  38443. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  38444. var side2 = BABYLON.Vector3.Cross(normal, side1);
  38445. // Six indices (two triangles) per face.
  38446. var verticesLength = positions.length / 3;
  38447. indices.push(verticesLength);
  38448. indices.push(verticesLength + 1);
  38449. indices.push(verticesLength + 2);
  38450. indices.push(verticesLength);
  38451. indices.push(verticesLength + 2);
  38452. indices.push(verticesLength + 3);
  38453. // Four vertices per face.
  38454. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  38455. positions.push(vertex.x, vertex.y, vertex.z);
  38456. normals.push(normal.x, normal.y, normal.z);
  38457. uvs.push(faceUV[index].z, faceUV[index].w);
  38458. if (faceColors) {
  38459. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38460. }
  38461. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  38462. positions.push(vertex.x, vertex.y, vertex.z);
  38463. normals.push(normal.x, normal.y, normal.z);
  38464. uvs.push(faceUV[index].x, faceUV[index].w);
  38465. if (faceColors) {
  38466. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38467. }
  38468. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  38469. positions.push(vertex.x, vertex.y, vertex.z);
  38470. normals.push(normal.x, normal.y, normal.z);
  38471. uvs.push(faceUV[index].x, faceUV[index].y);
  38472. if (faceColors) {
  38473. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38474. }
  38475. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  38476. positions.push(vertex.x, vertex.y, vertex.z);
  38477. normals.push(normal.x, normal.y, normal.z);
  38478. uvs.push(faceUV[index].z, faceUV[index].y);
  38479. if (faceColors) {
  38480. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38481. }
  38482. }
  38483. // sides
  38484. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38485. // Result
  38486. var vertexData = new VertexData();
  38487. vertexData.indices = indices;
  38488. vertexData.positions = positions;
  38489. vertexData.normals = normals;
  38490. vertexData.uvs = uvs;
  38491. if (faceColors) {
  38492. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38493. vertexData.colors = totalColors;
  38494. }
  38495. return vertexData;
  38496. };
  38497. /**
  38498. * Creates the VertexData for an ellipsoid, defaults to a sphere
  38499. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38500. * * segments sets the number of horizontal strips optional, default 32
  38501. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  38502. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  38503. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  38504. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  38505. * * 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
  38506. * * 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
  38507. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38508. * * 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)
  38509. * * 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)
  38510. * @returns the VertexData of the ellipsoid
  38511. */
  38512. VertexData.CreateSphere = function (options) {
  38513. var segments = options.segments || 32;
  38514. var diameterX = options.diameterX || options.diameter || 1;
  38515. var diameterY = options.diameterY || options.diameter || 1;
  38516. var diameterZ = options.diameterZ || options.diameter || 1;
  38517. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38518. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  38519. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38520. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  38521. var totalZRotationSteps = 2 + segments;
  38522. var totalYRotationSteps = 2 * totalZRotationSteps;
  38523. var indices = [];
  38524. var positions = [];
  38525. var normals = [];
  38526. var uvs = [];
  38527. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  38528. var normalizedZ = zRotationStep / totalZRotationSteps;
  38529. var angleZ = normalizedZ * Math.PI * slice;
  38530. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  38531. var normalizedY = yRotationStep / totalYRotationSteps;
  38532. var angleY = normalizedY * Math.PI * 2 * arc;
  38533. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  38534. var rotationY = BABYLON.Matrix.RotationY(angleY);
  38535. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  38536. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  38537. var vertex = complete.multiply(radius);
  38538. var normal = complete.divide(radius).normalize();
  38539. positions.push(vertex.x, vertex.y, vertex.z);
  38540. normals.push(normal.x, normal.y, normal.z);
  38541. uvs.push(normalizedY, normalizedZ);
  38542. }
  38543. if (zRotationStep > 0) {
  38544. var verticesCount = positions.length / 3;
  38545. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  38546. indices.push((firstIndex));
  38547. indices.push((firstIndex + 1));
  38548. indices.push(firstIndex + totalYRotationSteps + 1);
  38549. indices.push((firstIndex + totalYRotationSteps + 1));
  38550. indices.push((firstIndex + 1));
  38551. indices.push((firstIndex + totalYRotationSteps + 2));
  38552. }
  38553. }
  38554. }
  38555. // Sides
  38556. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38557. // Result
  38558. var vertexData = new VertexData();
  38559. vertexData.indices = indices;
  38560. vertexData.positions = positions;
  38561. vertexData.normals = normals;
  38562. vertexData.uvs = uvs;
  38563. return vertexData;
  38564. };
  38565. /**
  38566. * Creates the VertexData for a cylinder, cone or prism
  38567. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38568. * * height sets the height (y direction) of the cylinder, optional, default 2
  38569. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  38570. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  38571. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  38572. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38573. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  38574. * * 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
  38575. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38576. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38577. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  38578. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  38579. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38580. * * 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)
  38581. * * 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)
  38582. * @returns the VertexData of the cylinder, cone or prism
  38583. */
  38584. VertexData.CreateCylinder = function (options) {
  38585. var height = options.height || 2;
  38586. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  38587. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  38588. var tessellation = options.tessellation || 24;
  38589. var subdivisions = options.subdivisions || 1;
  38590. var hasRings = options.hasRings ? true : false;
  38591. var enclose = options.enclose ? true : false;
  38592. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38593. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38594. var faceUV = options.faceUV || new Array(3);
  38595. var faceColors = options.faceColors;
  38596. // default face colors and UV if undefined
  38597. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  38598. var ringNb = (hasRings) ? subdivisions : 1;
  38599. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  38600. var f;
  38601. for (f = 0; f < surfaceNb; f++) {
  38602. if (faceColors && faceColors[f] === undefined) {
  38603. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38604. }
  38605. }
  38606. for (f = 0; f < surfaceNb; f++) {
  38607. if (faceUV && faceUV[f] === undefined) {
  38608. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38609. }
  38610. }
  38611. var indices = new Array();
  38612. var positions = new Array();
  38613. var normals = new Array();
  38614. var uvs = new Array();
  38615. var colors = new Array();
  38616. var angle_step = Math.PI * 2 * arc / tessellation;
  38617. var angle;
  38618. var h;
  38619. var radius;
  38620. var tan = (diameterBottom - diameterTop) / 2 / height;
  38621. var ringVertex = BABYLON.Vector3.Zero();
  38622. var ringNormal = BABYLON.Vector3.Zero();
  38623. var ringFirstVertex = BABYLON.Vector3.Zero();
  38624. var ringFirstNormal = BABYLON.Vector3.Zero();
  38625. var quadNormal = BABYLON.Vector3.Zero();
  38626. var Y = BABYLON.Axis.Y;
  38627. // positions, normals, uvs
  38628. var i;
  38629. var j;
  38630. var r;
  38631. var ringIdx = 1;
  38632. var s = 1; // surface index
  38633. var cs = 0;
  38634. var v = 0;
  38635. for (i = 0; i <= subdivisions; i++) {
  38636. h = i / subdivisions;
  38637. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  38638. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  38639. for (r = 0; r < ringIdx; r++) {
  38640. if (hasRings) {
  38641. s += r;
  38642. }
  38643. if (enclose) {
  38644. s += 2 * r;
  38645. }
  38646. for (j = 0; j <= tessellation; j++) {
  38647. angle = j * angle_step;
  38648. // position
  38649. ringVertex.x = Math.cos(-angle) * radius;
  38650. ringVertex.y = -height / 2 + h * height;
  38651. ringVertex.z = Math.sin(-angle) * radius;
  38652. // normal
  38653. if (diameterTop === 0 && i === subdivisions) {
  38654. // if no top cap, reuse former normals
  38655. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  38656. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  38657. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  38658. }
  38659. else {
  38660. ringNormal.x = ringVertex.x;
  38661. ringNormal.z = ringVertex.z;
  38662. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  38663. ringNormal.normalize();
  38664. }
  38665. // keep first ring vertex values for enclose
  38666. if (j === 0) {
  38667. ringFirstVertex.copyFrom(ringVertex);
  38668. ringFirstNormal.copyFrom(ringNormal);
  38669. }
  38670. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38671. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  38672. if (hasRings) {
  38673. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  38674. }
  38675. else {
  38676. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  38677. }
  38678. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  38679. if (faceColors) {
  38680. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  38681. }
  38682. }
  38683. // if enclose, add four vertices and their dedicated normals
  38684. if (arc !== 1 && enclose) {
  38685. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38686. positions.push(0, ringVertex.y, 0);
  38687. positions.push(0, ringVertex.y, 0);
  38688. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  38689. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  38690. quadNormal.normalize();
  38691. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38692. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  38693. quadNormal.normalize();
  38694. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38695. if (hasRings) {
  38696. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  38697. }
  38698. else {
  38699. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  38700. }
  38701. uvs.push(faceUV[s + 1].x, v);
  38702. uvs.push(faceUV[s + 1].z, v);
  38703. if (hasRings) {
  38704. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  38705. }
  38706. else {
  38707. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  38708. }
  38709. uvs.push(faceUV[s + 2].x, v);
  38710. uvs.push(faceUV[s + 2].z, v);
  38711. if (faceColors) {
  38712. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38713. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38714. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38715. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38716. }
  38717. }
  38718. if (cs !== s) {
  38719. cs = s;
  38720. }
  38721. }
  38722. }
  38723. // indices
  38724. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  38725. var s;
  38726. i = 0;
  38727. for (s = 0; s < subdivisions; s++) {
  38728. var i0 = 0;
  38729. var i1 = 0;
  38730. var i2 = 0;
  38731. var i3 = 0;
  38732. for (j = 0; j < tessellation; j++) {
  38733. i0 = i * (e + 1) + j;
  38734. i1 = (i + 1) * (e + 1) + j;
  38735. i2 = i * (e + 1) + (j + 1);
  38736. i3 = (i + 1) * (e + 1) + (j + 1);
  38737. indices.push(i0, i1, i2);
  38738. indices.push(i3, i2, i1);
  38739. }
  38740. if (arc !== 1 && enclose) { // if enclose, add two quads
  38741. indices.push(i0 + 2, i1 + 2, i2 + 2);
  38742. indices.push(i3 + 2, i2 + 2, i1 + 2);
  38743. indices.push(i0 + 4, i1 + 4, i2 + 4);
  38744. indices.push(i3 + 4, i2 + 4, i1 + 4);
  38745. }
  38746. i = (hasRings) ? (i + 2) : (i + 1);
  38747. }
  38748. // Caps
  38749. var createCylinderCap = function (isTop) {
  38750. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  38751. if (radius === 0) {
  38752. return;
  38753. }
  38754. // Cap positions, normals & uvs
  38755. var angle;
  38756. var circleVector;
  38757. var i;
  38758. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  38759. var c = null;
  38760. if (faceColors) {
  38761. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  38762. }
  38763. // cap center
  38764. var vbase = positions.length / 3;
  38765. var offset = isTop ? height / 2 : -height / 2;
  38766. var center = new BABYLON.Vector3(0, offset, 0);
  38767. positions.push(center.x, center.y, center.z);
  38768. normals.push(0, isTop ? 1 : -1, 0);
  38769. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  38770. if (c) {
  38771. colors.push(c.r, c.g, c.b, c.a);
  38772. }
  38773. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  38774. for (i = 0; i <= tessellation; i++) {
  38775. angle = Math.PI * 2 * i * arc / tessellation;
  38776. var cos = Math.cos(-angle);
  38777. var sin = Math.sin(-angle);
  38778. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  38779. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  38780. positions.push(circleVector.x, circleVector.y, circleVector.z);
  38781. normals.push(0, isTop ? 1 : -1, 0);
  38782. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  38783. if (c) {
  38784. colors.push(c.r, c.g, c.b, c.a);
  38785. }
  38786. }
  38787. // Cap indices
  38788. for (i = 0; i < tessellation; i++) {
  38789. if (!isTop) {
  38790. indices.push(vbase);
  38791. indices.push(vbase + (i + 1));
  38792. indices.push(vbase + (i + 2));
  38793. }
  38794. else {
  38795. indices.push(vbase);
  38796. indices.push(vbase + (i + 2));
  38797. indices.push(vbase + (i + 1));
  38798. }
  38799. }
  38800. };
  38801. // add caps to geometry
  38802. createCylinderCap(false);
  38803. createCylinderCap(true);
  38804. // Sides
  38805. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38806. var vertexData = new VertexData();
  38807. vertexData.indices = indices;
  38808. vertexData.positions = positions;
  38809. vertexData.normals = normals;
  38810. vertexData.uvs = uvs;
  38811. if (faceColors) {
  38812. vertexData.colors = colors;
  38813. }
  38814. return vertexData;
  38815. };
  38816. /**
  38817. * Creates the VertexData for a torus
  38818. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38819. * * diameter the diameter of the torus, optional default 1
  38820. * * thickness the diameter of the tube forming the torus, optional default 0.5
  38821. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38822. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38823. * * 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)
  38824. * * 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)
  38825. * @returns the VertexData of the torus
  38826. */
  38827. VertexData.CreateTorus = function (options) {
  38828. var indices = [];
  38829. var positions = [];
  38830. var normals = [];
  38831. var uvs = [];
  38832. var diameter = options.diameter || 1;
  38833. var thickness = options.thickness || 0.5;
  38834. var tessellation = options.tessellation || 16;
  38835. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38836. var stride = tessellation + 1;
  38837. for (var i = 0; i <= tessellation; i++) {
  38838. var u = i / tessellation;
  38839. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  38840. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  38841. for (var j = 0; j <= tessellation; j++) {
  38842. var v = 1 - j / tessellation;
  38843. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  38844. var dx = Math.cos(innerAngle);
  38845. var dy = Math.sin(innerAngle);
  38846. // Create a vertex.
  38847. var normal = new BABYLON.Vector3(dx, dy, 0);
  38848. var position = normal.scale(thickness / 2);
  38849. var textureCoordinate = new BABYLON.Vector2(u, v);
  38850. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  38851. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  38852. positions.push(position.x, position.y, position.z);
  38853. normals.push(normal.x, normal.y, normal.z);
  38854. uvs.push(textureCoordinate.x, textureCoordinate.y);
  38855. // And create indices for two triangles.
  38856. var nextI = (i + 1) % stride;
  38857. var nextJ = (j + 1) % stride;
  38858. indices.push(i * stride + j);
  38859. indices.push(i * stride + nextJ);
  38860. indices.push(nextI * stride + j);
  38861. indices.push(i * stride + nextJ);
  38862. indices.push(nextI * stride + nextJ);
  38863. indices.push(nextI * stride + j);
  38864. }
  38865. }
  38866. // Sides
  38867. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38868. // Result
  38869. var vertexData = new VertexData();
  38870. vertexData.indices = indices;
  38871. vertexData.positions = positions;
  38872. vertexData.normals = normals;
  38873. vertexData.uvs = uvs;
  38874. return vertexData;
  38875. };
  38876. /**
  38877. * Creates the VertexData of the LineSystem
  38878. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  38879. * - lines an array of lines, each line being an array of successive Vector3
  38880. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  38881. * @returns the VertexData of the LineSystem
  38882. */
  38883. VertexData.CreateLineSystem = function (options) {
  38884. var indices = [];
  38885. var positions = [];
  38886. var lines = options.lines;
  38887. var colors = options.colors;
  38888. var vertexColors = [];
  38889. var idx = 0;
  38890. for (var l = 0; l < lines.length; l++) {
  38891. var points = lines[l];
  38892. for (var index = 0; index < points.length; index++) {
  38893. positions.push(points[index].x, points[index].y, points[index].z);
  38894. if (colors) {
  38895. var color = colors[l];
  38896. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  38897. }
  38898. if (index > 0) {
  38899. indices.push(idx - 1);
  38900. indices.push(idx);
  38901. }
  38902. idx++;
  38903. }
  38904. }
  38905. var vertexData = new VertexData();
  38906. vertexData.indices = indices;
  38907. vertexData.positions = positions;
  38908. if (colors) {
  38909. vertexData.colors = vertexColors;
  38910. }
  38911. return vertexData;
  38912. };
  38913. /**
  38914. * Create the VertexData for a DashedLines
  38915. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  38916. * - points an array successive Vector3
  38917. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  38918. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  38919. * - dashNb the intended total number of dashes, optional, default 200
  38920. * @returns the VertexData for the DashedLines
  38921. */
  38922. VertexData.CreateDashedLines = function (options) {
  38923. var dashSize = options.dashSize || 3;
  38924. var gapSize = options.gapSize || 1;
  38925. var dashNb = options.dashNb || 200;
  38926. var points = options.points;
  38927. var positions = new Array();
  38928. var indices = new Array();
  38929. var curvect = BABYLON.Vector3.Zero();
  38930. var lg = 0;
  38931. var nb = 0;
  38932. var shft = 0;
  38933. var dashshft = 0;
  38934. var curshft = 0;
  38935. var idx = 0;
  38936. var i = 0;
  38937. for (i = 0; i < points.length - 1; i++) {
  38938. points[i + 1].subtractToRef(points[i], curvect);
  38939. lg += curvect.length();
  38940. }
  38941. shft = lg / dashNb;
  38942. dashshft = dashSize * shft / (dashSize + gapSize);
  38943. for (i = 0; i < points.length - 1; i++) {
  38944. points[i + 1].subtractToRef(points[i], curvect);
  38945. nb = Math.floor(curvect.length() / shft);
  38946. curvect.normalize();
  38947. for (var j = 0; j < nb; j++) {
  38948. curshft = shft * j;
  38949. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  38950. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  38951. indices.push(idx, idx + 1);
  38952. idx += 2;
  38953. }
  38954. }
  38955. // Result
  38956. var vertexData = new VertexData();
  38957. vertexData.positions = positions;
  38958. vertexData.indices = indices;
  38959. return vertexData;
  38960. };
  38961. /**
  38962. * Creates the VertexData for a Ground
  38963. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38964. * - width the width (x direction) of the ground, optional, default 1
  38965. * - height the height (z direction) of the ground, optional, default 1
  38966. * - subdivisions the number of subdivisions per side, optional, default 1
  38967. * @returns the VertexData of the Ground
  38968. */
  38969. VertexData.CreateGround = function (options) {
  38970. var indices = [];
  38971. var positions = [];
  38972. var normals = [];
  38973. var uvs = [];
  38974. var row, col;
  38975. var width = options.width || 1;
  38976. var height = options.height || 1;
  38977. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  38978. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  38979. for (row = 0; row <= subdivisionsY; row++) {
  38980. for (col = 0; col <= subdivisionsX; col++) {
  38981. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  38982. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38983. positions.push(position.x, position.y, position.z);
  38984. normals.push(normal.x, normal.y, normal.z);
  38985. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  38986. }
  38987. }
  38988. for (row = 0; row < subdivisionsY; row++) {
  38989. for (col = 0; col < subdivisionsX; col++) {
  38990. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38991. indices.push(col + 1 + row * (subdivisionsX + 1));
  38992. indices.push(col + row * (subdivisionsX + 1));
  38993. indices.push(col + (row + 1) * (subdivisionsX + 1));
  38994. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38995. indices.push(col + row * (subdivisionsX + 1));
  38996. }
  38997. }
  38998. // Result
  38999. var vertexData = new VertexData();
  39000. vertexData.indices = indices;
  39001. vertexData.positions = positions;
  39002. vertexData.normals = normals;
  39003. vertexData.uvs = uvs;
  39004. return vertexData;
  39005. };
  39006. /**
  39007. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  39008. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  39009. * * xmin the ground minimum X coordinate, optional, default -1
  39010. * * zmin the ground minimum Z coordinate, optional, default -1
  39011. * * xmax the ground maximum X coordinate, optional, default 1
  39012. * * zmax the ground maximum Z coordinate, optional, default 1
  39013. * * 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}
  39014. * * 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}
  39015. * @returns the VertexData of the TiledGround
  39016. */
  39017. VertexData.CreateTiledGround = function (options) {
  39018. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  39019. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  39020. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  39021. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  39022. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  39023. var precision = options.precision || { w: 1, h: 1 };
  39024. var indices = new Array();
  39025. var positions = new Array();
  39026. var normals = new Array();
  39027. var uvs = new Array();
  39028. var row, col, tileRow, tileCol;
  39029. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  39030. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  39031. precision.w = (precision.w < 1) ? 1 : precision.w;
  39032. precision.h = (precision.h < 1) ? 1 : precision.h;
  39033. var tileSize = {
  39034. 'w': (xmax - xmin) / subdivisions.w,
  39035. 'h': (zmax - zmin) / subdivisions.h
  39036. };
  39037. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  39038. // Indices
  39039. var base = positions.length / 3;
  39040. var rowLength = precision.w + 1;
  39041. for (row = 0; row < precision.h; row++) {
  39042. for (col = 0; col < precision.w; col++) {
  39043. var square = [
  39044. base + col + row * rowLength,
  39045. base + (col + 1) + row * rowLength,
  39046. base + (col + 1) + (row + 1) * rowLength,
  39047. base + col + (row + 1) * rowLength
  39048. ];
  39049. indices.push(square[1]);
  39050. indices.push(square[2]);
  39051. indices.push(square[3]);
  39052. indices.push(square[0]);
  39053. indices.push(square[1]);
  39054. indices.push(square[3]);
  39055. }
  39056. }
  39057. // Position, normals and uvs
  39058. var position = BABYLON.Vector3.Zero();
  39059. var normal = new BABYLON.Vector3(0, 1.0, 0);
  39060. for (row = 0; row <= precision.h; row++) {
  39061. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  39062. for (col = 0; col <= precision.w; col++) {
  39063. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  39064. position.y = 0;
  39065. positions.push(position.x, position.y, position.z);
  39066. normals.push(normal.x, normal.y, normal.z);
  39067. uvs.push(col / precision.w, row / precision.h);
  39068. }
  39069. }
  39070. }
  39071. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  39072. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  39073. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  39074. }
  39075. }
  39076. // Result
  39077. var vertexData = new VertexData();
  39078. vertexData.indices = indices;
  39079. vertexData.positions = positions;
  39080. vertexData.normals = normals;
  39081. vertexData.uvs = uvs;
  39082. return vertexData;
  39083. };
  39084. /**
  39085. * Creates the VertexData of the Ground designed from a heightmap
  39086. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  39087. * * width the width (x direction) of the ground
  39088. * * height the height (z direction) of the ground
  39089. * * subdivisions the number of subdivisions per side
  39090. * * minHeight the minimum altitude on the ground, optional, default 0
  39091. * * maxHeight the maximum altitude on the ground, optional default 1
  39092. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  39093. * * buffer the array holding the image color data
  39094. * * bufferWidth the width of image
  39095. * * bufferHeight the height of image
  39096. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  39097. * @returns the VertexData of the Ground designed from a heightmap
  39098. */
  39099. VertexData.CreateGroundFromHeightMap = function (options) {
  39100. var indices = [];
  39101. var positions = [];
  39102. var normals = [];
  39103. var uvs = [];
  39104. var row, col;
  39105. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  39106. var alphaFilter = options.alphaFilter || 0.0;
  39107. // Vertices
  39108. for (row = 0; row <= options.subdivisions; row++) {
  39109. for (col = 0; col <= options.subdivisions; col++) {
  39110. 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));
  39111. // Compute height
  39112. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  39113. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  39114. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  39115. var r = options.buffer[pos] / 255.0;
  39116. var g = options.buffer[pos + 1] / 255.0;
  39117. var b = options.buffer[pos + 2] / 255.0;
  39118. var a = options.buffer[pos + 3] / 255.0;
  39119. var gradient = r * filter.r + g * filter.g + b * filter.b;
  39120. // If our alpha channel is not within our filter then we will assign a 'special' height
  39121. // Then when building the indices, we will ignore any vertex that is using the special height
  39122. if (a >= alphaFilter) {
  39123. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  39124. }
  39125. else {
  39126. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  39127. }
  39128. // Add vertex
  39129. positions.push(position.x, position.y, position.z);
  39130. normals.push(0, 0, 0);
  39131. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  39132. }
  39133. }
  39134. // Indices
  39135. for (row = 0; row < options.subdivisions; row++) {
  39136. for (col = 0; col < options.subdivisions; col++) {
  39137. // Calculate Indices
  39138. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  39139. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  39140. var idx3 = (col + row * (options.subdivisions + 1));
  39141. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  39142. // Check that all indices are visible (based on our special height)
  39143. // Only display the vertex if all Indices are visible
  39144. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  39145. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  39146. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  39147. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  39148. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  39149. indices.push(idx1);
  39150. indices.push(idx2);
  39151. indices.push(idx3);
  39152. }
  39153. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  39154. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  39155. indices.push(idx4);
  39156. indices.push(idx1);
  39157. indices.push(idx3);
  39158. }
  39159. }
  39160. }
  39161. // Normals
  39162. VertexData.ComputeNormals(positions, indices, normals);
  39163. // Result
  39164. var vertexData = new VertexData();
  39165. vertexData.indices = indices;
  39166. vertexData.positions = positions;
  39167. vertexData.normals = normals;
  39168. vertexData.uvs = uvs;
  39169. return vertexData;
  39170. };
  39171. /**
  39172. * Creates the VertexData for a Plane
  39173. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  39174. * * size sets the width and height of the plane to the value of size, optional default 1
  39175. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  39176. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  39177. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39178. * * 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)
  39179. * * 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)
  39180. * @returns the VertexData of the box
  39181. */
  39182. VertexData.CreatePlane = function (options) {
  39183. var indices = [];
  39184. var positions = [];
  39185. var normals = [];
  39186. var uvs = [];
  39187. var width = options.width || options.size || 1;
  39188. var height = options.height || options.size || 1;
  39189. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39190. // Vertices
  39191. var halfWidth = width / 2.0;
  39192. var halfHeight = height / 2.0;
  39193. positions.push(-halfWidth, -halfHeight, 0);
  39194. normals.push(0, 0, -1.0);
  39195. uvs.push(0.0, 0.0);
  39196. positions.push(halfWidth, -halfHeight, 0);
  39197. normals.push(0, 0, -1.0);
  39198. uvs.push(1.0, 0.0);
  39199. positions.push(halfWidth, halfHeight, 0);
  39200. normals.push(0, 0, -1.0);
  39201. uvs.push(1.0, 1.0);
  39202. positions.push(-halfWidth, halfHeight, 0);
  39203. normals.push(0, 0, -1.0);
  39204. uvs.push(0.0, 1.0);
  39205. // Indices
  39206. indices.push(0);
  39207. indices.push(1);
  39208. indices.push(2);
  39209. indices.push(0);
  39210. indices.push(2);
  39211. indices.push(3);
  39212. // Sides
  39213. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39214. // Result
  39215. var vertexData = new VertexData();
  39216. vertexData.indices = indices;
  39217. vertexData.positions = positions;
  39218. vertexData.normals = normals;
  39219. vertexData.uvs = uvs;
  39220. return vertexData;
  39221. };
  39222. /**
  39223. * Creates the VertexData of the Disc or regular Polygon
  39224. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  39225. * * radius the radius of the disc, optional default 0.5
  39226. * * tessellation the number of polygon sides, optional, default 64
  39227. * * 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
  39228. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39229. * * 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)
  39230. * * 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)
  39231. * @returns the VertexData of the box
  39232. */
  39233. VertexData.CreateDisc = function (options) {
  39234. var positions = new Array();
  39235. var indices = new Array();
  39236. var normals = new Array();
  39237. var uvs = new Array();
  39238. var radius = options.radius || 0.5;
  39239. var tessellation = options.tessellation || 64;
  39240. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  39241. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39242. // positions and uvs
  39243. positions.push(0, 0, 0); // disc center first
  39244. uvs.push(0.5, 0.5);
  39245. var theta = Math.PI * 2 * arc;
  39246. var step = theta / tessellation;
  39247. for (var a = 0; a < theta; a += step) {
  39248. var x = Math.cos(a);
  39249. var y = Math.sin(a);
  39250. var u = (x + 1) / 2;
  39251. var v = (1 - y) / 2;
  39252. positions.push(radius * x, radius * y, 0);
  39253. uvs.push(u, v);
  39254. }
  39255. if (arc === 1) {
  39256. positions.push(positions[3], positions[4], positions[5]); // close the circle
  39257. uvs.push(uvs[2], uvs[3]);
  39258. }
  39259. //indices
  39260. var vertexNb = positions.length / 3;
  39261. for (var i = 1; i < vertexNb - 1; i++) {
  39262. indices.push(i + 1, 0, i);
  39263. }
  39264. // result
  39265. VertexData.ComputeNormals(positions, indices, normals);
  39266. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39267. var vertexData = new VertexData();
  39268. vertexData.indices = indices;
  39269. vertexData.positions = positions;
  39270. vertexData.normals = normals;
  39271. vertexData.uvs = uvs;
  39272. return vertexData;
  39273. };
  39274. /**
  39275. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  39276. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  39277. * @param polygon a mesh built from polygonTriangulation.build()
  39278. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39279. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39280. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39281. * @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)
  39282. * @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)
  39283. * @returns the VertexData of the Polygon
  39284. */
  39285. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  39286. var faceUV = fUV || new Array(3);
  39287. var faceColors = fColors;
  39288. var colors = [];
  39289. // default face colors and UV if undefined
  39290. for (var f = 0; f < 3; f++) {
  39291. if (faceUV[f] === undefined) {
  39292. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39293. }
  39294. if (faceColors && faceColors[f] === undefined) {
  39295. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39296. }
  39297. }
  39298. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39299. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39300. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39301. var indices = polygon.getIndices();
  39302. // set face colours and textures
  39303. var idx = 0;
  39304. var face = 0;
  39305. for (var index = 0; index < normals.length; index += 3) {
  39306. //Edge Face no. 1
  39307. if (Math.abs(normals[index + 1]) < 0.001) {
  39308. face = 1;
  39309. }
  39310. //Top Face no. 0
  39311. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  39312. face = 0;
  39313. }
  39314. //Bottom Face no. 2
  39315. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  39316. face = 2;
  39317. }
  39318. idx = index / 3;
  39319. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  39320. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  39321. if (faceColors) {
  39322. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  39323. }
  39324. }
  39325. // sides
  39326. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  39327. // Result
  39328. var vertexData = new VertexData();
  39329. vertexData.indices = indices;
  39330. vertexData.positions = positions;
  39331. vertexData.normals = normals;
  39332. vertexData.uvs = uvs;
  39333. if (faceColors) {
  39334. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  39335. vertexData.colors = totalColors;
  39336. }
  39337. return vertexData;
  39338. };
  39339. /**
  39340. * Creates the VertexData of the IcoSphere
  39341. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  39342. * * radius the radius of the IcoSphere, optional default 1
  39343. * * radiusX allows stretching in the x direction, optional, default radius
  39344. * * radiusY allows stretching in the y direction, optional, default radius
  39345. * * radiusZ allows stretching in the z direction, optional, default radius
  39346. * * flat when true creates a flat shaded mesh, optional, default true
  39347. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39348. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39349. * * 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)
  39350. * * 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)
  39351. * @returns the VertexData of the IcoSphere
  39352. */
  39353. VertexData.CreateIcoSphere = function (options) {
  39354. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39355. var radius = options.radius || 1;
  39356. var flat = (options.flat === undefined) ? true : options.flat;
  39357. var subdivisions = options.subdivisions || 4;
  39358. var radiusX = options.radiusX || radius;
  39359. var radiusY = options.radiusY || radius;
  39360. var radiusZ = options.radiusZ || radius;
  39361. var t = (1 + Math.sqrt(5)) / 2;
  39362. // 12 vertex x,y,z
  39363. var ico_vertices = [
  39364. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  39365. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  39366. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  39367. ];
  39368. // index of 3 vertex makes a face of icopshere
  39369. var ico_indices = [
  39370. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  39371. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  39372. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  39373. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  39374. ];
  39375. // vertex for uv have aliased position, not for UV
  39376. var vertices_unalias_id = [
  39377. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  39378. // vertex alias
  39379. 0,
  39380. 2,
  39381. 3,
  39382. 3,
  39383. 3,
  39384. 4,
  39385. 7,
  39386. 8,
  39387. 9,
  39388. 9,
  39389. 10,
  39390. 11 // 23: B + 12
  39391. ];
  39392. // uv as integer step (not pixels !)
  39393. var ico_vertexuv = [
  39394. 5, 1, 3, 1, 6, 4, 0, 0,
  39395. 5, 3, 4, 2, 2, 2, 4, 0,
  39396. 2, 0, 1, 1, 6, 0, 6, 2,
  39397. // vertex alias (for same vertex on different faces)
  39398. 0, 4,
  39399. 3, 3,
  39400. 4, 4,
  39401. 3, 1,
  39402. 4, 2,
  39403. 4, 4,
  39404. 0, 2,
  39405. 1, 1,
  39406. 2, 2,
  39407. 3, 3,
  39408. 1, 3,
  39409. 2, 4 // 23: B + 12
  39410. ];
  39411. // Vertices[0, 1, ...9, A, B] : position on UV plane
  39412. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  39413. // First island of uv mapping
  39414. // v = 4h 3+ 2
  39415. // v = 3h 9+ 4
  39416. // v = 2h 9+ 5 B
  39417. // v = 1h 9 1 0
  39418. // v = 0h 3 8 7 A
  39419. // u = 0 1 2 3 4 5 6 *a
  39420. // Second island of uv mapping
  39421. // v = 4h 0+ B+ 4+
  39422. // v = 3h A+ 2+
  39423. // v = 2h 7+ 6 3+
  39424. // v = 1h 8+ 3+
  39425. // v = 0h
  39426. // u = 0 1 2 3 4 5 6 *a
  39427. // Face layout on texture UV mapping
  39428. // ============
  39429. // \ 4 /\ 16 / ======
  39430. // \ / \ / /\ 11 /
  39431. // \/ 7 \/ / \ /
  39432. // ======= / 10 \/
  39433. // /\ 17 /\ =======
  39434. // / \ / \ \ 15 /\
  39435. // / 8 \/ 12 \ \ / \
  39436. // ============ \/ 6 \
  39437. // \ 18 /\ ============
  39438. // \ / \ \ 5 /\ 0 /
  39439. // \/ 13 \ \ / \ /
  39440. // ======= \/ 1 \/
  39441. // =============
  39442. // /\ 19 /\ 2 /\
  39443. // / \ / \ / \
  39444. // / 14 \/ 9 \/ 3 \
  39445. // ===================
  39446. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  39447. var ustep = 138 / 1024;
  39448. var vstep = 239 / 1024;
  39449. var uoffset = 60 / 1024;
  39450. var voffset = 26 / 1024;
  39451. // Second island should have margin, not to touch the first island
  39452. // avoid any borderline artefact in pixel rounding
  39453. var island_u_offset = -40 / 1024;
  39454. var island_v_offset = +20 / 1024;
  39455. // face is either island 0 or 1 :
  39456. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  39457. var island = [
  39458. 0, 0, 0, 0, 1,
  39459. 0, 0, 1, 1, 0,
  39460. 0, 0, 1, 1, 0,
  39461. 0, 1, 1, 1, 0 // 15 - 19
  39462. ];
  39463. var indices = new Array();
  39464. var positions = new Array();
  39465. var normals = new Array();
  39466. var uvs = new Array();
  39467. var current_indice = 0;
  39468. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  39469. var face_vertex_pos = new Array(3);
  39470. var face_vertex_uv = new Array(3);
  39471. var v012;
  39472. for (v012 = 0; v012 < 3; v012++) {
  39473. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  39474. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  39475. }
  39476. // create all with normals
  39477. for (var face = 0; face < 20; face++) {
  39478. // 3 vertex per face
  39479. for (v012 = 0; v012 < 3; v012++) {
  39480. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  39481. var v_id = ico_indices[3 * face + v012];
  39482. // vertex have 3D position (x,y,z)
  39483. 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]);
  39484. // Normalize to get normal, then scale to radius
  39485. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  39486. // uv Coordinates from vertex ID
  39487. 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);
  39488. }
  39489. // Subdivide the face (interpolate pos, norm, uv)
  39490. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  39491. // - norm is linear interpolation of vertex corner normal
  39492. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  39493. // - uv is linear interpolation
  39494. //
  39495. // Topology is as below for sub-divide by 2
  39496. // vertex shown as v0,v1,v2
  39497. // interp index is i1 to progress in range [v0,v1[
  39498. // interp index is i2 to progress in range [v0,v2[
  39499. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  39500. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39501. //
  39502. //
  39503. // i2 v2
  39504. // ^ ^
  39505. // / / \
  39506. // / / \
  39507. // / / \
  39508. // / / (0,1) \
  39509. // / #---------\
  39510. // / / \ (0,0)'/ \
  39511. // / / \ / \
  39512. // / / \ / \
  39513. // / / (0,0) \ / (1,0) \
  39514. // / #---------#---------\
  39515. // v0 v1
  39516. //
  39517. // --------------------> i1
  39518. //
  39519. // interp of (i1,i2):
  39520. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  39521. // along i1 : lerp(x0,x1, i1/(S-i2))
  39522. //
  39523. // centroid of triangle is needed to get help normal computation
  39524. // (c1,c2) are used for centroid location
  39525. var interp_vertex = function (i1, i2, c1, c2) {
  39526. // vertex is interpolated from
  39527. // - face_vertex_pos[0..2]
  39528. // - face_vertex_uv[0..2]
  39529. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  39530. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  39531. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  39532. pos_interp.normalize();
  39533. var vertex_normal;
  39534. if (flat) {
  39535. // in flat mode, recalculate normal as face centroid normal
  39536. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  39537. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  39538. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  39539. }
  39540. else {
  39541. // in smooth mode, recalculate normal from each single vertex position
  39542. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  39543. }
  39544. // Vertex normal need correction due to X,Y,Z radius scaling
  39545. vertex_normal.x /= radiusX;
  39546. vertex_normal.y /= radiusY;
  39547. vertex_normal.z /= radiusZ;
  39548. vertex_normal.normalize();
  39549. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  39550. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  39551. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  39552. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  39553. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  39554. uvs.push(uv_interp.x, uv_interp.y);
  39555. // push each vertex has member of a face
  39556. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  39557. indices.push(current_indice);
  39558. current_indice++;
  39559. };
  39560. for (var i2 = 0; i2 < subdivisions; i2++) {
  39561. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  39562. // face : (i1,i2) for /\ :
  39563. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  39564. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39565. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39566. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39567. if (i1 + i2 + 1 < subdivisions) {
  39568. // face : (i1,i2)' for \/ :
  39569. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39570. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39571. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39572. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39573. }
  39574. }
  39575. }
  39576. }
  39577. // Sides
  39578. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39579. // Result
  39580. var vertexData = new VertexData();
  39581. vertexData.indices = indices;
  39582. vertexData.positions = positions;
  39583. vertexData.normals = normals;
  39584. vertexData.uvs = uvs;
  39585. return vertexData;
  39586. };
  39587. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  39588. /**
  39589. * Creates the VertexData for a Polyhedron
  39590. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  39591. * * type provided types are:
  39592. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39593. * * 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)
  39594. * * size the size of the IcoSphere, optional default 1
  39595. * * sizeX allows stretching in the x direction, optional, default size
  39596. * * sizeY allows stretching in the y direction, optional, default size
  39597. * * sizeZ allows stretching in the z direction, optional, default size
  39598. * * 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
  39599. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39600. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39601. * * flat when true creates a flat shaded mesh, optional, default true
  39602. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39603. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39604. * * 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)
  39605. * * 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)
  39606. * @returns the VertexData of the Polyhedron
  39607. */
  39608. VertexData.CreatePolyhedron = function (options) {
  39609. // provided polyhedron types :
  39610. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39611. // 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)
  39612. var polyhedra = [];
  39613. 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]] };
  39614. 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]] };
  39615. polyhedra[2] = {
  39616. 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]],
  39617. 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]]
  39618. };
  39619. polyhedra[3] = {
  39620. 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]],
  39621. 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]]
  39622. };
  39623. polyhedra[4] = {
  39624. 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]],
  39625. 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]]
  39626. };
  39627. 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]] };
  39628. 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]] };
  39629. 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]] };
  39630. 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]] };
  39631. 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]] };
  39632. 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]] };
  39633. 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]] };
  39634. 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]] };
  39635. 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]] };
  39636. polyhedra[14] = {
  39637. 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]],
  39638. 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]]
  39639. };
  39640. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  39641. var size = options.size;
  39642. var sizeX = options.sizeX || size || 1;
  39643. var sizeY = options.sizeY || size || 1;
  39644. var sizeZ = options.sizeZ || size || 1;
  39645. var data = options.custom || polyhedra[type];
  39646. var nbfaces = data.face.length;
  39647. var faceUV = options.faceUV || new Array(nbfaces);
  39648. var faceColors = options.faceColors;
  39649. var flat = (options.flat === undefined) ? true : options.flat;
  39650. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39651. var positions = new Array();
  39652. var indices = new Array();
  39653. var normals = new Array();
  39654. var uvs = new Array();
  39655. var colors = new Array();
  39656. var index = 0;
  39657. var faceIdx = 0; // face cursor in the array "indexes"
  39658. var indexes = new Array();
  39659. var i = 0;
  39660. var f = 0;
  39661. var u, v, ang, x, y, tmp;
  39662. // default face colors and UV if undefined
  39663. if (flat) {
  39664. for (f = 0; f < nbfaces; f++) {
  39665. if (faceColors && faceColors[f] === undefined) {
  39666. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39667. }
  39668. if (faceUV && faceUV[f] === undefined) {
  39669. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39670. }
  39671. }
  39672. }
  39673. if (!flat) {
  39674. for (i = 0; i < data.vertex.length; i++) {
  39675. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  39676. uvs.push(0, 0);
  39677. }
  39678. for (f = 0; f < nbfaces; f++) {
  39679. for (i = 0; i < data.face[f].length - 2; i++) {
  39680. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  39681. }
  39682. }
  39683. }
  39684. else {
  39685. for (f = 0; f < nbfaces; f++) {
  39686. var fl = data.face[f].length; // number of vertices of the current face
  39687. ang = 2 * Math.PI / fl;
  39688. x = 0.5 * Math.tan(ang / 2);
  39689. y = 0.5;
  39690. // positions, uvs, colors
  39691. for (i = 0; i < fl; i++) {
  39692. // positions
  39693. 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);
  39694. indexes.push(index);
  39695. index++;
  39696. // uvs
  39697. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  39698. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  39699. uvs.push(u, v);
  39700. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  39701. y = x * Math.sin(ang) + y * Math.cos(ang);
  39702. x = tmp;
  39703. // colors
  39704. if (faceColors) {
  39705. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  39706. }
  39707. }
  39708. // indices from indexes
  39709. for (i = 0; i < fl - 2; i++) {
  39710. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  39711. }
  39712. faceIdx += fl;
  39713. }
  39714. }
  39715. VertexData.ComputeNormals(positions, indices, normals);
  39716. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39717. var vertexData = new VertexData();
  39718. vertexData.positions = positions;
  39719. vertexData.indices = indices;
  39720. vertexData.normals = normals;
  39721. vertexData.uvs = uvs;
  39722. if (faceColors && flat) {
  39723. vertexData.colors = colors;
  39724. }
  39725. return vertexData;
  39726. };
  39727. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  39728. /**
  39729. * Creates the VertexData for a TorusKnot
  39730. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  39731. * * radius the radius of the torus knot, optional, default 2
  39732. * * tube the thickness of the tube, optional, default 0.5
  39733. * * radialSegments the number of sides on each tube segments, optional, default 32
  39734. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  39735. * * p the number of windings around the z axis, optional, default 2
  39736. * * q the number of windings around the x axis, optional, default 3
  39737. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39738. * * 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)
  39739. * * 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)
  39740. * @returns the VertexData of the Torus Knot
  39741. */
  39742. VertexData.CreateTorusKnot = function (options) {
  39743. var indices = new Array();
  39744. var positions = new Array();
  39745. var normals = new Array();
  39746. var uvs = new Array();
  39747. var radius = options.radius || 2;
  39748. var tube = options.tube || 0.5;
  39749. var radialSegments = options.radialSegments || 32;
  39750. var tubularSegments = options.tubularSegments || 32;
  39751. var p = options.p || 2;
  39752. var q = options.q || 3;
  39753. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39754. // Helper
  39755. var getPos = function (angle) {
  39756. var cu = Math.cos(angle);
  39757. var su = Math.sin(angle);
  39758. var quOverP = q / p * angle;
  39759. var cs = Math.cos(quOverP);
  39760. var tx = radius * (2 + cs) * 0.5 * cu;
  39761. var ty = radius * (2 + cs) * su * 0.5;
  39762. var tz = radius * Math.sin(quOverP) * 0.5;
  39763. return new BABYLON.Vector3(tx, ty, tz);
  39764. };
  39765. // Vertices
  39766. var i;
  39767. var j;
  39768. for (i = 0; i <= radialSegments; i++) {
  39769. var modI = i % radialSegments;
  39770. var u = modI / radialSegments * 2 * p * Math.PI;
  39771. var p1 = getPos(u);
  39772. var p2 = getPos(u + 0.01);
  39773. var tang = p2.subtract(p1);
  39774. var n = p2.add(p1);
  39775. var bitan = BABYLON.Vector3.Cross(tang, n);
  39776. n = BABYLON.Vector3.Cross(bitan, tang);
  39777. bitan.normalize();
  39778. n.normalize();
  39779. for (j = 0; j < tubularSegments; j++) {
  39780. var modJ = j % tubularSegments;
  39781. var v = modJ / tubularSegments * 2 * Math.PI;
  39782. var cx = -tube * Math.cos(v);
  39783. var cy = tube * Math.sin(v);
  39784. positions.push(p1.x + cx * n.x + cy * bitan.x);
  39785. positions.push(p1.y + cx * n.y + cy * bitan.y);
  39786. positions.push(p1.z + cx * n.z + cy * bitan.z);
  39787. uvs.push(i / radialSegments);
  39788. uvs.push(j / tubularSegments);
  39789. }
  39790. }
  39791. for (i = 0; i < radialSegments; i++) {
  39792. for (j = 0; j < tubularSegments; j++) {
  39793. var jNext = (j + 1) % tubularSegments;
  39794. var a = i * tubularSegments + j;
  39795. var b = (i + 1) * tubularSegments + j;
  39796. var c = (i + 1) * tubularSegments + jNext;
  39797. var d = i * tubularSegments + jNext;
  39798. indices.push(d);
  39799. indices.push(b);
  39800. indices.push(a);
  39801. indices.push(d);
  39802. indices.push(c);
  39803. indices.push(b);
  39804. }
  39805. }
  39806. // Normals
  39807. VertexData.ComputeNormals(positions, indices, normals);
  39808. // Sides
  39809. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39810. // Result
  39811. var vertexData = new VertexData();
  39812. vertexData.indices = indices;
  39813. vertexData.positions = positions;
  39814. vertexData.normals = normals;
  39815. vertexData.uvs = uvs;
  39816. return vertexData;
  39817. };
  39818. // Tools
  39819. /**
  39820. * Compute normals for given positions and indices
  39821. * @param positions an array of vertex positions, [...., x, y, z, ......]
  39822. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  39823. * @param normals an array of vertex normals, [...., x, y, z, ......]
  39824. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  39825. * * facetNormals : optional array of facet normals (vector3)
  39826. * * facetPositions : optional array of facet positions (vector3)
  39827. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  39828. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  39829. * * bInfo : optional bounding info, required for facetPartitioning computation
  39830. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  39831. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  39832. * * useRightHandedSystem: optional boolean to for right handed system computation
  39833. * * depthSort : optional boolean to enable the facet depth sort computation
  39834. * * distanceTo : optional Vector3 to compute the facet depth from this location
  39835. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  39836. */
  39837. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  39838. // temporary scalar variables
  39839. var index = 0; // facet index
  39840. var p1p2x = 0.0; // p1p2 vector x coordinate
  39841. var p1p2y = 0.0; // p1p2 vector y coordinate
  39842. var p1p2z = 0.0; // p1p2 vector z coordinate
  39843. var p3p2x = 0.0; // p3p2 vector x coordinate
  39844. var p3p2y = 0.0; // p3p2 vector y coordinate
  39845. var p3p2z = 0.0; // p3p2 vector z coordinate
  39846. var faceNormalx = 0.0; // facet normal x coordinate
  39847. var faceNormaly = 0.0; // facet normal y coordinate
  39848. var faceNormalz = 0.0; // facet normal z coordinate
  39849. var length = 0.0; // facet normal length before normalization
  39850. var v1x = 0; // vector1 x index in the positions array
  39851. var v1y = 0; // vector1 y index in the positions array
  39852. var v1z = 0; // vector1 z index in the positions array
  39853. var v2x = 0; // vector2 x index in the positions array
  39854. var v2y = 0; // vector2 y index in the positions array
  39855. var v2z = 0; // vector2 z index in the positions array
  39856. var v3x = 0; // vector3 x index in the positions array
  39857. var v3y = 0; // vector3 y index in the positions array
  39858. var v3z = 0; // vector3 z index in the positions array
  39859. var computeFacetNormals = false;
  39860. var computeFacetPositions = false;
  39861. var computeFacetPartitioning = false;
  39862. var computeDepthSort = false;
  39863. var faceNormalSign = 1;
  39864. var ratio = 0;
  39865. var distanceTo = null;
  39866. if (options) {
  39867. computeFacetNormals = (options.facetNormals) ? true : false;
  39868. computeFacetPositions = (options.facetPositions) ? true : false;
  39869. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  39870. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  39871. ratio = options.ratio || 0;
  39872. computeDepthSort = (options.depthSort) ? true : false;
  39873. distanceTo = (options.distanceTo);
  39874. if (computeDepthSort) {
  39875. if (distanceTo === undefined) {
  39876. distanceTo = BABYLON.Vector3.Zero();
  39877. }
  39878. var depthSortedFacets = options.depthSortedFacets;
  39879. }
  39880. }
  39881. // facetPartitioning reinit if needed
  39882. var xSubRatio = 0;
  39883. var ySubRatio = 0;
  39884. var zSubRatio = 0;
  39885. var subSq = 0;
  39886. if (computeFacetPartitioning && options && options.bbSize) {
  39887. var ox = 0; // X partitioning index for facet position
  39888. var oy = 0; // Y partinioning index for facet position
  39889. var oz = 0; // Z partinioning index for facet position
  39890. var b1x = 0; // X partitioning index for facet v1 vertex
  39891. var b1y = 0; // Y partitioning index for facet v1 vertex
  39892. var b1z = 0; // z partitioning index for facet v1 vertex
  39893. var b2x = 0; // X partitioning index for facet v2 vertex
  39894. var b2y = 0; // Y partitioning index for facet v2 vertex
  39895. var b2z = 0; // Z partitioning index for facet v2 vertex
  39896. var b3x = 0; // X partitioning index for facet v3 vertex
  39897. var b3y = 0; // Y partitioning index for facet v3 vertex
  39898. var b3z = 0; // Z partitioning index for facet v3 vertex
  39899. var block_idx_o = 0; // facet barycenter block index
  39900. var block_idx_v1 = 0; // v1 vertex block index
  39901. var block_idx_v2 = 0; // v2 vertex block index
  39902. var block_idx_v3 = 0; // v3 vertex block index
  39903. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  39904. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  39905. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  39906. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  39907. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  39908. subSq = options.subDiv.max * options.subDiv.max;
  39909. options.facetPartitioning.length = 0;
  39910. }
  39911. // reset the normals
  39912. for (index = 0; index < positions.length; index++) {
  39913. normals[index] = 0.0;
  39914. }
  39915. // Loop : 1 indice triplet = 1 facet
  39916. var nbFaces = (indices.length / 3) | 0;
  39917. for (index = 0; index < nbFaces; index++) {
  39918. // get the indexes of the coordinates of each vertex of the facet
  39919. v1x = indices[index * 3] * 3;
  39920. v1y = v1x + 1;
  39921. v1z = v1x + 2;
  39922. v2x = indices[index * 3 + 1] * 3;
  39923. v2y = v2x + 1;
  39924. v2z = v2x + 2;
  39925. v3x = indices[index * 3 + 2] * 3;
  39926. v3y = v3x + 1;
  39927. v3z = v3x + 2;
  39928. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  39929. p1p2y = positions[v1y] - positions[v2y];
  39930. p1p2z = positions[v1z] - positions[v2z];
  39931. p3p2x = positions[v3x] - positions[v2x];
  39932. p3p2y = positions[v3y] - positions[v2y];
  39933. p3p2z = positions[v3z] - positions[v2z];
  39934. // compute the face normal with the cross product
  39935. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  39936. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  39937. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  39938. // normalize this normal and store it in the array facetData
  39939. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39940. length = (length === 0) ? 1.0 : length;
  39941. faceNormalx /= length;
  39942. faceNormaly /= length;
  39943. faceNormalz /= length;
  39944. if (computeFacetNormals && options) {
  39945. options.facetNormals[index].x = faceNormalx;
  39946. options.facetNormals[index].y = faceNormaly;
  39947. options.facetNormals[index].z = faceNormalz;
  39948. }
  39949. if (computeFacetPositions && options) {
  39950. // compute and the facet barycenter coordinates in the array facetPositions
  39951. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  39952. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  39953. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  39954. }
  39955. if (computeFacetPartitioning && options) {
  39956. // store the facet indexes in arrays in the main facetPartitioning array :
  39957. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  39958. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  39959. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  39960. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  39961. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39962. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39963. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39964. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39965. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39966. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39967. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39968. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39969. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39970. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  39971. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  39972. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  39973. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  39974. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  39975. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  39976. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  39977. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  39978. // push each facet index in each block containing the vertex
  39979. options.facetPartitioning[block_idx_v1].push(index);
  39980. if (block_idx_v2 != block_idx_v1) {
  39981. options.facetPartitioning[block_idx_v2].push(index);
  39982. }
  39983. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  39984. options.facetPartitioning[block_idx_v3].push(index);
  39985. }
  39986. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  39987. options.facetPartitioning[block_idx_o].push(index);
  39988. }
  39989. }
  39990. if (computeDepthSort && options && options.facetPositions) {
  39991. var dsf = depthSortedFacets[index];
  39992. dsf.ind = index * 3;
  39993. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  39994. }
  39995. // compute the normals anyway
  39996. normals[v1x] += faceNormalx; // accumulate all the normals per face
  39997. normals[v1y] += faceNormaly;
  39998. normals[v1z] += faceNormalz;
  39999. normals[v2x] += faceNormalx;
  40000. normals[v2y] += faceNormaly;
  40001. normals[v2z] += faceNormalz;
  40002. normals[v3x] += faceNormalx;
  40003. normals[v3y] += faceNormaly;
  40004. normals[v3z] += faceNormalz;
  40005. }
  40006. // last normalization of each normal
  40007. for (index = 0; index < normals.length / 3; index++) {
  40008. faceNormalx = normals[index * 3];
  40009. faceNormaly = normals[index * 3 + 1];
  40010. faceNormalz = normals[index * 3 + 2];
  40011. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  40012. length = (length === 0) ? 1.0 : length;
  40013. faceNormalx /= length;
  40014. faceNormaly /= length;
  40015. faceNormalz /= length;
  40016. normals[index * 3] = faceNormalx;
  40017. normals[index * 3 + 1] = faceNormaly;
  40018. normals[index * 3 + 2] = faceNormalz;
  40019. }
  40020. };
  40021. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  40022. var li = indices.length;
  40023. var ln = normals.length;
  40024. var i;
  40025. var n;
  40026. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40027. switch (sideOrientation) {
  40028. case BABYLON.Mesh.FRONTSIDE:
  40029. // nothing changed
  40030. break;
  40031. case BABYLON.Mesh.BACKSIDE:
  40032. var tmp;
  40033. // indices
  40034. for (i = 0; i < li; i += 3) {
  40035. tmp = indices[i];
  40036. indices[i] = indices[i + 2];
  40037. indices[i + 2] = tmp;
  40038. }
  40039. // normals
  40040. for (n = 0; n < ln; n++) {
  40041. normals[n] = -normals[n];
  40042. }
  40043. break;
  40044. case BABYLON.Mesh.DOUBLESIDE:
  40045. // positions
  40046. var lp = positions.length;
  40047. var l = lp / 3;
  40048. for (var p = 0; p < lp; p++) {
  40049. positions[lp + p] = positions[p];
  40050. }
  40051. // indices
  40052. for (i = 0; i < li; i += 3) {
  40053. indices[i + li] = indices[i + 2] + l;
  40054. indices[i + 1 + li] = indices[i + 1] + l;
  40055. indices[i + 2 + li] = indices[i] + l;
  40056. }
  40057. // normals
  40058. for (n = 0; n < ln; n++) {
  40059. normals[ln + n] = -normals[n];
  40060. }
  40061. // uvs
  40062. var lu = uvs.length;
  40063. var u = 0;
  40064. for (u = 0; u < lu; u++) {
  40065. uvs[u + lu] = uvs[u];
  40066. }
  40067. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  40068. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  40069. u = 0;
  40070. for (i = 0; i < lu / 2; i++) {
  40071. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  40072. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  40073. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  40074. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  40075. u += 2;
  40076. }
  40077. break;
  40078. }
  40079. };
  40080. /**
  40081. * Applies VertexData created from the imported parameters to the geometry
  40082. * @param parsedVertexData the parsed data from an imported file
  40083. * @param geometry the geometry to apply the VertexData to
  40084. */
  40085. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  40086. var vertexData = new VertexData();
  40087. // positions
  40088. var positions = parsedVertexData.positions;
  40089. if (positions) {
  40090. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  40091. }
  40092. // normals
  40093. var normals = parsedVertexData.normals;
  40094. if (normals) {
  40095. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  40096. }
  40097. // tangents
  40098. var tangents = parsedVertexData.tangents;
  40099. if (tangents) {
  40100. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  40101. }
  40102. // uvs
  40103. var uvs = parsedVertexData.uvs;
  40104. if (uvs) {
  40105. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  40106. }
  40107. // uv2s
  40108. var uv2s = parsedVertexData.uv2s;
  40109. if (uv2s) {
  40110. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  40111. }
  40112. // uv3s
  40113. var uv3s = parsedVertexData.uv3s;
  40114. if (uv3s) {
  40115. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  40116. }
  40117. // uv4s
  40118. var uv4s = parsedVertexData.uv4s;
  40119. if (uv4s) {
  40120. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  40121. }
  40122. // uv5s
  40123. var uv5s = parsedVertexData.uv5s;
  40124. if (uv5s) {
  40125. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  40126. }
  40127. // uv6s
  40128. var uv6s = parsedVertexData.uv6s;
  40129. if (uv6s) {
  40130. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  40131. }
  40132. // colors
  40133. var colors = parsedVertexData.colors;
  40134. if (colors) {
  40135. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  40136. }
  40137. // matricesIndices
  40138. var matricesIndices = parsedVertexData.matricesIndices;
  40139. if (matricesIndices) {
  40140. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  40141. }
  40142. // matricesWeights
  40143. var matricesWeights = parsedVertexData.matricesWeights;
  40144. if (matricesWeights) {
  40145. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  40146. }
  40147. // indices
  40148. var indices = parsedVertexData.indices;
  40149. if (indices) {
  40150. vertexData.indices = indices;
  40151. }
  40152. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  40153. };
  40154. return VertexData;
  40155. }());
  40156. BABYLON.VertexData = VertexData;
  40157. })(BABYLON || (BABYLON = {}));
  40158. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  40159. var BABYLON;
  40160. (function (BABYLON) {
  40161. /**
  40162. * Class used to store geometry data (vertex buffers + index buffer)
  40163. */
  40164. var Geometry = /** @class */ (function () {
  40165. /**
  40166. * Creates a new geometry
  40167. * @param id defines the unique ID
  40168. * @param scene defines the hosting scene
  40169. * @param vertexData defines the VertexData used to get geometry data
  40170. * @param updatable defines if geometry must be updatable (false by default)
  40171. * @param mesh defines the mesh that will be associated with the geometry
  40172. */
  40173. function Geometry(id, scene, vertexData, updatable, mesh) {
  40174. if (updatable === void 0) { updatable = false; }
  40175. if (mesh === void 0) { mesh = null; }
  40176. /**
  40177. * Gets the delay loading state of the geometry (none by default which means not delayed)
  40178. */
  40179. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40180. this._totalVertices = 0;
  40181. this._isDisposed = false;
  40182. this._indexBufferIsUpdatable = false;
  40183. this.id = id;
  40184. this._engine = scene.getEngine();
  40185. this._meshes = [];
  40186. this._scene = scene;
  40187. //Init vertex buffer cache
  40188. this._vertexBuffers = {};
  40189. this._indices = [];
  40190. this._updatable = updatable;
  40191. // vertexData
  40192. if (vertexData) {
  40193. this.setAllVerticesData(vertexData, updatable);
  40194. }
  40195. else {
  40196. this._totalVertices = 0;
  40197. this._indices = [];
  40198. }
  40199. if (this._engine.getCaps().vertexArrayObject) {
  40200. this._vertexArrayObjects = {};
  40201. }
  40202. // applyToMesh
  40203. if (mesh) {
  40204. if (mesh.getClassName() === "LinesMesh") {
  40205. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  40206. this._updateExtend();
  40207. }
  40208. this.applyToMesh(mesh);
  40209. mesh.computeWorldMatrix(true);
  40210. }
  40211. }
  40212. Object.defineProperty(Geometry.prototype, "boundingBias", {
  40213. /**
  40214. * 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
  40215. */
  40216. get: function () {
  40217. return this._boundingBias;
  40218. },
  40219. /**
  40220. * 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
  40221. */
  40222. set: function (value) {
  40223. if (this._boundingBias) {
  40224. if (this._boundingBias.equals(value)) {
  40225. return;
  40226. }
  40227. this._boundingBias.copyFrom(value);
  40228. }
  40229. else {
  40230. this._boundingBias = value.clone();
  40231. }
  40232. this._updateBoundingInfo(true, null);
  40233. },
  40234. enumerable: true,
  40235. configurable: true
  40236. });
  40237. /**
  40238. * Static function used to attach a new empty geometry to a mesh
  40239. * @param mesh defines the mesh to attach the geometry to
  40240. * @returns the new Geometry
  40241. */
  40242. Geometry.CreateGeometryForMesh = function (mesh) {
  40243. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  40244. geometry.applyToMesh(mesh);
  40245. return geometry;
  40246. };
  40247. Object.defineProperty(Geometry.prototype, "extend", {
  40248. /**
  40249. * Gets the current extend of the geometry
  40250. */
  40251. get: function () {
  40252. return this._extend;
  40253. },
  40254. enumerable: true,
  40255. configurable: true
  40256. });
  40257. /**
  40258. * Gets the hosting scene
  40259. * @returns the hosting Scene
  40260. */
  40261. Geometry.prototype.getScene = function () {
  40262. return this._scene;
  40263. };
  40264. /**
  40265. * Gets the hosting engine
  40266. * @returns the hosting Engine
  40267. */
  40268. Geometry.prototype.getEngine = function () {
  40269. return this._engine;
  40270. };
  40271. /**
  40272. * Defines if the geometry is ready to use
  40273. * @returns true if the geometry is ready to be used
  40274. */
  40275. Geometry.prototype.isReady = function () {
  40276. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  40277. };
  40278. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  40279. /**
  40280. * Gets a value indicating that the geometry should not be serialized
  40281. */
  40282. get: function () {
  40283. for (var index = 0; index < this._meshes.length; index++) {
  40284. if (!this._meshes[index].doNotSerialize) {
  40285. return false;
  40286. }
  40287. }
  40288. return true;
  40289. },
  40290. enumerable: true,
  40291. configurable: true
  40292. });
  40293. /** @hidden */
  40294. Geometry.prototype._rebuild = function () {
  40295. if (this._vertexArrayObjects) {
  40296. this._vertexArrayObjects = {};
  40297. }
  40298. // Index buffer
  40299. if (this._meshes.length !== 0 && this._indices) {
  40300. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40301. }
  40302. // Vertex buffers
  40303. for (var key in this._vertexBuffers) {
  40304. var vertexBuffer = this._vertexBuffers[key];
  40305. vertexBuffer._rebuild();
  40306. }
  40307. };
  40308. /**
  40309. * Affects all geometry data in one call
  40310. * @param vertexData defines the geometry data
  40311. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  40312. */
  40313. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40314. vertexData.applyToGeometry(this, updatable);
  40315. this.notifyUpdate();
  40316. };
  40317. /**
  40318. * Set specific vertex data
  40319. * @param kind defines the data kind (Position, normal, etc...)
  40320. * @param data defines the vertex data to use
  40321. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  40322. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  40323. */
  40324. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  40325. if (updatable === void 0) { updatable = false; }
  40326. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  40327. this.setVerticesBuffer(buffer);
  40328. };
  40329. /**
  40330. * Removes a specific vertex data
  40331. * @param kind defines the data kind (Position, normal, etc...)
  40332. */
  40333. Geometry.prototype.removeVerticesData = function (kind) {
  40334. if (this._vertexBuffers[kind]) {
  40335. this._vertexBuffers[kind].dispose();
  40336. delete this._vertexBuffers[kind];
  40337. }
  40338. };
  40339. /**
  40340. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  40341. * @param buffer defines the vertex buffer to use
  40342. * @param totalVertices defines the total number of vertices for position kind (could be null)
  40343. */
  40344. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  40345. if (totalVertices === void 0) { totalVertices = null; }
  40346. var kind = buffer.getKind();
  40347. if (this._vertexBuffers[kind]) {
  40348. this._vertexBuffers[kind].dispose();
  40349. }
  40350. this._vertexBuffers[kind] = buffer;
  40351. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40352. var data = buffer.getData();
  40353. if (totalVertices != null) {
  40354. this._totalVertices = totalVertices;
  40355. }
  40356. else {
  40357. if (data != null) {
  40358. this._totalVertices = data.length / (buffer.byteStride / 4);
  40359. }
  40360. }
  40361. this._updateExtend(data);
  40362. this._resetPointsArrayCache();
  40363. var meshes = this._meshes;
  40364. var numOfMeshes = meshes.length;
  40365. for (var index = 0; index < numOfMeshes; index++) {
  40366. var mesh = meshes[index];
  40367. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40368. mesh._createGlobalSubMesh(false);
  40369. mesh.computeWorldMatrix(true);
  40370. }
  40371. }
  40372. this.notifyUpdate(kind);
  40373. if (this._vertexArrayObjects) {
  40374. this._disposeVertexArrayObjects();
  40375. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  40376. }
  40377. };
  40378. /**
  40379. * Update a specific vertex buffer
  40380. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  40381. * It will do nothing if the buffer is not updatable
  40382. * @param kind defines the data kind (Position, normal, etc...)
  40383. * @param data defines the data to use
  40384. * @param offset defines the offset in the target buffer where to store the data
  40385. * @param useBytes set to true if the offset is in bytes
  40386. */
  40387. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  40388. if (useBytes === void 0) { useBytes = false; }
  40389. var vertexBuffer = this.getVertexBuffer(kind);
  40390. if (!vertexBuffer) {
  40391. return;
  40392. }
  40393. vertexBuffer.updateDirectly(data, offset, useBytes);
  40394. this.notifyUpdate(kind);
  40395. };
  40396. /**
  40397. * Update a specific vertex buffer
  40398. * This function will create a new buffer if the current one is not updatable
  40399. * @param kind defines the data kind (Position, normal, etc...)
  40400. * @param data defines the data to use
  40401. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  40402. */
  40403. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  40404. if (updateExtends === void 0) { updateExtends = false; }
  40405. var vertexBuffer = this.getVertexBuffer(kind);
  40406. if (!vertexBuffer) {
  40407. return;
  40408. }
  40409. vertexBuffer.update(data);
  40410. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40411. this._updateBoundingInfo(updateExtends, data);
  40412. }
  40413. this.notifyUpdate(kind);
  40414. };
  40415. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  40416. if (updateExtends) {
  40417. this._updateExtend(data);
  40418. }
  40419. var meshes = this._meshes;
  40420. var numOfMeshes = meshes.length;
  40421. this._resetPointsArrayCache();
  40422. for (var index = 0; index < numOfMeshes; index++) {
  40423. var mesh = meshes[index];
  40424. if (updateExtends) {
  40425. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40426. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  40427. var subMesh = mesh.subMeshes[subIndex];
  40428. subMesh.refreshBoundingInfo();
  40429. }
  40430. }
  40431. }
  40432. };
  40433. /** @hidden */
  40434. Geometry.prototype._bind = function (effect, indexToBind) {
  40435. if (!effect) {
  40436. return;
  40437. }
  40438. if (indexToBind === undefined) {
  40439. indexToBind = this._indexBuffer;
  40440. }
  40441. var vbs = this.getVertexBuffers();
  40442. if (!vbs) {
  40443. return;
  40444. }
  40445. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  40446. this._engine.bindBuffers(vbs, indexToBind, effect);
  40447. return;
  40448. }
  40449. // Using VAO
  40450. if (!this._vertexArrayObjects[effect.key]) {
  40451. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  40452. }
  40453. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  40454. };
  40455. /**
  40456. * Gets total number of vertices
  40457. * @returns the total number of vertices
  40458. */
  40459. Geometry.prototype.getTotalVertices = function () {
  40460. if (!this.isReady()) {
  40461. return 0;
  40462. }
  40463. return this._totalVertices;
  40464. };
  40465. /**
  40466. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  40467. * @param kind defines the data kind (Position, normal, etc...)
  40468. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40469. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40470. * @returns a float array containing vertex data
  40471. */
  40472. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  40473. var vertexBuffer = this.getVertexBuffer(kind);
  40474. if (!vertexBuffer) {
  40475. return null;
  40476. }
  40477. var data = vertexBuffer.getData();
  40478. if (!data) {
  40479. return null;
  40480. }
  40481. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  40482. var count = this._totalVertices * vertexBuffer.getSize();
  40483. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  40484. var copy_1 = new Array(count);
  40485. vertexBuffer.forEach(count, function (value, index) {
  40486. copy_1[index] = value;
  40487. });
  40488. return copy_1;
  40489. }
  40490. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  40491. if (data instanceof Array) {
  40492. var offset = vertexBuffer.byteOffset / 4;
  40493. return BABYLON.Tools.Slice(data, offset, offset + count);
  40494. }
  40495. else if (data instanceof ArrayBuffer) {
  40496. return new Float32Array(data, vertexBuffer.byteOffset, count);
  40497. }
  40498. else {
  40499. var offset = data.byteOffset + vertexBuffer.byteOffset;
  40500. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  40501. var result = new Float32Array(count);
  40502. var source = new Float32Array(data.buffer, offset, count);
  40503. result.set(source);
  40504. return result;
  40505. }
  40506. return new Float32Array(data.buffer, offset, count);
  40507. }
  40508. }
  40509. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  40510. return BABYLON.Tools.Slice(data);
  40511. }
  40512. return data;
  40513. };
  40514. /**
  40515. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  40516. * @param kind defines the data kind (Position, normal, etc...)
  40517. * @returns true if the vertex buffer with the specified kind is updatable
  40518. */
  40519. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  40520. var vb = this._vertexBuffers[kind];
  40521. if (!vb) {
  40522. return false;
  40523. }
  40524. return vb.isUpdatable();
  40525. };
  40526. /**
  40527. * Gets a specific vertex buffer
  40528. * @param kind defines the data kind (Position, normal, etc...)
  40529. * @returns a VertexBuffer
  40530. */
  40531. Geometry.prototype.getVertexBuffer = function (kind) {
  40532. if (!this.isReady()) {
  40533. return null;
  40534. }
  40535. return this._vertexBuffers[kind];
  40536. };
  40537. /**
  40538. * Returns all vertex buffers
  40539. * @return an object holding all vertex buffers indexed by kind
  40540. */
  40541. Geometry.prototype.getVertexBuffers = function () {
  40542. if (!this.isReady()) {
  40543. return null;
  40544. }
  40545. return this._vertexBuffers;
  40546. };
  40547. /**
  40548. * Gets a boolean indicating if specific vertex buffer is present
  40549. * @param kind defines the data kind (Position, normal, etc...)
  40550. * @returns true if data is present
  40551. */
  40552. Geometry.prototype.isVerticesDataPresent = function (kind) {
  40553. if (!this._vertexBuffers) {
  40554. if (this._delayInfo) {
  40555. return this._delayInfo.indexOf(kind) !== -1;
  40556. }
  40557. return false;
  40558. }
  40559. return this._vertexBuffers[kind] !== undefined;
  40560. };
  40561. /**
  40562. * Gets a list of all attached data kinds (Position, normal, etc...)
  40563. * @returns a list of string containing all kinds
  40564. */
  40565. Geometry.prototype.getVerticesDataKinds = function () {
  40566. var result = [];
  40567. var kind;
  40568. if (!this._vertexBuffers && this._delayInfo) {
  40569. for (kind in this._delayInfo) {
  40570. result.push(kind);
  40571. }
  40572. }
  40573. else {
  40574. for (kind in this._vertexBuffers) {
  40575. result.push(kind);
  40576. }
  40577. }
  40578. return result;
  40579. };
  40580. /**
  40581. * Update index buffer
  40582. * @param indices defines the indices to store in the index buffer
  40583. * @param offset defines the offset in the target buffer where to store the data
  40584. */
  40585. Geometry.prototype.updateIndices = function (indices, offset) {
  40586. if (!this._indexBuffer) {
  40587. return;
  40588. }
  40589. if (!this._indexBufferIsUpdatable) {
  40590. this.setIndices(indices, null, true);
  40591. }
  40592. else {
  40593. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  40594. }
  40595. };
  40596. /**
  40597. * Creates a new index buffer
  40598. * @param indices defines the indices to store in the index buffer
  40599. * @param totalVertices defines the total number of vertices (could be null)
  40600. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  40601. */
  40602. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  40603. if (totalVertices === void 0) { totalVertices = null; }
  40604. if (updatable === void 0) { updatable = false; }
  40605. if (this._indexBuffer) {
  40606. this._engine._releaseBuffer(this._indexBuffer);
  40607. }
  40608. this._disposeVertexArrayObjects();
  40609. this._indices = indices;
  40610. this._indexBufferIsUpdatable = updatable;
  40611. if (this._meshes.length !== 0 && this._indices) {
  40612. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  40613. }
  40614. if (totalVertices != undefined) { // including null and undefined
  40615. this._totalVertices = totalVertices;
  40616. }
  40617. var meshes = this._meshes;
  40618. var numOfMeshes = meshes.length;
  40619. for (var index = 0; index < numOfMeshes; index++) {
  40620. meshes[index]._createGlobalSubMesh(true);
  40621. }
  40622. this.notifyUpdate();
  40623. };
  40624. /**
  40625. * Return the total number of indices
  40626. * @returns the total number of indices
  40627. */
  40628. Geometry.prototype.getTotalIndices = function () {
  40629. if (!this.isReady()) {
  40630. return 0;
  40631. }
  40632. return this._indices.length;
  40633. };
  40634. /**
  40635. * Gets the index buffer array
  40636. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40637. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40638. * @returns the index buffer array
  40639. */
  40640. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  40641. if (!this.isReady()) {
  40642. return null;
  40643. }
  40644. var orig = this._indices;
  40645. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  40646. return orig;
  40647. }
  40648. else {
  40649. var len = orig.length;
  40650. var copy = [];
  40651. for (var i = 0; i < len; i++) {
  40652. copy.push(orig[i]);
  40653. }
  40654. return copy;
  40655. }
  40656. };
  40657. /**
  40658. * Gets the index buffer
  40659. * @return the index buffer
  40660. */
  40661. Geometry.prototype.getIndexBuffer = function () {
  40662. if (!this.isReady()) {
  40663. return null;
  40664. }
  40665. return this._indexBuffer;
  40666. };
  40667. /** @hidden */
  40668. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  40669. if (effect === void 0) { effect = null; }
  40670. if (!effect || !this._vertexArrayObjects) {
  40671. return;
  40672. }
  40673. if (this._vertexArrayObjects[effect.key]) {
  40674. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  40675. delete this._vertexArrayObjects[effect.key];
  40676. }
  40677. };
  40678. /**
  40679. * Release the associated resources for a specific mesh
  40680. * @param mesh defines the source mesh
  40681. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  40682. */
  40683. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  40684. var meshes = this._meshes;
  40685. var index = meshes.indexOf(mesh);
  40686. if (index === -1) {
  40687. return;
  40688. }
  40689. meshes.splice(index, 1);
  40690. mesh._geometry = null;
  40691. if (meshes.length === 0 && shouldDispose) {
  40692. this.dispose();
  40693. }
  40694. };
  40695. /**
  40696. * Apply current geometry to a given mesh
  40697. * @param mesh defines the mesh to apply geometry to
  40698. */
  40699. Geometry.prototype.applyToMesh = function (mesh) {
  40700. if (mesh._geometry === this) {
  40701. return;
  40702. }
  40703. var previousGeometry = mesh._geometry;
  40704. if (previousGeometry) {
  40705. previousGeometry.releaseForMesh(mesh);
  40706. }
  40707. var meshes = this._meshes;
  40708. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  40709. mesh._geometry = this;
  40710. this._scene.pushGeometry(this);
  40711. meshes.push(mesh);
  40712. if (this.isReady()) {
  40713. this._applyToMesh(mesh);
  40714. }
  40715. else {
  40716. mesh._boundingInfo = this._boundingInfo;
  40717. }
  40718. };
  40719. Geometry.prototype._updateExtend = function (data) {
  40720. if (data === void 0) { data = null; }
  40721. if (!data) {
  40722. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40723. }
  40724. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  40725. };
  40726. Geometry.prototype._applyToMesh = function (mesh) {
  40727. var numOfMeshes = this._meshes.length;
  40728. // vertexBuffers
  40729. for (var kind in this._vertexBuffers) {
  40730. if (numOfMeshes === 1) {
  40731. this._vertexBuffers[kind].create();
  40732. }
  40733. var buffer = this._vertexBuffers[kind].getBuffer();
  40734. if (buffer) {
  40735. buffer.references = numOfMeshes;
  40736. }
  40737. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40738. if (!this._extend) {
  40739. this._updateExtend();
  40740. }
  40741. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40742. mesh._createGlobalSubMesh(false);
  40743. //bounding info was just created again, world matrix should be applied again.
  40744. mesh._updateBoundingInfo();
  40745. }
  40746. }
  40747. // indexBuffer
  40748. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  40749. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40750. }
  40751. if (this._indexBuffer) {
  40752. this._indexBuffer.references = numOfMeshes;
  40753. }
  40754. };
  40755. Geometry.prototype.notifyUpdate = function (kind) {
  40756. if (this.onGeometryUpdated) {
  40757. this.onGeometryUpdated(this, kind);
  40758. }
  40759. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  40760. var mesh = _a[_i];
  40761. mesh._markSubMeshesAsAttributesDirty();
  40762. }
  40763. };
  40764. /**
  40765. * Load the geometry if it was flagged as delay loaded
  40766. * @param scene defines the hosting scene
  40767. * @param onLoaded defines a callback called when the geometry is loaded
  40768. */
  40769. Geometry.prototype.load = function (scene, onLoaded) {
  40770. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  40771. return;
  40772. }
  40773. if (this.isReady()) {
  40774. if (onLoaded) {
  40775. onLoaded();
  40776. }
  40777. return;
  40778. }
  40779. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  40780. this._queueLoad(scene, onLoaded);
  40781. };
  40782. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  40783. var _this = this;
  40784. if (!this.delayLoadingFile) {
  40785. return;
  40786. }
  40787. scene._addPendingData(this);
  40788. scene._loadFile(this.delayLoadingFile, function (data) {
  40789. if (!_this._delayLoadingFunction) {
  40790. return;
  40791. }
  40792. _this._delayLoadingFunction(JSON.parse(data), _this);
  40793. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40794. _this._delayInfo = [];
  40795. scene._removePendingData(_this);
  40796. var meshes = _this._meshes;
  40797. var numOfMeshes = meshes.length;
  40798. for (var index = 0; index < numOfMeshes; index++) {
  40799. _this._applyToMesh(meshes[index]);
  40800. }
  40801. if (onLoaded) {
  40802. onLoaded();
  40803. }
  40804. }, undefined, true);
  40805. };
  40806. /**
  40807. * Invert the geometry to move from a right handed system to a left handed one.
  40808. */
  40809. Geometry.prototype.toLeftHanded = function () {
  40810. // Flip faces
  40811. var tIndices = this.getIndices(false);
  40812. if (tIndices != null && tIndices.length > 0) {
  40813. for (var i = 0; i < tIndices.length; i += 3) {
  40814. var tTemp = tIndices[i + 0];
  40815. tIndices[i + 0] = tIndices[i + 2];
  40816. tIndices[i + 2] = tTemp;
  40817. }
  40818. this.setIndices(tIndices);
  40819. }
  40820. // Negate position.z
  40821. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  40822. if (tPositions != null && tPositions.length > 0) {
  40823. for (var i = 0; i < tPositions.length; i += 3) {
  40824. tPositions[i + 2] = -tPositions[i + 2];
  40825. }
  40826. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  40827. }
  40828. // Negate normal.z
  40829. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  40830. if (tNormals != null && tNormals.length > 0) {
  40831. for (var i = 0; i < tNormals.length; i += 3) {
  40832. tNormals[i + 2] = -tNormals[i + 2];
  40833. }
  40834. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  40835. }
  40836. };
  40837. // Cache
  40838. /** @hidden */
  40839. Geometry.prototype._resetPointsArrayCache = function () {
  40840. this._positions = null;
  40841. };
  40842. /** @hidden */
  40843. Geometry.prototype._generatePointsArray = function () {
  40844. if (this._positions) {
  40845. return true;
  40846. }
  40847. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40848. if (!data || data.length === 0) {
  40849. return false;
  40850. }
  40851. this._positions = [];
  40852. for (var index = 0; index < data.length; index += 3) {
  40853. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  40854. }
  40855. return true;
  40856. };
  40857. /**
  40858. * Gets a value indicating if the geometry is disposed
  40859. * @returns true if the geometry was disposed
  40860. */
  40861. Geometry.prototype.isDisposed = function () {
  40862. return this._isDisposed;
  40863. };
  40864. Geometry.prototype._disposeVertexArrayObjects = function () {
  40865. if (this._vertexArrayObjects) {
  40866. for (var kind in this._vertexArrayObjects) {
  40867. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  40868. }
  40869. this._vertexArrayObjects = {};
  40870. }
  40871. };
  40872. /**
  40873. * Free all associated resources
  40874. */
  40875. Geometry.prototype.dispose = function () {
  40876. var meshes = this._meshes;
  40877. var numOfMeshes = meshes.length;
  40878. var index;
  40879. for (index = 0; index < numOfMeshes; index++) {
  40880. this.releaseForMesh(meshes[index]);
  40881. }
  40882. this._meshes = [];
  40883. this._disposeVertexArrayObjects();
  40884. for (var kind in this._vertexBuffers) {
  40885. this._vertexBuffers[kind].dispose();
  40886. }
  40887. this._vertexBuffers = {};
  40888. this._totalVertices = 0;
  40889. if (this._indexBuffer) {
  40890. this._engine._releaseBuffer(this._indexBuffer);
  40891. }
  40892. this._indexBuffer = null;
  40893. this._indices = [];
  40894. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40895. this.delayLoadingFile = null;
  40896. this._delayLoadingFunction = null;
  40897. this._delayInfo = [];
  40898. this._boundingInfo = null;
  40899. this._scene.removeGeometry(this);
  40900. this._isDisposed = true;
  40901. };
  40902. /**
  40903. * Clone the current geometry into a new geometry
  40904. * @param id defines the unique ID of the new geometry
  40905. * @returns a new geometry object
  40906. */
  40907. Geometry.prototype.copy = function (id) {
  40908. var vertexData = new BABYLON.VertexData();
  40909. vertexData.indices = [];
  40910. var indices = this.getIndices();
  40911. if (indices) {
  40912. for (var index = 0; index < indices.length; index++) {
  40913. vertexData.indices.push(indices[index]);
  40914. }
  40915. }
  40916. var updatable = false;
  40917. var stopChecking = false;
  40918. var kind;
  40919. for (kind in this._vertexBuffers) {
  40920. // using slice() to make a copy of the array and not just reference it
  40921. var data = this.getVerticesData(kind);
  40922. if (data instanceof Float32Array) {
  40923. vertexData.set(new Float32Array(data), kind);
  40924. }
  40925. else {
  40926. vertexData.set(data.slice(0), kind);
  40927. }
  40928. if (!stopChecking) {
  40929. var vb = this.getVertexBuffer(kind);
  40930. if (vb) {
  40931. updatable = vb.isUpdatable();
  40932. stopChecking = !updatable;
  40933. }
  40934. }
  40935. }
  40936. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  40937. geometry.delayLoadState = this.delayLoadState;
  40938. geometry.delayLoadingFile = this.delayLoadingFile;
  40939. geometry._delayLoadingFunction = this._delayLoadingFunction;
  40940. for (kind in this._delayInfo) {
  40941. geometry._delayInfo = geometry._delayInfo || [];
  40942. geometry._delayInfo.push(kind);
  40943. }
  40944. // Bounding info
  40945. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40946. return geometry;
  40947. };
  40948. /**
  40949. * Serialize the current geometry info (and not the vertices data) into a JSON object
  40950. * @return a JSON representation of the current geometry data (without the vertices data)
  40951. */
  40952. Geometry.prototype.serialize = function () {
  40953. var serializationObject = {};
  40954. serializationObject.id = this.id;
  40955. serializationObject.updatable = this._updatable;
  40956. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  40957. serializationObject.tags = BABYLON.Tags.GetTags(this);
  40958. }
  40959. return serializationObject;
  40960. };
  40961. Geometry.prototype.toNumberArray = function (origin) {
  40962. if (Array.isArray(origin)) {
  40963. return origin;
  40964. }
  40965. else {
  40966. return Array.prototype.slice.call(origin);
  40967. }
  40968. };
  40969. /**
  40970. * Serialize all vertices data into a JSON oject
  40971. * @returns a JSON representation of the current geometry data
  40972. */
  40973. Geometry.prototype.serializeVerticeData = function () {
  40974. var serializationObject = this.serialize();
  40975. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  40976. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  40977. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  40978. serializationObject.positions._updatable = true;
  40979. }
  40980. }
  40981. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40982. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  40983. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  40984. serializationObject.normals._updatable = true;
  40985. }
  40986. }
  40987. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40988. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  40989. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  40990. serializationObject.tangets._updatable = true;
  40991. }
  40992. }
  40993. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40994. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  40995. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  40996. serializationObject.uvs._updatable = true;
  40997. }
  40998. }
  40999. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  41000. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  41001. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  41002. serializationObject.uv2s._updatable = true;
  41003. }
  41004. }
  41005. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  41006. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  41007. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  41008. serializationObject.uv3s._updatable = true;
  41009. }
  41010. }
  41011. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  41012. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  41013. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  41014. serializationObject.uv4s._updatable = true;
  41015. }
  41016. }
  41017. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  41018. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  41019. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  41020. serializationObject.uv5s._updatable = true;
  41021. }
  41022. }
  41023. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  41024. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  41025. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  41026. serializationObject.uv6s._updatable = true;
  41027. }
  41028. }
  41029. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  41030. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  41031. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  41032. serializationObject.colors._updatable = true;
  41033. }
  41034. }
  41035. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  41036. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  41037. serializationObject.matricesIndices._isExpanded = true;
  41038. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  41039. serializationObject.matricesIndices._updatable = true;
  41040. }
  41041. }
  41042. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  41043. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  41044. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  41045. serializationObject.matricesWeights._updatable = true;
  41046. }
  41047. }
  41048. serializationObject.indices = this.toNumberArray(this.getIndices());
  41049. return serializationObject;
  41050. };
  41051. // Statics
  41052. /**
  41053. * Extracts a clone of a mesh geometry
  41054. * @param mesh defines the source mesh
  41055. * @param id defines the unique ID of the new geometry object
  41056. * @returns the new geometry object
  41057. */
  41058. Geometry.ExtractFromMesh = function (mesh, id) {
  41059. var geometry = mesh._geometry;
  41060. if (!geometry) {
  41061. return null;
  41062. }
  41063. return geometry.copy(id);
  41064. };
  41065. /**
  41066. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  41067. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  41068. * Be aware Math.random() could cause collisions, but:
  41069. * "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"
  41070. * @returns a string containing a new GUID
  41071. */
  41072. Geometry.RandomId = function () {
  41073. return BABYLON.Tools.RandomId();
  41074. };
  41075. /** @hidden */
  41076. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  41077. var scene = mesh.getScene();
  41078. // Geometry
  41079. var geometryId = parsedGeometry.geometryId;
  41080. if (geometryId) {
  41081. var geometry = scene.getGeometryByID(geometryId);
  41082. if (geometry) {
  41083. geometry.applyToMesh(mesh);
  41084. }
  41085. }
  41086. else if (parsedGeometry instanceof ArrayBuffer) {
  41087. var binaryInfo = mesh._binaryInfo;
  41088. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  41089. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  41090. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  41091. }
  41092. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  41093. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  41094. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  41095. }
  41096. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  41097. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  41098. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  41099. }
  41100. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  41101. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  41102. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  41103. }
  41104. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  41105. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  41106. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  41107. }
  41108. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  41109. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  41110. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  41111. }
  41112. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  41113. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  41114. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  41115. }
  41116. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  41117. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  41118. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  41119. }
  41120. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  41121. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  41122. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  41123. }
  41124. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  41125. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  41126. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  41127. }
  41128. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  41129. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  41130. var floatIndices = [];
  41131. for (var i = 0; i < matricesIndicesData.length; i++) {
  41132. var index = matricesIndicesData[i];
  41133. floatIndices.push(index & 0x000000FF);
  41134. floatIndices.push((index & 0x0000FF00) >> 8);
  41135. floatIndices.push((index & 0x00FF0000) >> 16);
  41136. floatIndices.push(index >> 24);
  41137. }
  41138. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  41139. }
  41140. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  41141. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  41142. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  41143. }
  41144. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  41145. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  41146. mesh.setIndices(indicesData, null);
  41147. }
  41148. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  41149. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  41150. mesh.subMeshes = [];
  41151. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  41152. var materialIndex = subMeshesData[(i * 5) + 0];
  41153. var verticesStart = subMeshesData[(i * 5) + 1];
  41154. var verticesCount = subMeshesData[(i * 5) + 2];
  41155. var indexStart = subMeshesData[(i * 5) + 3];
  41156. var indexCount = subMeshesData[(i * 5) + 4];
  41157. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  41158. }
  41159. }
  41160. }
  41161. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  41162. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  41163. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  41164. if (parsedGeometry.tangents) {
  41165. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  41166. }
  41167. if (parsedGeometry.uvs) {
  41168. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  41169. }
  41170. if (parsedGeometry.uvs2) {
  41171. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  41172. }
  41173. if (parsedGeometry.uvs3) {
  41174. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  41175. }
  41176. if (parsedGeometry.uvs4) {
  41177. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  41178. }
  41179. if (parsedGeometry.uvs5) {
  41180. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  41181. }
  41182. if (parsedGeometry.uvs6) {
  41183. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  41184. }
  41185. if (parsedGeometry.colors) {
  41186. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  41187. }
  41188. if (parsedGeometry.matricesIndices) {
  41189. if (!parsedGeometry.matricesIndices._isExpanded) {
  41190. var floatIndices = [];
  41191. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  41192. var matricesIndex = parsedGeometry.matricesIndices[i];
  41193. floatIndices.push(matricesIndex & 0x000000FF);
  41194. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41195. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41196. floatIndices.push(matricesIndex >> 24);
  41197. }
  41198. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  41199. }
  41200. else {
  41201. delete parsedGeometry.matricesIndices._isExpanded;
  41202. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  41203. }
  41204. }
  41205. if (parsedGeometry.matricesIndicesExtra) {
  41206. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  41207. var floatIndices = [];
  41208. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  41209. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  41210. floatIndices.push(matricesIndex & 0x000000FF);
  41211. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41212. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41213. floatIndices.push(matricesIndex >> 24);
  41214. }
  41215. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  41216. }
  41217. else {
  41218. delete parsedGeometry.matricesIndices._isExpanded;
  41219. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  41220. }
  41221. }
  41222. if (parsedGeometry.matricesWeights) {
  41223. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  41224. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  41225. }
  41226. if (parsedGeometry.matricesWeightsExtra) {
  41227. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  41228. }
  41229. mesh.setIndices(parsedGeometry.indices, null);
  41230. }
  41231. // SubMeshes
  41232. if (parsedGeometry.subMeshes) {
  41233. mesh.subMeshes = [];
  41234. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  41235. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  41236. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  41237. }
  41238. }
  41239. // Flat shading
  41240. if (mesh._shouldGenerateFlatShading) {
  41241. mesh.convertToFlatShadedMesh();
  41242. delete mesh._shouldGenerateFlatShading;
  41243. }
  41244. // Update
  41245. mesh.computeWorldMatrix(true);
  41246. scene.onMeshImportedObservable.notifyObservers(mesh);
  41247. };
  41248. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  41249. var epsilon = 1e-3;
  41250. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  41251. return;
  41252. }
  41253. var noInfluenceBoneIndex = 0.0;
  41254. if (parsedGeometry.skeletonId > -1) {
  41255. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  41256. if (!skeleton) {
  41257. return;
  41258. }
  41259. noInfluenceBoneIndex = skeleton.bones.length;
  41260. }
  41261. else {
  41262. return;
  41263. }
  41264. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  41265. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41266. var matricesWeights = parsedGeometry.matricesWeights;
  41267. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  41268. var influencers = parsedGeometry.numBoneInfluencer;
  41269. var size = matricesWeights.length;
  41270. for (var i = 0; i < size; i += 4) {
  41271. var weight = 0.0;
  41272. var firstZeroWeight = -1;
  41273. for (var j = 0; j < 4; j++) {
  41274. var w = matricesWeights[i + j];
  41275. weight += w;
  41276. if (w < epsilon && firstZeroWeight < 0) {
  41277. firstZeroWeight = j;
  41278. }
  41279. }
  41280. if (matricesWeightsExtra) {
  41281. for (var j = 0; j < 4; j++) {
  41282. var w = matricesWeightsExtra[i + j];
  41283. weight += w;
  41284. if (w < epsilon && firstZeroWeight < 0) {
  41285. firstZeroWeight = j + 4;
  41286. }
  41287. }
  41288. }
  41289. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  41290. firstZeroWeight = influencers - 1;
  41291. }
  41292. if (weight > epsilon) {
  41293. var mweight = 1.0 / weight;
  41294. for (var j = 0; j < 4; j++) {
  41295. matricesWeights[i + j] *= mweight;
  41296. }
  41297. if (matricesWeightsExtra) {
  41298. for (var j = 0; j < 4; j++) {
  41299. matricesWeightsExtra[i + j] *= mweight;
  41300. }
  41301. }
  41302. }
  41303. else {
  41304. if (firstZeroWeight >= 4) {
  41305. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  41306. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  41307. }
  41308. else {
  41309. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  41310. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  41311. }
  41312. }
  41313. }
  41314. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  41315. if (parsedGeometry.matricesWeightsExtra) {
  41316. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  41317. }
  41318. };
  41319. /**
  41320. * Create a new geometry from persisted data (Using .babylon file format)
  41321. * @param parsedVertexData defines the persisted data
  41322. * @param scene defines the hosting scene
  41323. * @param rootUrl defines the root url to use to load assets (like delayed data)
  41324. * @returns the new geometry object
  41325. */
  41326. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  41327. if (scene.getGeometryByID(parsedVertexData.id)) {
  41328. return null; // null since geometry could be something else than a box...
  41329. }
  41330. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  41331. if (BABYLON.Tags) {
  41332. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  41333. }
  41334. if (parsedVertexData.delayLoadingFile) {
  41335. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41336. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  41337. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  41338. geometry._delayInfo = [];
  41339. if (parsedVertexData.hasUVs) {
  41340. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  41341. }
  41342. if (parsedVertexData.hasUVs2) {
  41343. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  41344. }
  41345. if (parsedVertexData.hasUVs3) {
  41346. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  41347. }
  41348. if (parsedVertexData.hasUVs4) {
  41349. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  41350. }
  41351. if (parsedVertexData.hasUVs5) {
  41352. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  41353. }
  41354. if (parsedVertexData.hasUVs6) {
  41355. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  41356. }
  41357. if (parsedVertexData.hasColors) {
  41358. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  41359. }
  41360. if (parsedVertexData.hasMatricesIndices) {
  41361. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41362. }
  41363. if (parsedVertexData.hasMatricesWeights) {
  41364. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41365. }
  41366. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  41367. }
  41368. else {
  41369. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  41370. }
  41371. scene.pushGeometry(geometry, true);
  41372. return geometry;
  41373. };
  41374. return Geometry;
  41375. }());
  41376. BABYLON.Geometry = Geometry;
  41377. // Primitives
  41378. /// Abstract class
  41379. /**
  41380. * Abstract class used to provide common services for all typed geometries
  41381. * @hidden
  41382. */
  41383. var _PrimitiveGeometry = /** @class */ (function (_super) {
  41384. __extends(_PrimitiveGeometry, _super);
  41385. /**
  41386. * Creates a new typed geometry
  41387. * @param id defines the unique ID of the geometry
  41388. * @param scene defines the hosting scene
  41389. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41390. * @param mesh defines the hosting mesh (can be null)
  41391. */
  41392. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  41393. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  41394. if (mesh === void 0) { mesh = null; }
  41395. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  41396. _this._canBeRegenerated = _canBeRegenerated;
  41397. _this._beingRegenerated = true;
  41398. _this.regenerate();
  41399. _this._beingRegenerated = false;
  41400. return _this;
  41401. }
  41402. /**
  41403. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  41404. * @returns true if the geometry can be regenerated
  41405. */
  41406. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  41407. return this._canBeRegenerated;
  41408. };
  41409. /**
  41410. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  41411. */
  41412. _PrimitiveGeometry.prototype.regenerate = function () {
  41413. if (!this._canBeRegenerated) {
  41414. return;
  41415. }
  41416. this._beingRegenerated = true;
  41417. this.setAllVerticesData(this._regenerateVertexData(), false);
  41418. this._beingRegenerated = false;
  41419. };
  41420. /**
  41421. * Clone the geometry
  41422. * @param id defines the unique ID of the new geometry
  41423. * @returns the new geometry
  41424. */
  41425. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  41426. return _super.prototype.copy.call(this, id);
  41427. };
  41428. // overrides
  41429. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  41430. if (!this._beingRegenerated) {
  41431. return;
  41432. }
  41433. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  41434. };
  41435. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  41436. if (!this._beingRegenerated) {
  41437. return;
  41438. }
  41439. _super.prototype.setVerticesData.call(this, kind, data, false);
  41440. };
  41441. // to override
  41442. /** @hidden */
  41443. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  41444. throw new Error("Abstract method");
  41445. };
  41446. _PrimitiveGeometry.prototype.copy = function (id) {
  41447. throw new Error("Must be overriden in sub-classes.");
  41448. };
  41449. _PrimitiveGeometry.prototype.serialize = function () {
  41450. var serializationObject = _super.prototype.serialize.call(this);
  41451. serializationObject.canBeRegenerated = this.canBeRegenerated();
  41452. return serializationObject;
  41453. };
  41454. return _PrimitiveGeometry;
  41455. }(Geometry));
  41456. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  41457. /**
  41458. * Creates a ribbon geometry
  41459. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  41460. */
  41461. var RibbonGeometry = /** @class */ (function (_super) {
  41462. __extends(RibbonGeometry, _super);
  41463. /**
  41464. * Creates a ribbon geometry
  41465. * @param id defines the unique ID of the geometry
  41466. * @param scene defines the hosting scene
  41467. * @param pathArray defines the array of paths to use
  41468. * @param closeArray defines if the last path and the first path must be joined
  41469. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  41470. * @param offset defines the offset between points
  41471. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41472. * @param mesh defines the hosting mesh (can be null)
  41473. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41474. */
  41475. function RibbonGeometry(id, scene,
  41476. /**
  41477. * Defines the array of paths to use
  41478. */
  41479. pathArray,
  41480. /**
  41481. * Defines if the last and first points of each path in your pathArray must be joined
  41482. */
  41483. closeArray,
  41484. /**
  41485. * Defines if the last and first points of each path in your pathArray must be joined
  41486. */
  41487. closePath,
  41488. /**
  41489. * Defines the offset between points
  41490. */
  41491. offset, canBeRegenerated, mesh,
  41492. /**
  41493. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41494. */
  41495. side) {
  41496. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41497. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41498. _this.pathArray = pathArray;
  41499. _this.closeArray = closeArray;
  41500. _this.closePath = closePath;
  41501. _this.offset = offset;
  41502. _this.side = side;
  41503. return _this;
  41504. }
  41505. /** @hidden */
  41506. RibbonGeometry.prototype._regenerateVertexData = function () {
  41507. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  41508. };
  41509. RibbonGeometry.prototype.copy = function (id) {
  41510. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  41511. };
  41512. return RibbonGeometry;
  41513. }(_PrimitiveGeometry));
  41514. BABYLON.RibbonGeometry = RibbonGeometry;
  41515. /**
  41516. * Creates a box geometry
  41517. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  41518. */
  41519. var BoxGeometry = /** @class */ (function (_super) {
  41520. __extends(BoxGeometry, _super);
  41521. /**
  41522. * Creates a box geometry
  41523. * @param id defines the unique ID of the geometry
  41524. * @param scene defines the hosting scene
  41525. * @param size defines the zise of the box (width, height and depth are the same)
  41526. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41527. * @param mesh defines the hosting mesh (can be null)
  41528. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41529. */
  41530. function BoxGeometry(id, scene,
  41531. /**
  41532. * Defines the zise of the box (width, height and depth are the same)
  41533. */
  41534. size, canBeRegenerated, mesh,
  41535. /**
  41536. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41537. */
  41538. side) {
  41539. if (mesh === void 0) { mesh = null; }
  41540. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41541. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41542. _this.size = size;
  41543. _this.side = side;
  41544. return _this;
  41545. }
  41546. /** @hidden */
  41547. BoxGeometry.prototype._regenerateVertexData = function () {
  41548. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  41549. };
  41550. BoxGeometry.prototype.copy = function (id) {
  41551. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  41552. };
  41553. BoxGeometry.prototype.serialize = function () {
  41554. var serializationObject = _super.prototype.serialize.call(this);
  41555. serializationObject.size = this.size;
  41556. return serializationObject;
  41557. };
  41558. BoxGeometry.Parse = function (parsedBox, scene) {
  41559. if (scene.getGeometryByID(parsedBox.id)) {
  41560. return null; // null since geometry could be something else than a box...
  41561. }
  41562. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  41563. if (BABYLON.Tags) {
  41564. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  41565. }
  41566. scene.pushGeometry(box, true);
  41567. return box;
  41568. };
  41569. return BoxGeometry;
  41570. }(_PrimitiveGeometry));
  41571. BABYLON.BoxGeometry = BoxGeometry;
  41572. /**
  41573. * Creates a sphere geometry
  41574. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  41575. */
  41576. var SphereGeometry = /** @class */ (function (_super) {
  41577. __extends(SphereGeometry, _super);
  41578. /**
  41579. * Create a new sphere geometry
  41580. * @param id defines the unique ID of the geometry
  41581. * @param scene defines the hosting scene
  41582. * @param segments defines the number of segments to use to create the sphere
  41583. * @param diameter defines the diameter of the sphere
  41584. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41585. * @param mesh defines the hosting mesh (can be null)
  41586. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41587. */
  41588. function SphereGeometry(id, scene,
  41589. /**
  41590. * Defines the number of segments to use to create the sphere
  41591. */
  41592. segments,
  41593. /**
  41594. * Defines the diameter of the sphere
  41595. */
  41596. diameter, canBeRegenerated, mesh,
  41597. /**
  41598. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41599. */
  41600. side) {
  41601. if (mesh === void 0) { mesh = null; }
  41602. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41603. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41604. _this.segments = segments;
  41605. _this.diameter = diameter;
  41606. _this.side = side;
  41607. return _this;
  41608. }
  41609. /** @hidden */
  41610. SphereGeometry.prototype._regenerateVertexData = function () {
  41611. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  41612. };
  41613. SphereGeometry.prototype.copy = function (id) {
  41614. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  41615. };
  41616. SphereGeometry.prototype.serialize = function () {
  41617. var serializationObject = _super.prototype.serialize.call(this);
  41618. serializationObject.segments = this.segments;
  41619. serializationObject.diameter = this.diameter;
  41620. return serializationObject;
  41621. };
  41622. SphereGeometry.Parse = function (parsedSphere, scene) {
  41623. if (scene.getGeometryByID(parsedSphere.id)) {
  41624. return null; // null since geometry could be something else than a sphere...
  41625. }
  41626. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  41627. if (BABYLON.Tags) {
  41628. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  41629. }
  41630. scene.pushGeometry(sphere, true);
  41631. return sphere;
  41632. };
  41633. return SphereGeometry;
  41634. }(_PrimitiveGeometry));
  41635. BABYLON.SphereGeometry = SphereGeometry;
  41636. /**
  41637. * Creates a disc geometry
  41638. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  41639. */
  41640. var DiscGeometry = /** @class */ (function (_super) {
  41641. __extends(DiscGeometry, _super);
  41642. /**
  41643. * Creates a new disc geometry
  41644. * @param id defines the unique ID of the geometry
  41645. * @param scene defines the hosting scene
  41646. * @param radius defines the radius of the disc
  41647. * @param tessellation defines the tesselation factor to apply to the disc
  41648. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41649. * @param mesh defines the hosting mesh (can be null)
  41650. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41651. */
  41652. function DiscGeometry(id, scene,
  41653. /**
  41654. * Defines the radius of the disc
  41655. */
  41656. radius,
  41657. /**
  41658. * Defines the tesselation factor to apply to the disc
  41659. */
  41660. tessellation, canBeRegenerated, mesh,
  41661. /**
  41662. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41663. */
  41664. side) {
  41665. if (mesh === void 0) { mesh = null; }
  41666. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41667. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41668. _this.radius = radius;
  41669. _this.tessellation = tessellation;
  41670. _this.side = side;
  41671. return _this;
  41672. }
  41673. /** @hidden */
  41674. DiscGeometry.prototype._regenerateVertexData = function () {
  41675. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  41676. };
  41677. DiscGeometry.prototype.copy = function (id) {
  41678. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  41679. };
  41680. return DiscGeometry;
  41681. }(_PrimitiveGeometry));
  41682. BABYLON.DiscGeometry = DiscGeometry;
  41683. /**
  41684. * Creates a new cylinder geometry
  41685. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  41686. */
  41687. var CylinderGeometry = /** @class */ (function (_super) {
  41688. __extends(CylinderGeometry, _super);
  41689. /**
  41690. * Creates a new cylinder geometry
  41691. * @param id defines the unique ID of the geometry
  41692. * @param scene defines the hosting scene
  41693. * @param height defines the height of the cylinder
  41694. * @param diameterTop defines the diameter of the cylinder's top cap
  41695. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  41696. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  41697. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  41698. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41699. * @param mesh defines the hosting mesh (can be null)
  41700. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41701. */
  41702. function CylinderGeometry(id, scene,
  41703. /**
  41704. * Defines the height of the cylinder
  41705. */
  41706. height,
  41707. /**
  41708. * Defines the diameter of the cylinder's top cap
  41709. */
  41710. diameterTop,
  41711. /**
  41712. * Defines the diameter of the cylinder's bottom cap
  41713. */
  41714. diameterBottom,
  41715. /**
  41716. * Defines the tessellation factor to apply to the cylinder
  41717. */
  41718. tessellation,
  41719. /**
  41720. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  41721. */
  41722. subdivisions, canBeRegenerated, mesh,
  41723. /**
  41724. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41725. */
  41726. side) {
  41727. if (subdivisions === void 0) { subdivisions = 1; }
  41728. if (mesh === void 0) { mesh = null; }
  41729. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41730. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41731. _this.height = height;
  41732. _this.diameterTop = diameterTop;
  41733. _this.diameterBottom = diameterBottom;
  41734. _this.tessellation = tessellation;
  41735. _this.subdivisions = subdivisions;
  41736. _this.side = side;
  41737. return _this;
  41738. }
  41739. /** @hidden */
  41740. CylinderGeometry.prototype._regenerateVertexData = function () {
  41741. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  41742. };
  41743. CylinderGeometry.prototype.copy = function (id) {
  41744. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  41745. };
  41746. CylinderGeometry.prototype.serialize = function () {
  41747. var serializationObject = _super.prototype.serialize.call(this);
  41748. serializationObject.height = this.height;
  41749. serializationObject.diameterTop = this.diameterTop;
  41750. serializationObject.diameterBottom = this.diameterBottom;
  41751. serializationObject.tessellation = this.tessellation;
  41752. return serializationObject;
  41753. };
  41754. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  41755. if (scene.getGeometryByID(parsedCylinder.id)) {
  41756. return null; // null since geometry could be something else than a cylinder...
  41757. }
  41758. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  41759. if (BABYLON.Tags) {
  41760. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  41761. }
  41762. scene.pushGeometry(cylinder, true);
  41763. return cylinder;
  41764. };
  41765. return CylinderGeometry;
  41766. }(_PrimitiveGeometry));
  41767. BABYLON.CylinderGeometry = CylinderGeometry;
  41768. /**
  41769. * Creates a new torus geometry
  41770. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  41771. */
  41772. var TorusGeometry = /** @class */ (function (_super) {
  41773. __extends(TorusGeometry, _super);
  41774. /**
  41775. * Creates a new torus geometry
  41776. * @param id defines the unique ID of the geometry
  41777. * @param scene defines the hosting scene
  41778. * @param diameter defines the diameter of the torus
  41779. * @param thickness defines the thickness of the torus (ie. internal diameter)
  41780. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  41781. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41782. * @param mesh defines the hosting mesh (can be null)
  41783. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41784. */
  41785. function TorusGeometry(id, scene,
  41786. /**
  41787. * Defines the diameter of the torus
  41788. */
  41789. diameter,
  41790. /**
  41791. * Defines the thickness of the torus (ie. internal diameter)
  41792. */
  41793. thickness,
  41794. /**
  41795. * Defines the tesselation factor to apply to the torus
  41796. */
  41797. tessellation, canBeRegenerated, mesh,
  41798. /**
  41799. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41800. */
  41801. side) {
  41802. if (mesh === void 0) { mesh = null; }
  41803. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41804. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41805. _this.diameter = diameter;
  41806. _this.thickness = thickness;
  41807. _this.tessellation = tessellation;
  41808. _this.side = side;
  41809. return _this;
  41810. }
  41811. /** @hidden */
  41812. TorusGeometry.prototype._regenerateVertexData = function () {
  41813. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  41814. };
  41815. TorusGeometry.prototype.copy = function (id) {
  41816. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  41817. };
  41818. TorusGeometry.prototype.serialize = function () {
  41819. var serializationObject = _super.prototype.serialize.call(this);
  41820. serializationObject.diameter = this.diameter;
  41821. serializationObject.thickness = this.thickness;
  41822. serializationObject.tessellation = this.tessellation;
  41823. return serializationObject;
  41824. };
  41825. TorusGeometry.Parse = function (parsedTorus, scene) {
  41826. if (scene.getGeometryByID(parsedTorus.id)) {
  41827. return null; // null since geometry could be something else than a torus...
  41828. }
  41829. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  41830. if (BABYLON.Tags) {
  41831. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  41832. }
  41833. scene.pushGeometry(torus, true);
  41834. return torus;
  41835. };
  41836. return TorusGeometry;
  41837. }(_PrimitiveGeometry));
  41838. BABYLON.TorusGeometry = TorusGeometry;
  41839. /**
  41840. * Creates a new ground geometry
  41841. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  41842. */
  41843. var GroundGeometry = /** @class */ (function (_super) {
  41844. __extends(GroundGeometry, _super);
  41845. /**
  41846. * Creates a new ground geometry
  41847. * @param id defines the unique ID of the geometry
  41848. * @param scene defines the hosting scene
  41849. * @param width defines the width of the ground
  41850. * @param height defines the height of the ground
  41851. * @param subdivisions defines the subdivisions to apply to the ground
  41852. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41853. * @param mesh defines the hosting mesh (can be null)
  41854. */
  41855. function GroundGeometry(id, scene,
  41856. /**
  41857. * Defines the width of the ground
  41858. */
  41859. width,
  41860. /**
  41861. * Defines the height of the ground
  41862. */
  41863. height,
  41864. /**
  41865. * Defines the subdivisions to apply to the ground
  41866. */
  41867. subdivisions, canBeRegenerated, mesh) {
  41868. if (mesh === void 0) { mesh = null; }
  41869. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41870. _this.width = width;
  41871. _this.height = height;
  41872. _this.subdivisions = subdivisions;
  41873. return _this;
  41874. }
  41875. /** @hidden */
  41876. GroundGeometry.prototype._regenerateVertexData = function () {
  41877. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  41878. };
  41879. GroundGeometry.prototype.copy = function (id) {
  41880. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  41881. };
  41882. GroundGeometry.prototype.serialize = function () {
  41883. var serializationObject = _super.prototype.serialize.call(this);
  41884. serializationObject.width = this.width;
  41885. serializationObject.height = this.height;
  41886. serializationObject.subdivisions = this.subdivisions;
  41887. return serializationObject;
  41888. };
  41889. GroundGeometry.Parse = function (parsedGround, scene) {
  41890. if (scene.getGeometryByID(parsedGround.id)) {
  41891. return null; // null since geometry could be something else than a ground...
  41892. }
  41893. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  41894. if (BABYLON.Tags) {
  41895. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  41896. }
  41897. scene.pushGeometry(ground, true);
  41898. return ground;
  41899. };
  41900. return GroundGeometry;
  41901. }(_PrimitiveGeometry));
  41902. BABYLON.GroundGeometry = GroundGeometry;
  41903. /**
  41904. * Creates a tiled ground geometry
  41905. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  41906. */
  41907. var TiledGroundGeometry = /** @class */ (function (_super) {
  41908. __extends(TiledGroundGeometry, _super);
  41909. /**
  41910. * Creates a tiled ground geometry
  41911. * @param id defines the unique ID of the geometry
  41912. * @param scene defines the hosting scene
  41913. * @param xmin defines the minimum value on X axis
  41914. * @param zmin defines the minimum value on Z axis
  41915. * @param xmax defines the maximum value on X axis
  41916. * @param zmax defines the maximum value on Z axis
  41917. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  41918. * @param precision defines the precision to use when computing the tiles
  41919. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41920. * @param mesh defines the hosting mesh (can be null)
  41921. */
  41922. function TiledGroundGeometry(id, scene,
  41923. /**
  41924. * Defines the minimum value on X axis
  41925. */
  41926. xmin,
  41927. /**
  41928. * Defines the minimum value on Z axis
  41929. */
  41930. zmin,
  41931. /**
  41932. * Defines the maximum value on X axis
  41933. */
  41934. xmax,
  41935. /**
  41936. * Defines the maximum value on Z axis
  41937. */
  41938. zmax,
  41939. /**
  41940. * Defines the subdivisions to apply to the ground
  41941. */
  41942. subdivisions,
  41943. /**
  41944. * Defines the precision to use when computing the tiles
  41945. */
  41946. precision, canBeRegenerated, mesh) {
  41947. if (mesh === void 0) { mesh = null; }
  41948. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41949. _this.xmin = xmin;
  41950. _this.zmin = zmin;
  41951. _this.xmax = xmax;
  41952. _this.zmax = zmax;
  41953. _this.subdivisions = subdivisions;
  41954. _this.precision = precision;
  41955. return _this;
  41956. }
  41957. /** @hidden */
  41958. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  41959. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  41960. };
  41961. TiledGroundGeometry.prototype.copy = function (id) {
  41962. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  41963. };
  41964. return TiledGroundGeometry;
  41965. }(_PrimitiveGeometry));
  41966. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  41967. /**
  41968. * Creates a plane geometry
  41969. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  41970. */
  41971. var PlaneGeometry = /** @class */ (function (_super) {
  41972. __extends(PlaneGeometry, _super);
  41973. /**
  41974. * Creates a plane geometry
  41975. * @param id defines the unique ID of the geometry
  41976. * @param scene defines the hosting scene
  41977. * @param size defines the size of the plane (width === height)
  41978. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41979. * @param mesh defines the hosting mesh (can be null)
  41980. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41981. */
  41982. function PlaneGeometry(id, scene,
  41983. /**
  41984. * Defines the size of the plane (width === height)
  41985. */
  41986. size, canBeRegenerated, mesh,
  41987. /**
  41988. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41989. */
  41990. side) {
  41991. if (mesh === void 0) { mesh = null; }
  41992. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41993. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41994. _this.size = size;
  41995. _this.side = side;
  41996. return _this;
  41997. }
  41998. /** @hidden */
  41999. PlaneGeometry.prototype._regenerateVertexData = function () {
  42000. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  42001. };
  42002. PlaneGeometry.prototype.copy = function (id) {
  42003. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  42004. };
  42005. PlaneGeometry.prototype.serialize = function () {
  42006. var serializationObject = _super.prototype.serialize.call(this);
  42007. serializationObject.size = this.size;
  42008. return serializationObject;
  42009. };
  42010. PlaneGeometry.Parse = function (parsedPlane, scene) {
  42011. if (scene.getGeometryByID(parsedPlane.id)) {
  42012. return null; // null since geometry could be something else than a ground...
  42013. }
  42014. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  42015. if (BABYLON.Tags) {
  42016. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  42017. }
  42018. scene.pushGeometry(plane, true);
  42019. return plane;
  42020. };
  42021. return PlaneGeometry;
  42022. }(_PrimitiveGeometry));
  42023. BABYLON.PlaneGeometry = PlaneGeometry;
  42024. /**
  42025. * Creates a torus knot geometry
  42026. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  42027. */
  42028. var TorusKnotGeometry = /** @class */ (function (_super) {
  42029. __extends(TorusKnotGeometry, _super);
  42030. /**
  42031. * Creates a torus knot geometry
  42032. * @param id defines the unique ID of the geometry
  42033. * @param scene defines the hosting scene
  42034. * @param radius defines the radius of the torus knot
  42035. * @param tube defines the thickness of the torus knot tube
  42036. * @param radialSegments defines the number of radial segments
  42037. * @param tubularSegments defines the number of tubular segments
  42038. * @param p defines the first number of windings
  42039. * @param q defines the second number of windings
  42040. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42041. * @param mesh defines the hosting mesh (can be null)
  42042. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42043. */
  42044. function TorusKnotGeometry(id, scene,
  42045. /**
  42046. * Defines the radius of the torus knot
  42047. */
  42048. radius,
  42049. /**
  42050. * Defines the thickness of the torus knot tube
  42051. */
  42052. tube,
  42053. /**
  42054. * Defines the number of radial segments
  42055. */
  42056. radialSegments,
  42057. /**
  42058. * Defines the number of tubular segments
  42059. */
  42060. tubularSegments,
  42061. /**
  42062. * Defines the first number of windings
  42063. */
  42064. p,
  42065. /**
  42066. * Defines the second number of windings
  42067. */
  42068. q, canBeRegenerated, mesh,
  42069. /**
  42070. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42071. */
  42072. side) {
  42073. if (mesh === void 0) { mesh = null; }
  42074. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42075. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42076. _this.radius = radius;
  42077. _this.tube = tube;
  42078. _this.radialSegments = radialSegments;
  42079. _this.tubularSegments = tubularSegments;
  42080. _this.p = p;
  42081. _this.q = q;
  42082. _this.side = side;
  42083. return _this;
  42084. }
  42085. /** @hidden */
  42086. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  42087. 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 });
  42088. };
  42089. TorusKnotGeometry.prototype.copy = function (id) {
  42090. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  42091. };
  42092. TorusKnotGeometry.prototype.serialize = function () {
  42093. var serializationObject = _super.prototype.serialize.call(this);
  42094. serializationObject.radius = this.radius;
  42095. serializationObject.tube = this.tube;
  42096. serializationObject.radialSegments = this.radialSegments;
  42097. serializationObject.tubularSegments = this.tubularSegments;
  42098. serializationObject.p = this.p;
  42099. serializationObject.q = this.q;
  42100. return serializationObject;
  42101. };
  42102. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  42103. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  42104. return null; // null since geometry could be something else than a ground...
  42105. }
  42106. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  42107. if (BABYLON.Tags) {
  42108. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  42109. }
  42110. scene.pushGeometry(torusKnot, true);
  42111. return torusKnot;
  42112. };
  42113. return TorusKnotGeometry;
  42114. }(_PrimitiveGeometry));
  42115. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  42116. //}
  42117. })(BABYLON || (BABYLON = {}));
  42118. //# sourceMappingURL=babylon.geometry.js.map
  42119. var BABYLON;
  42120. (function (BABYLON) {
  42121. /**
  42122. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  42123. */
  42124. var PerformanceMonitor = /** @class */ (function () {
  42125. /**
  42126. * constructor
  42127. * @param frameSampleSize The number of samples required to saturate the sliding window
  42128. */
  42129. function PerformanceMonitor(frameSampleSize) {
  42130. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  42131. this._enabled = true;
  42132. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  42133. }
  42134. /**
  42135. * Samples current frame
  42136. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  42137. */
  42138. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  42139. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  42140. if (!this._enabled) {
  42141. return;
  42142. }
  42143. if (this._lastFrameTimeMs != null) {
  42144. var dt = timeMs - this._lastFrameTimeMs;
  42145. this._rollingFrameTime.add(dt);
  42146. }
  42147. this._lastFrameTimeMs = timeMs;
  42148. };
  42149. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  42150. /**
  42151. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  42152. */
  42153. get: function () {
  42154. return this._rollingFrameTime.average;
  42155. },
  42156. enumerable: true,
  42157. configurable: true
  42158. });
  42159. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  42160. /**
  42161. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  42162. */
  42163. get: function () {
  42164. return this._rollingFrameTime.variance;
  42165. },
  42166. enumerable: true,
  42167. configurable: true
  42168. });
  42169. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  42170. /**
  42171. * Returns the frame time of the most recent frame
  42172. */
  42173. get: function () {
  42174. return this._rollingFrameTime.history(0);
  42175. },
  42176. enumerable: true,
  42177. configurable: true
  42178. });
  42179. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  42180. /**
  42181. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  42182. */
  42183. get: function () {
  42184. return 1000.0 / this._rollingFrameTime.average;
  42185. },
  42186. enumerable: true,
  42187. configurable: true
  42188. });
  42189. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  42190. /**
  42191. * Returns the average framerate in frames per second using the most recent frame time
  42192. */
  42193. get: function () {
  42194. var history = this._rollingFrameTime.history(0);
  42195. if (history === 0) {
  42196. return 0;
  42197. }
  42198. return 1000.0 / history;
  42199. },
  42200. enumerable: true,
  42201. configurable: true
  42202. });
  42203. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  42204. /**
  42205. * Returns true if enough samples have been taken to completely fill the sliding window
  42206. */
  42207. get: function () {
  42208. return this._rollingFrameTime.isSaturated();
  42209. },
  42210. enumerable: true,
  42211. configurable: true
  42212. });
  42213. /**
  42214. * Enables contributions to the sliding window sample set
  42215. */
  42216. PerformanceMonitor.prototype.enable = function () {
  42217. this._enabled = true;
  42218. };
  42219. /**
  42220. * Disables contributions to the sliding window sample set
  42221. * Samples will not be interpolated over the disabled period
  42222. */
  42223. PerformanceMonitor.prototype.disable = function () {
  42224. this._enabled = false;
  42225. //clear last sample to avoid interpolating over the disabled period when next enabled
  42226. this._lastFrameTimeMs = null;
  42227. };
  42228. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  42229. /**
  42230. * Returns true if sampling is enabled
  42231. */
  42232. get: function () {
  42233. return this._enabled;
  42234. },
  42235. enumerable: true,
  42236. configurable: true
  42237. });
  42238. /**
  42239. * Resets performance monitor
  42240. */
  42241. PerformanceMonitor.prototype.reset = function () {
  42242. //clear last sample to avoid interpolating over the disabled period when next enabled
  42243. this._lastFrameTimeMs = null;
  42244. //wipe record
  42245. this._rollingFrameTime.reset();
  42246. };
  42247. return PerformanceMonitor;
  42248. }());
  42249. BABYLON.PerformanceMonitor = PerformanceMonitor;
  42250. /**
  42251. * RollingAverage
  42252. *
  42253. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  42254. */
  42255. var RollingAverage = /** @class */ (function () {
  42256. /**
  42257. * constructor
  42258. * @param length The number of samples required to saturate the sliding window
  42259. */
  42260. function RollingAverage(length) {
  42261. this._samples = new Array(length);
  42262. this.reset();
  42263. }
  42264. /**
  42265. * Adds a sample to the sample set
  42266. * @param v The sample value
  42267. */
  42268. RollingAverage.prototype.add = function (v) {
  42269. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  42270. var delta;
  42271. //we need to check if we've already wrapped round
  42272. if (this.isSaturated()) {
  42273. //remove bottom of stack from mean
  42274. var bottomValue = this._samples[this._pos];
  42275. delta = bottomValue - this.average;
  42276. this.average -= delta / (this._sampleCount - 1);
  42277. this._m2 -= delta * (bottomValue - this.average);
  42278. }
  42279. else {
  42280. this._sampleCount++;
  42281. }
  42282. //add new value to mean
  42283. delta = v - this.average;
  42284. this.average += delta / (this._sampleCount);
  42285. this._m2 += delta * (v - this.average);
  42286. //set the new variance
  42287. this.variance = this._m2 / (this._sampleCount - 1);
  42288. this._samples[this._pos] = v;
  42289. this._pos++;
  42290. this._pos %= this._samples.length; //positive wrap around
  42291. };
  42292. /**
  42293. * Returns previously added values or null if outside of history or outside the sliding window domain
  42294. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  42295. * @return Value previously recorded with add() or null if outside of range
  42296. */
  42297. RollingAverage.prototype.history = function (i) {
  42298. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  42299. return 0;
  42300. }
  42301. var i0 = this._wrapPosition(this._pos - 1.0);
  42302. return this._samples[this._wrapPosition(i0 - i)];
  42303. };
  42304. /**
  42305. * Returns true if enough samples have been taken to completely fill the sliding window
  42306. * @return true if sample-set saturated
  42307. */
  42308. RollingAverage.prototype.isSaturated = function () {
  42309. return this._sampleCount >= this._samples.length;
  42310. };
  42311. /**
  42312. * Resets the rolling average (equivalent to 0 samples taken so far)
  42313. */
  42314. RollingAverage.prototype.reset = function () {
  42315. this.average = 0;
  42316. this.variance = 0;
  42317. this._sampleCount = 0;
  42318. this._pos = 0;
  42319. this._m2 = 0;
  42320. };
  42321. /**
  42322. * Wraps a value around the sample range boundaries
  42323. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  42324. * @return Wrapped position in sample range
  42325. */
  42326. RollingAverage.prototype._wrapPosition = function (i) {
  42327. var max = this._samples.length;
  42328. return ((i % max) + max) % max;
  42329. };
  42330. return RollingAverage;
  42331. }());
  42332. BABYLON.RollingAverage = RollingAverage;
  42333. })(BABYLON || (BABYLON = {}));
  42334. //# sourceMappingURL=babylon.performanceMonitor.js.map
  42335. var BABYLON;
  42336. (function (BABYLON) {
  42337. /**
  42338. * "Static Class" containing the most commonly used helper while dealing with material for
  42339. * rendering purpose.
  42340. *
  42341. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42342. *
  42343. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42344. */
  42345. var MaterialHelper = /** @class */ (function () {
  42346. function MaterialHelper() {
  42347. }
  42348. /**
  42349. * Bind the current view position to an effect.
  42350. * @param effect The effect to be bound
  42351. * @param scene The scene the eyes position is used from
  42352. */
  42353. MaterialHelper.BindEyePosition = function (effect, scene) {
  42354. if (scene._forcedViewPosition) {
  42355. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42356. return;
  42357. }
  42358. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42359. };
  42360. /**
  42361. * Helps preparing the defines values about the UVs in used in the effect.
  42362. * UVs are shared as much as we can accross channels in the shaders.
  42363. * @param texture The texture we are preparing the UVs for
  42364. * @param defines The defines to update
  42365. * @param key The channel key "diffuse", "specular"... used in the shader
  42366. */
  42367. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42368. defines._needUVs = true;
  42369. defines[key] = true;
  42370. if (texture.getTextureMatrix().isIdentity(true)) {
  42371. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42372. if (texture.coordinatesIndex === 0) {
  42373. defines["MAINUV1"] = true;
  42374. }
  42375. else {
  42376. defines["MAINUV2"] = true;
  42377. }
  42378. }
  42379. else {
  42380. defines[key + "DIRECTUV"] = 0;
  42381. }
  42382. };
  42383. /**
  42384. * Binds a texture matrix value to its corrsponding uniform
  42385. * @param texture The texture to bind the matrix for
  42386. * @param uniformBuffer The uniform buffer receivin the data
  42387. * @param key The channel key "diffuse", "specular"... used in the shader
  42388. */
  42389. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42390. var matrix = texture.getTextureMatrix();
  42391. if (!matrix.isIdentity(true)) {
  42392. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42393. }
  42394. };
  42395. /**
  42396. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42397. * @param mesh defines the current mesh
  42398. * @param scene defines the current scene
  42399. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42400. * @param pointsCloud defines if point cloud rendering has to be turned on
  42401. * @param fogEnabled defines if fog has to be turned on
  42402. * @param alphaTest defines if alpha testing has to be turned on
  42403. * @param defines defines the current list of defines
  42404. */
  42405. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42406. if (defines._areMiscDirty) {
  42407. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42408. defines["POINTSIZE"] = pointsCloud;
  42409. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42410. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42411. defines["ALPHATEST"] = alphaTest;
  42412. }
  42413. };
  42414. /**
  42415. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42416. * @param scene defines the current scene
  42417. * @param engine defines the current engine
  42418. * @param defines specifies the list of active defines
  42419. * @param useInstances defines if instances have to be turned on
  42420. * @param useClipPlane defines if clip plane have to be turned on
  42421. */
  42422. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42423. if (useClipPlane === void 0) { useClipPlane = null; }
  42424. var changed = false;
  42425. var useClipPlane1 = false;
  42426. var useClipPlane2 = false;
  42427. var useClipPlane3 = false;
  42428. var useClipPlane4 = false;
  42429. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  42430. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  42431. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  42432. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  42433. if (defines["CLIPPLANE"] !== useClipPlane1) {
  42434. defines["CLIPPLANE"] = useClipPlane1;
  42435. changed = true;
  42436. }
  42437. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  42438. defines["CLIPPLANE2"] = useClipPlane2;
  42439. changed = true;
  42440. }
  42441. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  42442. defines["CLIPPLANE3"] = useClipPlane3;
  42443. changed = true;
  42444. }
  42445. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  42446. defines["CLIPPLANE4"] = useClipPlane4;
  42447. changed = true;
  42448. }
  42449. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42450. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42451. changed = true;
  42452. }
  42453. if (defines["INSTANCES"] !== useInstances) {
  42454. defines["INSTANCES"] = useInstances;
  42455. changed = true;
  42456. }
  42457. if (changed) {
  42458. defines.markAsUnprocessed();
  42459. }
  42460. };
  42461. /**
  42462. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42463. * @param mesh The mesh containing the geometry data we will draw
  42464. * @param defines The defines to update
  42465. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42466. * @param useBones Precise whether bones should be used or not (override mesh info)
  42467. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42468. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42469. * @returns false if defines are considered not dirty and have not been checked
  42470. */
  42471. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42472. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42473. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42474. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42475. return false;
  42476. }
  42477. defines._normals = defines._needNormals;
  42478. defines._uvs = defines._needUVs;
  42479. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42480. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42481. defines["TANGENT"] = true;
  42482. }
  42483. if (defines._needUVs) {
  42484. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42485. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42486. }
  42487. else {
  42488. defines["UV1"] = false;
  42489. defines["UV2"] = false;
  42490. }
  42491. if (useVertexColor) {
  42492. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42493. defines["VERTEXCOLOR"] = hasVertexColors;
  42494. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42495. }
  42496. if (useBones) {
  42497. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42498. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42499. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42500. }
  42501. else {
  42502. defines["NUM_BONE_INFLUENCERS"] = 0;
  42503. defines["BonesPerMesh"] = 0;
  42504. }
  42505. }
  42506. if (useMorphTargets) {
  42507. var manager = mesh.morphTargetManager;
  42508. if (manager) {
  42509. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42510. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42511. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42512. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42513. }
  42514. else {
  42515. defines["MORPHTARGETS_TANGENT"] = false;
  42516. defines["MORPHTARGETS_NORMAL"] = false;
  42517. defines["MORPHTARGETS"] = false;
  42518. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42519. }
  42520. }
  42521. return true;
  42522. };
  42523. /**
  42524. * Prepares the defines related to the light information passed in parameter
  42525. * @param scene The scene we are intending to draw
  42526. * @param mesh The mesh the effect is compiling for
  42527. * @param defines The defines to update
  42528. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42529. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42530. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42531. * @returns true if normals will be required for the rest of the effect
  42532. */
  42533. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42534. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42535. if (disableLighting === void 0) { disableLighting = false; }
  42536. if (!defines._areLightsDirty) {
  42537. return defines._needNormals;
  42538. }
  42539. var lightIndex = 0;
  42540. var needNormals = false;
  42541. var needRebuild = false;
  42542. var lightmapMode = false;
  42543. var shadowEnabled = false;
  42544. var specularEnabled = false;
  42545. if (scene.lightsEnabled && !disableLighting) {
  42546. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42547. var light = _a[_i];
  42548. needNormals = true;
  42549. if (defines["LIGHT" + lightIndex] === undefined) {
  42550. needRebuild = true;
  42551. }
  42552. defines["LIGHT" + lightIndex] = true;
  42553. defines["SPOTLIGHT" + lightIndex] = false;
  42554. defines["HEMILIGHT" + lightIndex] = false;
  42555. defines["POINTLIGHT" + lightIndex] = false;
  42556. defines["DIRLIGHT" + lightIndex] = false;
  42557. light.prepareLightSpecificDefines(defines, lightIndex);
  42558. // FallOff.
  42559. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  42560. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  42561. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  42562. switch (light.falloffType) {
  42563. case BABYLON.Light.FALLOFF_GLTF:
  42564. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  42565. break;
  42566. case BABYLON.Light.FALLOFF_PHYSICAL:
  42567. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  42568. break;
  42569. case BABYLON.Light.FALLOFF_STANDARD:
  42570. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  42571. break;
  42572. }
  42573. // Specular
  42574. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42575. specularEnabled = true;
  42576. }
  42577. // Shadows
  42578. defines["SHADOW" + lightIndex] = false;
  42579. defines["SHADOWPCF" + lightIndex] = false;
  42580. defines["SHADOWPCSS" + lightIndex] = false;
  42581. defines["SHADOWPOISSON" + lightIndex] = false;
  42582. defines["SHADOWESM" + lightIndex] = false;
  42583. defines["SHADOWCUBE" + lightIndex] = false;
  42584. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42585. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42586. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42587. var shadowGenerator = light.getShadowGenerator();
  42588. if (shadowGenerator) {
  42589. var shadowMap = shadowGenerator.getShadowMap();
  42590. if (shadowMap) {
  42591. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  42592. shadowEnabled = true;
  42593. shadowGenerator.prepareDefines(defines, lightIndex);
  42594. }
  42595. }
  42596. }
  42597. }
  42598. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42599. lightmapMode = true;
  42600. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42601. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42602. }
  42603. else {
  42604. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42605. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42606. }
  42607. lightIndex++;
  42608. if (lightIndex === maxSimultaneousLights) {
  42609. break;
  42610. }
  42611. }
  42612. }
  42613. defines["SPECULARTERM"] = specularEnabled;
  42614. defines["SHADOWS"] = shadowEnabled;
  42615. // Resetting all other lights if any
  42616. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42617. if (defines["LIGHT" + index] !== undefined) {
  42618. defines["LIGHT" + index] = false;
  42619. defines["HEMILIGHT" + lightIndex] = false;
  42620. defines["POINTLIGHT" + lightIndex] = false;
  42621. defines["DIRLIGHT" + lightIndex] = false;
  42622. defines["SPOTLIGHT" + lightIndex] = false;
  42623. defines["SHADOW" + lightIndex] = false;
  42624. }
  42625. }
  42626. var caps = scene.getEngine().getCaps();
  42627. if (defines["SHADOWFLOAT"] === undefined) {
  42628. needRebuild = true;
  42629. }
  42630. defines["SHADOWFLOAT"] = shadowEnabled &&
  42631. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42632. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42633. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42634. if (needRebuild) {
  42635. defines.rebuild();
  42636. }
  42637. return needNormals;
  42638. };
  42639. /**
  42640. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42641. * that won t be acctive due to defines being turned off.
  42642. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42643. * @param samplersList The samplers list
  42644. * @param defines The defines helping in the list generation
  42645. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42646. */
  42647. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42648. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42649. var uniformsList;
  42650. var uniformBuffersList = null;
  42651. if (uniformsListOrOptions.uniformsNames) {
  42652. var options = uniformsListOrOptions;
  42653. uniformsList = options.uniformsNames;
  42654. uniformBuffersList = options.uniformBuffersNames;
  42655. samplersList = options.samplers;
  42656. defines = options.defines;
  42657. maxSimultaneousLights = options.maxSimultaneousLights;
  42658. }
  42659. else {
  42660. uniformsList = uniformsListOrOptions;
  42661. if (!samplersList) {
  42662. samplersList = [];
  42663. }
  42664. }
  42665. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42666. if (!defines["LIGHT" + lightIndex]) {
  42667. break;
  42668. }
  42669. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42670. if (uniformBuffersList) {
  42671. uniformBuffersList.push("Light" + lightIndex);
  42672. }
  42673. samplersList.push("shadowSampler" + lightIndex);
  42674. samplersList.push("depthSampler" + lightIndex);
  42675. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42676. samplersList.push("projectionLightSampler" + lightIndex);
  42677. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42678. }
  42679. }
  42680. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42681. uniformsList.push("morphTargetInfluences");
  42682. }
  42683. };
  42684. /**
  42685. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42686. * @param defines The defines to update while falling back
  42687. * @param fallbacks The authorized effect fallbacks
  42688. * @param maxSimultaneousLights The maximum number of lights allowed
  42689. * @param rank the current rank of the Effect
  42690. * @returns The newly affected rank
  42691. */
  42692. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42693. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42694. if (rank === void 0) { rank = 0; }
  42695. var lightFallbackRank = 0;
  42696. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42697. if (!defines["LIGHT" + lightIndex]) {
  42698. break;
  42699. }
  42700. if (lightIndex > 0) {
  42701. lightFallbackRank = rank + lightIndex;
  42702. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42703. }
  42704. if (!defines["SHADOWS"]) {
  42705. if (defines["SHADOW" + lightIndex]) {
  42706. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42707. }
  42708. if (defines["SHADOWPCF" + lightIndex]) {
  42709. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42710. }
  42711. if (defines["SHADOWPCSS" + lightIndex]) {
  42712. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42713. }
  42714. if (defines["SHADOWPOISSON" + lightIndex]) {
  42715. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42716. }
  42717. if (defines["SHADOWESM" + lightIndex]) {
  42718. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42719. }
  42720. }
  42721. }
  42722. return lightFallbackRank++;
  42723. };
  42724. /**
  42725. * Prepares the list of attributes required for morph targets according to the effect defines.
  42726. * @param attribs The current list of supported attribs
  42727. * @param mesh The mesh to prepare the morph targets attributes for
  42728. * @param defines The current Defines of the effect
  42729. */
  42730. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42731. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42732. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42733. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42734. var manager = mesh.morphTargetManager;
  42735. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42736. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42737. for (var index = 0; index < influencers; index++) {
  42738. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42739. if (normal) {
  42740. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42741. }
  42742. if (tangent) {
  42743. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42744. }
  42745. if (attribs.length > maxAttributesCount) {
  42746. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42747. }
  42748. }
  42749. }
  42750. };
  42751. /**
  42752. * Prepares the list of attributes required for bones according to the effect defines.
  42753. * @param attribs The current list of supported attribs
  42754. * @param mesh The mesh to prepare the bones attributes for
  42755. * @param defines The current Defines of the effect
  42756. * @param fallbacks The current efffect fallback strategy
  42757. */
  42758. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42759. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42760. fallbacks.addCPUSkinningFallback(0, mesh);
  42761. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42762. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42763. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42764. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42765. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42766. }
  42767. }
  42768. };
  42769. /**
  42770. * Prepares the list of attributes required for instances according to the effect defines.
  42771. * @param attribs The current list of supported attribs
  42772. * @param defines The current Defines of the effect
  42773. */
  42774. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42775. if (defines["INSTANCES"]) {
  42776. attribs.push("world0");
  42777. attribs.push("world1");
  42778. attribs.push("world2");
  42779. attribs.push("world3");
  42780. }
  42781. };
  42782. /**
  42783. * Binds the light shadow information to the effect for the given mesh.
  42784. * @param light The light containing the generator
  42785. * @param scene The scene the lights belongs to
  42786. * @param mesh The mesh we are binding the information to render
  42787. * @param lightIndex The light index in the effect used to render the mesh
  42788. * @param effect The effect we are binding the data to
  42789. */
  42790. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42791. if (light.shadowEnabled && mesh.receiveShadows) {
  42792. var shadowGenerator = light.getShadowGenerator();
  42793. if (shadowGenerator) {
  42794. shadowGenerator.bindShadowLight(lightIndex, effect);
  42795. }
  42796. }
  42797. };
  42798. /**
  42799. * Binds the light information to the effect.
  42800. * @param light The light containing the generator
  42801. * @param effect The effect we are binding the data to
  42802. * @param lightIndex The light index in the effect used to render
  42803. */
  42804. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42805. light.transferToEffect(effect, lightIndex + "");
  42806. };
  42807. /**
  42808. * Binds the lights information from the scene to the effect for the given mesh.
  42809. * @param scene The scene the lights belongs to
  42810. * @param mesh The mesh we are binding the information to render
  42811. * @param effect The effect we are binding the data to
  42812. * @param defines The generated defines for the effect
  42813. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42814. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42815. */
  42816. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42817. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42818. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42819. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42820. for (var i = 0; i < len; i++) {
  42821. var light = mesh._lightSources[i];
  42822. var iAsString = i.toString();
  42823. var scaledIntensity = light.getScaledIntensity();
  42824. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42825. MaterialHelper.BindLightProperties(light, effect, i);
  42826. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42827. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42828. if (defines["SPECULARTERM"]) {
  42829. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42830. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42831. }
  42832. // Shadows
  42833. if (scene.shadowsEnabled) {
  42834. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42835. }
  42836. light._uniformBuffer.update();
  42837. }
  42838. };
  42839. /**
  42840. * Binds the fog information from the scene to the effect for the given mesh.
  42841. * @param scene The scene the lights belongs to
  42842. * @param mesh The mesh we are binding the information to render
  42843. * @param effect The effect we are binding the data to
  42844. * @param linearSpace Defines if the fog effect is applied in linear space
  42845. */
  42846. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  42847. if (linearSpace === void 0) { linearSpace = false; }
  42848. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42849. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42850. // Convert fog color to linear space if used in a linear space computed shader.
  42851. if (linearSpace) {
  42852. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  42853. effect.setColor3("vFogColor", this._tempFogColor);
  42854. }
  42855. else {
  42856. effect.setColor3("vFogColor", scene.fogColor);
  42857. }
  42858. }
  42859. };
  42860. /**
  42861. * Binds the bones information from the mesh to the effect.
  42862. * @param mesh The mesh we are binding the information to render
  42863. * @param effect The effect we are binding the data to
  42864. */
  42865. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42866. if (!effect || !mesh) {
  42867. return;
  42868. }
  42869. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42870. mesh.computeBonesUsingShaders = false;
  42871. }
  42872. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42873. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42874. if (matrices) {
  42875. effect.setMatrices("mBones", matrices);
  42876. }
  42877. }
  42878. };
  42879. /**
  42880. * Binds the morph targets information from the mesh to the effect.
  42881. * @param abstractMesh The mesh we are binding the information to render
  42882. * @param effect The effect we are binding the data to
  42883. */
  42884. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42885. var manager = abstractMesh.morphTargetManager;
  42886. if (!abstractMesh || !manager) {
  42887. return;
  42888. }
  42889. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42890. };
  42891. /**
  42892. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42893. * @param defines The generated defines used in the effect
  42894. * @param effect The effect we are binding the data to
  42895. * @param scene The scene we are willing to render with logarithmic scale for
  42896. */
  42897. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42898. if (defines["LOGARITHMICDEPTH"]) {
  42899. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42900. }
  42901. };
  42902. /**
  42903. * Binds the clip plane information from the scene to the effect.
  42904. * @param scene The scene the clip plane information are extracted from
  42905. * @param effect The effect we are binding the data to
  42906. */
  42907. MaterialHelper.BindClipPlane = function (effect, scene) {
  42908. if (scene.clipPlane) {
  42909. var clipPlane = scene.clipPlane;
  42910. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42911. }
  42912. if (scene.clipPlane2) {
  42913. var clipPlane = scene.clipPlane2;
  42914. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42915. }
  42916. if (scene.clipPlane3) {
  42917. var clipPlane = scene.clipPlane3;
  42918. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42919. }
  42920. if (scene.clipPlane4) {
  42921. var clipPlane = scene.clipPlane4;
  42922. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42923. }
  42924. };
  42925. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  42926. return MaterialHelper;
  42927. }());
  42928. BABYLON.MaterialHelper = MaterialHelper;
  42929. })(BABYLON || (BABYLON = {}));
  42930. //# sourceMappingURL=babylon.materialHelper.js.map
  42931. var BABYLON;
  42932. (function (BABYLON) {
  42933. /**
  42934. * Base class of materials working in push mode in babylon JS
  42935. * @hidden
  42936. */
  42937. var PushMaterial = /** @class */ (function (_super) {
  42938. __extends(PushMaterial, _super);
  42939. function PushMaterial(name, scene) {
  42940. var _this = _super.call(this, name, scene) || this;
  42941. _this._normalMatrix = new BABYLON.Matrix();
  42942. _this.storeEffectOnSubMeshes = true;
  42943. return _this;
  42944. }
  42945. PushMaterial.prototype.getEffect = function () {
  42946. return this._activeEffect;
  42947. };
  42948. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42949. if (!mesh) {
  42950. return false;
  42951. }
  42952. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42953. return true;
  42954. }
  42955. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42956. };
  42957. /**
  42958. * Binds the given world matrix to the active effect
  42959. *
  42960. * @param world the matrix to bind
  42961. */
  42962. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42963. this._activeEffect.setMatrix("world", world);
  42964. };
  42965. /**
  42966. * Binds the given normal matrix to the active effect
  42967. *
  42968. * @param normalMatrix the matrix to bind
  42969. */
  42970. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42971. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42972. };
  42973. PushMaterial.prototype.bind = function (world, mesh) {
  42974. if (!mesh) {
  42975. return;
  42976. }
  42977. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42978. };
  42979. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42980. if (effect === void 0) { effect = null; }
  42981. _super.prototype._afterBind.call(this, mesh);
  42982. this.getScene()._cachedEffect = effect;
  42983. };
  42984. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42985. if (visibility === void 0) { visibility = 1; }
  42986. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42987. };
  42988. return PushMaterial;
  42989. }(BABYLON.Material));
  42990. BABYLON.PushMaterial = PushMaterial;
  42991. })(BABYLON || (BABYLON = {}));
  42992. //# sourceMappingURL=babylon.pushMaterial.js.map
  42993. var BABYLON;
  42994. (function (BABYLON) {
  42995. /** @hidden */
  42996. var StandardMaterialDefines = /** @class */ (function (_super) {
  42997. __extends(StandardMaterialDefines, _super);
  42998. function StandardMaterialDefines() {
  42999. var _this = _super.call(this) || this;
  43000. _this.MAINUV1 = false;
  43001. _this.MAINUV2 = false;
  43002. _this.DIFFUSE = false;
  43003. _this.DIFFUSEDIRECTUV = 0;
  43004. _this.AMBIENT = false;
  43005. _this.AMBIENTDIRECTUV = 0;
  43006. _this.OPACITY = false;
  43007. _this.OPACITYDIRECTUV = 0;
  43008. _this.OPACITYRGB = false;
  43009. _this.REFLECTION = false;
  43010. _this.EMISSIVE = false;
  43011. _this.EMISSIVEDIRECTUV = 0;
  43012. _this.SPECULAR = false;
  43013. _this.SPECULARDIRECTUV = 0;
  43014. _this.BUMP = false;
  43015. _this.BUMPDIRECTUV = 0;
  43016. _this.PARALLAX = false;
  43017. _this.PARALLAXOCCLUSION = false;
  43018. _this.SPECULAROVERALPHA = false;
  43019. _this.CLIPPLANE = false;
  43020. _this.CLIPPLANE2 = false;
  43021. _this.CLIPPLANE3 = false;
  43022. _this.CLIPPLANE4 = false;
  43023. _this.ALPHATEST = false;
  43024. _this.DEPTHPREPASS = false;
  43025. _this.ALPHAFROMDIFFUSE = false;
  43026. _this.POINTSIZE = false;
  43027. _this.FOG = false;
  43028. _this.SPECULARTERM = false;
  43029. _this.DIFFUSEFRESNEL = false;
  43030. _this.OPACITYFRESNEL = false;
  43031. _this.REFLECTIONFRESNEL = false;
  43032. _this.REFRACTIONFRESNEL = false;
  43033. _this.EMISSIVEFRESNEL = false;
  43034. _this.FRESNEL = false;
  43035. _this.NORMAL = false;
  43036. _this.UV1 = false;
  43037. _this.UV2 = false;
  43038. _this.VERTEXCOLOR = false;
  43039. _this.VERTEXALPHA = false;
  43040. _this.NUM_BONE_INFLUENCERS = 0;
  43041. _this.BonesPerMesh = 0;
  43042. _this.INSTANCES = false;
  43043. _this.GLOSSINESS = false;
  43044. _this.ROUGHNESS = false;
  43045. _this.EMISSIVEASILLUMINATION = false;
  43046. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43047. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43048. _this.LIGHTMAP = false;
  43049. _this.LIGHTMAPDIRECTUV = 0;
  43050. _this.OBJECTSPACE_NORMALMAP = false;
  43051. _this.USELIGHTMAPASSHADOWMAP = false;
  43052. _this.REFLECTIONMAP_3D = false;
  43053. _this.REFLECTIONMAP_SPHERICAL = false;
  43054. _this.REFLECTIONMAP_PLANAR = false;
  43055. _this.REFLECTIONMAP_CUBIC = false;
  43056. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43057. _this.REFLECTIONMAP_PROJECTION = false;
  43058. _this.REFLECTIONMAP_SKYBOX = false;
  43059. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43060. _this.REFLECTIONMAP_EXPLICIT = false;
  43061. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43062. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43063. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43064. _this.INVERTCUBICMAP = false;
  43065. _this.LOGARITHMICDEPTH = false;
  43066. _this.REFRACTION = false;
  43067. _this.REFRACTIONMAP_3D = false;
  43068. _this.REFLECTIONOVERALPHA = false;
  43069. _this.TWOSIDEDLIGHTING = false;
  43070. _this.SHADOWFLOAT = false;
  43071. _this.MORPHTARGETS = false;
  43072. _this.MORPHTARGETS_NORMAL = false;
  43073. _this.MORPHTARGETS_TANGENT = false;
  43074. _this.NUM_MORPH_INFLUENCERS = 0;
  43075. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  43076. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  43077. _this.IMAGEPROCESSING = false;
  43078. _this.VIGNETTE = false;
  43079. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43080. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43081. _this.TONEMAPPING = false;
  43082. _this.TONEMAPPING_ACES = false;
  43083. _this.CONTRAST = false;
  43084. _this.COLORCURVES = false;
  43085. _this.COLORGRADING = false;
  43086. _this.COLORGRADING3D = false;
  43087. _this.SAMPLER3DGREENDEPTH = false;
  43088. _this.SAMPLER3DBGRMAP = false;
  43089. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43090. /**
  43091. * If the reflection texture on this material is in linear color space
  43092. * @hidden
  43093. */
  43094. _this.IS_REFLECTION_LINEAR = false;
  43095. /**
  43096. * If the refraction texture on this material is in linear color space
  43097. * @hidden
  43098. */
  43099. _this.IS_REFRACTION_LINEAR = false;
  43100. _this.EXPOSURE = false;
  43101. _this.rebuild();
  43102. return _this;
  43103. }
  43104. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43105. var modes = [
  43106. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43107. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43108. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43109. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43110. ];
  43111. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43112. var mode = modes_1[_i];
  43113. this[mode] = (mode === modeToEnable);
  43114. }
  43115. };
  43116. return StandardMaterialDefines;
  43117. }(BABYLON.MaterialDefines));
  43118. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43119. /**
  43120. * This is the default material used in Babylon. It is the best trade off between quality
  43121. * and performances.
  43122. * @see http://doc.babylonjs.com/babylon101/materials
  43123. */
  43124. var StandardMaterial = /** @class */ (function (_super) {
  43125. __extends(StandardMaterial, _super);
  43126. /**
  43127. * Instantiates a new standard material.
  43128. * This is the default material used in Babylon. It is the best trade off between quality
  43129. * and performances.
  43130. * @see http://doc.babylonjs.com/babylon101/materials
  43131. * @param name Define the name of the material in the scene
  43132. * @param scene Define the scene the material belong to
  43133. */
  43134. function StandardMaterial(name, scene) {
  43135. var _this = _super.call(this, name, scene) || this;
  43136. /**
  43137. * The color of the material lit by the environmental background lighting.
  43138. * @see http://doc.babylonjs.com/babylon101/materials#ambient-color-example
  43139. */
  43140. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43141. /**
  43142. * The basic color of the material as viewed under a light.
  43143. */
  43144. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43145. /**
  43146. * Define how the color and intensity of the highlight given by the light in the material.
  43147. */
  43148. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43149. /**
  43150. * Define the color of the material as if self lit.
  43151. * This will be mixed in the final result even in the absence of light.
  43152. */
  43153. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43154. /**
  43155. * Defines how sharp are the highlights in the material.
  43156. * The bigger the value the sharper giving a more glossy feeling to the result.
  43157. * Reversely, the smaller the value the blurrier giving a more rough feeling to the result.
  43158. */
  43159. _this.specularPower = 64;
  43160. _this._useAlphaFromDiffuseTexture = false;
  43161. _this._useEmissiveAsIllumination = false;
  43162. _this._linkEmissiveWithDiffuse = false;
  43163. _this._useSpecularOverAlpha = false;
  43164. _this._useReflectionOverAlpha = false;
  43165. _this._disableLighting = false;
  43166. _this._useObjectSpaceNormalMap = false;
  43167. _this._useParallax = false;
  43168. _this._useParallaxOcclusion = false;
  43169. /**
  43170. * Apply a scaling factor that determine which "depth" the height map should reprensent. A value between 0.05 and 0.1 is reasonnable in Parallax, you can reach 0.2 using Parallax Occlusion.
  43171. */
  43172. _this.parallaxScaleBias = 0.05;
  43173. _this._roughness = 0;
  43174. /**
  43175. * In case of refraction, define the value of the indice of refraction.
  43176. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43177. */
  43178. _this.indexOfRefraction = 0.98;
  43179. /**
  43180. * Invert the refraction texture alongside the y axis.
  43181. * It can be usefull with procedural textures or probe for instance.
  43182. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43183. */
  43184. _this.invertRefractionY = true;
  43185. /**
  43186. * Defines the alpha limits in alpha test mode.
  43187. */
  43188. _this.alphaCutOff = 0.4;
  43189. _this._useLightmapAsShadowmap = false;
  43190. _this._useReflectionFresnelFromSpecular = false;
  43191. _this._useGlossinessFromSpecularMapAlpha = false;
  43192. _this._maxSimultaneousLights = 4;
  43193. _this._invertNormalMapX = false;
  43194. _this._invertNormalMapY = false;
  43195. _this._twoSidedLighting = false;
  43196. _this._renderTargets = new BABYLON.SmartArray(16);
  43197. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43198. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43199. // Setup the default processing configuration to the scene.
  43200. _this._attachImageProcessingConfiguration(null);
  43201. _this.getRenderTargetTextures = function () {
  43202. _this._renderTargets.reset();
  43203. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43204. _this._renderTargets.push(_this._reflectionTexture);
  43205. }
  43206. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43207. _this._renderTargets.push(_this._refractionTexture);
  43208. }
  43209. return _this._renderTargets;
  43210. };
  43211. return _this;
  43212. }
  43213. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43214. /**
  43215. * Gets the image processing configuration used either in this material.
  43216. */
  43217. get: function () {
  43218. return this._imageProcessingConfiguration;
  43219. },
  43220. /**
  43221. * Sets the Default image processing configuration used either in the this material.
  43222. *
  43223. * If sets to null, the scene one is in use.
  43224. */
  43225. set: function (value) {
  43226. this._attachImageProcessingConfiguration(value);
  43227. // Ensure the effect will be rebuilt.
  43228. this._markAllSubMeshesAsTexturesDirty();
  43229. },
  43230. enumerable: true,
  43231. configurable: true
  43232. });
  43233. /**
  43234. * Attaches a new image processing configuration to the Standard Material.
  43235. * @param configuration
  43236. */
  43237. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43238. var _this = this;
  43239. if (configuration === this._imageProcessingConfiguration) {
  43240. return;
  43241. }
  43242. // Detaches observer.
  43243. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43244. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43245. }
  43246. // Pick the scene configuration if needed.
  43247. if (!configuration) {
  43248. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43249. }
  43250. else {
  43251. this._imageProcessingConfiguration = configuration;
  43252. }
  43253. // Attaches observer.
  43254. if (this._imageProcessingConfiguration) {
  43255. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43256. _this._markAllSubMeshesAsImageProcessingDirty();
  43257. });
  43258. }
  43259. };
  43260. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43261. /**
  43262. * Gets wether the color curves effect is enabled.
  43263. */
  43264. get: function () {
  43265. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43266. },
  43267. /**
  43268. * Sets wether the color curves effect is enabled.
  43269. */
  43270. set: function (value) {
  43271. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43272. },
  43273. enumerable: true,
  43274. configurable: true
  43275. });
  43276. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43277. /**
  43278. * Gets wether the color grading effect is enabled.
  43279. */
  43280. get: function () {
  43281. return this.imageProcessingConfiguration.colorGradingEnabled;
  43282. },
  43283. /**
  43284. * Gets wether the color grading effect is enabled.
  43285. */
  43286. set: function (value) {
  43287. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43288. },
  43289. enumerable: true,
  43290. configurable: true
  43291. });
  43292. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43293. /**
  43294. * Gets wether tonemapping is enabled or not.
  43295. */
  43296. get: function () {
  43297. return this._imageProcessingConfiguration.toneMappingEnabled;
  43298. },
  43299. /**
  43300. * Sets wether tonemapping is enabled or not
  43301. */
  43302. set: function (value) {
  43303. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43304. },
  43305. enumerable: true,
  43306. configurable: true
  43307. });
  43308. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43309. /**
  43310. * The camera exposure used on this material.
  43311. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43312. * This corresponds to a photographic exposure.
  43313. */
  43314. get: function () {
  43315. return this._imageProcessingConfiguration.exposure;
  43316. },
  43317. /**
  43318. * The camera exposure used on this material.
  43319. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43320. * This corresponds to a photographic exposure.
  43321. */
  43322. set: function (value) {
  43323. this._imageProcessingConfiguration.exposure = value;
  43324. },
  43325. enumerable: true,
  43326. configurable: true
  43327. });
  43328. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43329. /**
  43330. * Gets The camera contrast used on this material.
  43331. */
  43332. get: function () {
  43333. return this._imageProcessingConfiguration.contrast;
  43334. },
  43335. /**
  43336. * Sets The camera contrast used on this material.
  43337. */
  43338. set: function (value) {
  43339. this._imageProcessingConfiguration.contrast = value;
  43340. },
  43341. enumerable: true,
  43342. configurable: true
  43343. });
  43344. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43345. /**
  43346. * Gets the Color Grading 2D Lookup Texture.
  43347. */
  43348. get: function () {
  43349. return this._imageProcessingConfiguration.colorGradingTexture;
  43350. },
  43351. /**
  43352. * Sets the Color Grading 2D Lookup Texture.
  43353. */
  43354. set: function (value) {
  43355. this._imageProcessingConfiguration.colorGradingTexture = value;
  43356. },
  43357. enumerable: true,
  43358. configurable: true
  43359. });
  43360. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43361. /**
  43362. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43363. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43364. * 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;
  43365. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43366. */
  43367. get: function () {
  43368. return this._imageProcessingConfiguration.colorCurves;
  43369. },
  43370. /**
  43371. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43372. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43373. * 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;
  43374. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43375. */
  43376. set: function (value) {
  43377. this._imageProcessingConfiguration.colorCurves = value;
  43378. },
  43379. enumerable: true,
  43380. configurable: true
  43381. });
  43382. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  43383. /**
  43384. * Gets a boolean indicating that current material needs to register RTT
  43385. */
  43386. get: function () {
  43387. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43388. return true;
  43389. }
  43390. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43391. return true;
  43392. }
  43393. return false;
  43394. },
  43395. enumerable: true,
  43396. configurable: true
  43397. });
  43398. /**
  43399. * Gets the current class name of the material e.g. "StandardMaterial"
  43400. * Mainly use in serialization.
  43401. * @returns the class name
  43402. */
  43403. StandardMaterial.prototype.getClassName = function () {
  43404. return "StandardMaterial";
  43405. };
  43406. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43407. /**
  43408. * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes)
  43409. * You can try switching to logarithmic depth.
  43410. * @see http://doc.babylonjs.com/how_to/using_logarithmic_depth_buffer
  43411. */
  43412. get: function () {
  43413. return this._useLogarithmicDepth;
  43414. },
  43415. set: function (value) {
  43416. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43417. this._markAllSubMeshesAsMiscDirty();
  43418. },
  43419. enumerable: true,
  43420. configurable: true
  43421. });
  43422. /**
  43423. * Specifies if the material will require alpha blending
  43424. * @returns a boolean specifying if alpha blending is needed
  43425. */
  43426. StandardMaterial.prototype.needAlphaBlending = function () {
  43427. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43428. };
  43429. /**
  43430. * Specifies if this material should be rendered in alpha test mode
  43431. * @returns a boolean specifying if an alpha test is needed.
  43432. */
  43433. StandardMaterial.prototype.needAlphaTesting = function () {
  43434. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43435. };
  43436. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43437. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43438. };
  43439. /**
  43440. * Get the texture used for alpha test purpose.
  43441. * @returns the diffuse texture in case of the standard material.
  43442. */
  43443. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43444. return this._diffuseTexture;
  43445. };
  43446. /**
  43447. * Get if the submesh is ready to be used and all its information available.
  43448. * Child classes can use it to update shaders
  43449. * @param mesh defines the mesh to check
  43450. * @param subMesh defines which submesh to check
  43451. * @param useInstances specifies that instances should be used
  43452. * @returns a boolean indicating that the submesh is ready or not
  43453. */
  43454. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43455. if (useInstances === void 0) { useInstances = false; }
  43456. if (subMesh.effect && this.isFrozen) {
  43457. if (this._wasPreviouslyReady) {
  43458. return true;
  43459. }
  43460. }
  43461. if (!subMesh._materialDefines) {
  43462. subMesh._materialDefines = new StandardMaterialDefines();
  43463. }
  43464. var scene = this.getScene();
  43465. var defines = subMesh._materialDefines;
  43466. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43467. if (defines._renderId === scene.getRenderId()) {
  43468. return true;
  43469. }
  43470. }
  43471. var engine = scene.getEngine();
  43472. // Lights
  43473. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43474. // Textures
  43475. if (defines._areTexturesDirty) {
  43476. defines._needUVs = false;
  43477. defines.MAINUV1 = false;
  43478. defines.MAINUV2 = false;
  43479. if (scene.texturesEnabled) {
  43480. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43481. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43482. return false;
  43483. }
  43484. else {
  43485. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43486. }
  43487. }
  43488. else {
  43489. defines.DIFFUSE = false;
  43490. }
  43491. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43492. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43493. return false;
  43494. }
  43495. else {
  43496. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43497. }
  43498. }
  43499. else {
  43500. defines.AMBIENT = false;
  43501. }
  43502. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43503. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43504. return false;
  43505. }
  43506. else {
  43507. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43508. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43509. }
  43510. }
  43511. else {
  43512. defines.OPACITY = false;
  43513. }
  43514. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43515. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43516. return false;
  43517. }
  43518. else {
  43519. defines._needNormals = true;
  43520. defines.REFLECTION = true;
  43521. defines.ROUGHNESS = (this._roughness > 0);
  43522. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43523. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43524. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43525. switch (this._reflectionTexture.coordinatesMode) {
  43526. case BABYLON.Texture.EXPLICIT_MODE:
  43527. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43528. break;
  43529. case BABYLON.Texture.PLANAR_MODE:
  43530. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43531. break;
  43532. case BABYLON.Texture.PROJECTION_MODE:
  43533. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43534. break;
  43535. case BABYLON.Texture.SKYBOX_MODE:
  43536. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43537. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  43538. break;
  43539. case BABYLON.Texture.SPHERICAL_MODE:
  43540. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43541. break;
  43542. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43543. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43544. break;
  43545. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43546. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43547. break;
  43548. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43549. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43550. break;
  43551. case BABYLON.Texture.CUBIC_MODE:
  43552. case BABYLON.Texture.INVCUBIC_MODE:
  43553. default:
  43554. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43555. break;
  43556. }
  43557. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43558. }
  43559. }
  43560. else {
  43561. defines.REFLECTION = false;
  43562. }
  43563. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43564. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43565. return false;
  43566. }
  43567. else {
  43568. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43569. }
  43570. }
  43571. else {
  43572. defines.EMISSIVE = false;
  43573. }
  43574. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43575. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43576. return false;
  43577. }
  43578. else {
  43579. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43580. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43581. }
  43582. }
  43583. else {
  43584. defines.LIGHTMAP = false;
  43585. }
  43586. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43587. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43588. return false;
  43589. }
  43590. else {
  43591. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43592. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43593. }
  43594. }
  43595. else {
  43596. defines.SPECULAR = false;
  43597. }
  43598. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43599. // Bump texure can not be not blocking.
  43600. if (!this._bumpTexture.isReady()) {
  43601. return false;
  43602. }
  43603. else {
  43604. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43605. defines.PARALLAX = this._useParallax;
  43606. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43607. }
  43608. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43609. }
  43610. else {
  43611. defines.BUMP = false;
  43612. }
  43613. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43614. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43615. return false;
  43616. }
  43617. else {
  43618. defines._needUVs = true;
  43619. defines.REFRACTION = true;
  43620. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43621. }
  43622. }
  43623. else {
  43624. defines.REFRACTION = false;
  43625. }
  43626. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43627. }
  43628. else {
  43629. defines.DIFFUSE = false;
  43630. defines.AMBIENT = false;
  43631. defines.OPACITY = false;
  43632. defines.REFLECTION = false;
  43633. defines.EMISSIVE = false;
  43634. defines.LIGHTMAP = false;
  43635. defines.BUMP = false;
  43636. defines.REFRACTION = false;
  43637. }
  43638. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43639. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43640. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43641. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43642. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43643. }
  43644. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43645. if (!this._imageProcessingConfiguration.isReady()) {
  43646. return false;
  43647. }
  43648. this._imageProcessingConfiguration.prepareDefines(defines);
  43649. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43650. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43651. }
  43652. if (defines._areFresnelDirty) {
  43653. if (StandardMaterial.FresnelEnabled) {
  43654. // Fresnel
  43655. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43656. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43657. this._reflectionFresnelParameters) {
  43658. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43659. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43660. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43661. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43662. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43663. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43664. defines._needNormals = true;
  43665. defines.FRESNEL = true;
  43666. }
  43667. }
  43668. else {
  43669. defines.FRESNEL = false;
  43670. }
  43671. }
  43672. // Misc.
  43673. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43674. // Attribs
  43675. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43676. // Values that need to be evaluated on every frame
  43677. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43678. // Get correct effect
  43679. if (defines.isDirty) {
  43680. defines.markAsProcessed();
  43681. scene.resetCachedMaterial();
  43682. // Fallbacks
  43683. var fallbacks = new BABYLON.EffectFallbacks();
  43684. if (defines.REFLECTION) {
  43685. fallbacks.addFallback(0, "REFLECTION");
  43686. }
  43687. if (defines.SPECULAR) {
  43688. fallbacks.addFallback(0, "SPECULAR");
  43689. }
  43690. if (defines.BUMP) {
  43691. fallbacks.addFallback(0, "BUMP");
  43692. }
  43693. if (defines.PARALLAX) {
  43694. fallbacks.addFallback(1, "PARALLAX");
  43695. }
  43696. if (defines.PARALLAXOCCLUSION) {
  43697. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43698. }
  43699. if (defines.SPECULAROVERALPHA) {
  43700. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43701. }
  43702. if (defines.FOG) {
  43703. fallbacks.addFallback(1, "FOG");
  43704. }
  43705. if (defines.POINTSIZE) {
  43706. fallbacks.addFallback(0, "POINTSIZE");
  43707. }
  43708. if (defines.LOGARITHMICDEPTH) {
  43709. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43710. }
  43711. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43712. if (defines.SPECULARTERM) {
  43713. fallbacks.addFallback(0, "SPECULARTERM");
  43714. }
  43715. if (defines.DIFFUSEFRESNEL) {
  43716. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43717. }
  43718. if (defines.OPACITYFRESNEL) {
  43719. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43720. }
  43721. if (defines.REFLECTIONFRESNEL) {
  43722. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43723. }
  43724. if (defines.EMISSIVEFRESNEL) {
  43725. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43726. }
  43727. if (defines.FRESNEL) {
  43728. fallbacks.addFallback(4, "FRESNEL");
  43729. }
  43730. //Attributes
  43731. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43732. if (defines.NORMAL) {
  43733. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43734. }
  43735. if (defines.UV1) {
  43736. attribs.push(BABYLON.VertexBuffer.UVKind);
  43737. }
  43738. if (defines.UV2) {
  43739. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43740. }
  43741. if (defines.VERTEXCOLOR) {
  43742. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43743. }
  43744. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43745. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43746. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43747. var shaderName = "default";
  43748. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43749. "vFogInfos", "vFogColor", "pointSize",
  43750. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43751. "mBones",
  43752. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43753. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43754. "vReflectionPosition", "vReflectionSize",
  43755. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43756. ];
  43757. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43758. var uniformBuffers = ["Material", "Scene"];
  43759. if (BABYLON.ImageProcessingConfiguration) {
  43760. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43761. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43762. }
  43763. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43764. uniformsNames: uniforms,
  43765. uniformBuffersNames: uniformBuffers,
  43766. samplers: samplers,
  43767. defines: defines,
  43768. maxSimultaneousLights: this._maxSimultaneousLights
  43769. });
  43770. if (this.customShaderNameResolve) {
  43771. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43772. }
  43773. var join = defines.toString();
  43774. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43775. attributes: attribs,
  43776. uniformsNames: uniforms,
  43777. uniformBuffersNames: uniformBuffers,
  43778. samplers: samplers,
  43779. defines: join,
  43780. fallbacks: fallbacks,
  43781. onCompiled: this.onCompiled,
  43782. onError: this.onError,
  43783. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43784. }, engine), defines);
  43785. this.buildUniformLayout();
  43786. }
  43787. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43788. return false;
  43789. }
  43790. defines._renderId = scene.getRenderId();
  43791. this._wasPreviouslyReady = true;
  43792. return true;
  43793. };
  43794. /**
  43795. * Builds the material UBO layouts.
  43796. * Used internally during the effect preparation.
  43797. */
  43798. StandardMaterial.prototype.buildUniformLayout = function () {
  43799. // Order is important !
  43800. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43801. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43802. this._uniformBuffer.addUniform("opacityParts", 4);
  43803. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43804. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43805. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43806. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43807. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43808. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43809. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43810. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43811. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43812. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43813. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43814. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43815. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43816. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43817. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43818. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43819. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43820. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43821. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43822. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43823. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43824. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43825. this._uniformBuffer.addUniform("specularMatrix", 16);
  43826. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43827. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43828. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43829. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43830. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43831. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43832. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43833. this._uniformBuffer.addUniform("pointSize", 1);
  43834. this._uniformBuffer.create();
  43835. };
  43836. /**
  43837. * Unbinds the material from the mesh
  43838. */
  43839. StandardMaterial.prototype.unbind = function () {
  43840. if (this._activeEffect) {
  43841. var needFlag = false;
  43842. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43843. this._activeEffect.setTexture("reflection2DSampler", null);
  43844. needFlag = true;
  43845. }
  43846. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43847. this._activeEffect.setTexture("refraction2DSampler", null);
  43848. needFlag = true;
  43849. }
  43850. if (needFlag) {
  43851. this._markAllSubMeshesAsTexturesDirty();
  43852. }
  43853. }
  43854. _super.prototype.unbind.call(this);
  43855. };
  43856. /**
  43857. * Binds the submesh to this material by preparing the effect and shader to draw
  43858. * @param world defines the world transformation matrix
  43859. * @param mesh defines the mesh containing the submesh
  43860. * @param subMesh defines the submesh to bind the material to
  43861. */
  43862. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43863. var scene = this.getScene();
  43864. var defines = subMesh._materialDefines;
  43865. if (!defines) {
  43866. return;
  43867. }
  43868. var effect = subMesh.effect;
  43869. if (!effect) {
  43870. return;
  43871. }
  43872. this._activeEffect = effect;
  43873. // Matrices
  43874. this.bindOnlyWorldMatrix(world);
  43875. // Normal Matrix
  43876. if (defines.OBJECTSPACE_NORMALMAP) {
  43877. world.toNormalMatrix(this._normalMatrix);
  43878. this.bindOnlyNormalMatrix(this._normalMatrix);
  43879. }
  43880. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43881. // Bones
  43882. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43883. if (mustRebind) {
  43884. this._uniformBuffer.bindToEffect(effect, "Material");
  43885. this.bindViewProjection(effect);
  43886. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43887. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43888. // Fresnel
  43889. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43890. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43891. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43892. }
  43893. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43894. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43895. }
  43896. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43897. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43898. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43899. }
  43900. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43901. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43902. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43903. }
  43904. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43905. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43906. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43907. }
  43908. }
  43909. // Textures
  43910. if (scene.texturesEnabled) {
  43911. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43912. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43913. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43914. if (this._diffuseTexture.hasAlpha) {
  43915. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43916. }
  43917. }
  43918. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43919. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43920. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43921. }
  43922. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43923. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43924. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43925. }
  43926. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43927. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43928. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43929. if (this._reflectionTexture.boundingBoxSize) {
  43930. var cubeTexture = this._reflectionTexture;
  43931. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43932. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43933. }
  43934. }
  43935. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43936. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43937. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43938. }
  43939. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43940. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43941. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43942. }
  43943. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43944. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43945. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43946. }
  43947. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43948. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43949. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43950. if (scene._mirroredCameraPosition) {
  43951. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43952. }
  43953. else {
  43954. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43955. }
  43956. }
  43957. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43958. var depth = 1.0;
  43959. if (!this._refractionTexture.isCube) {
  43960. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43961. if (this._refractionTexture.depth) {
  43962. depth = this._refractionTexture.depth;
  43963. }
  43964. }
  43965. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43966. }
  43967. }
  43968. // Point size
  43969. if (this.pointsCloud) {
  43970. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43971. }
  43972. if (defines.SPECULARTERM) {
  43973. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43974. }
  43975. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43976. // Diffuse
  43977. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43978. }
  43979. // Textures
  43980. if (scene.texturesEnabled) {
  43981. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43982. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43983. }
  43984. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43985. effect.setTexture("ambientSampler", this._ambientTexture);
  43986. }
  43987. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43988. effect.setTexture("opacitySampler", this._opacityTexture);
  43989. }
  43990. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43991. if (this._reflectionTexture.isCube) {
  43992. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43993. }
  43994. else {
  43995. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43996. }
  43997. }
  43998. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43999. effect.setTexture("emissiveSampler", this._emissiveTexture);
  44000. }
  44001. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44002. effect.setTexture("lightmapSampler", this._lightmapTexture);
  44003. }
  44004. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44005. effect.setTexture("specularSampler", this._specularTexture);
  44006. }
  44007. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44008. effect.setTexture("bumpSampler", this._bumpTexture);
  44009. }
  44010. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44011. var depth = 1.0;
  44012. if (this._refractionTexture.isCube) {
  44013. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  44014. }
  44015. else {
  44016. effect.setTexture("refraction2DSampler", this._refractionTexture);
  44017. }
  44018. }
  44019. }
  44020. // Clip plane
  44021. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  44022. // Colors
  44023. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44024. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  44025. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44026. }
  44027. if (mustRebind || !this.isFrozen) {
  44028. // Lights
  44029. if (scene.lightsEnabled && !this._disableLighting) {
  44030. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  44031. }
  44032. // View
  44033. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  44034. this.bindView(effect);
  44035. }
  44036. // Fog
  44037. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  44038. // Morph targets
  44039. if (defines.NUM_MORPH_INFLUENCERS) {
  44040. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  44041. }
  44042. // Log. depth
  44043. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  44044. // image processing
  44045. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  44046. this._imageProcessingConfiguration.bind(this._activeEffect);
  44047. }
  44048. }
  44049. this._uniformBuffer.update();
  44050. this._afterBind(mesh, this._activeEffect);
  44051. };
  44052. /**
  44053. * Get the list of animatables in the material.
  44054. * @returns the list of animatables object used in the material
  44055. */
  44056. StandardMaterial.prototype.getAnimatables = function () {
  44057. var results = [];
  44058. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  44059. results.push(this._diffuseTexture);
  44060. }
  44061. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44062. results.push(this._ambientTexture);
  44063. }
  44064. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44065. results.push(this._opacityTexture);
  44066. }
  44067. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44068. results.push(this._reflectionTexture);
  44069. }
  44070. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44071. results.push(this._emissiveTexture);
  44072. }
  44073. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  44074. results.push(this._specularTexture);
  44075. }
  44076. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44077. results.push(this._bumpTexture);
  44078. }
  44079. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44080. results.push(this._lightmapTexture);
  44081. }
  44082. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44083. results.push(this._refractionTexture);
  44084. }
  44085. return results;
  44086. };
  44087. /**
  44088. * Gets the active textures from the material
  44089. * @returns an array of textures
  44090. */
  44091. StandardMaterial.prototype.getActiveTextures = function () {
  44092. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44093. if (this._diffuseTexture) {
  44094. activeTextures.push(this._diffuseTexture);
  44095. }
  44096. if (this._ambientTexture) {
  44097. activeTextures.push(this._ambientTexture);
  44098. }
  44099. if (this._opacityTexture) {
  44100. activeTextures.push(this._opacityTexture);
  44101. }
  44102. if (this._reflectionTexture) {
  44103. activeTextures.push(this._reflectionTexture);
  44104. }
  44105. if (this._emissiveTexture) {
  44106. activeTextures.push(this._emissiveTexture);
  44107. }
  44108. if (this._specularTexture) {
  44109. activeTextures.push(this._specularTexture);
  44110. }
  44111. if (this._bumpTexture) {
  44112. activeTextures.push(this._bumpTexture);
  44113. }
  44114. if (this._lightmapTexture) {
  44115. activeTextures.push(this._lightmapTexture);
  44116. }
  44117. if (this._refractionTexture) {
  44118. activeTextures.push(this._refractionTexture);
  44119. }
  44120. return activeTextures;
  44121. };
  44122. /**
  44123. * Specifies if the material uses a texture
  44124. * @param texture defines the texture to check against the material
  44125. * @returns a boolean specifying if the material uses the texture
  44126. */
  44127. StandardMaterial.prototype.hasTexture = function (texture) {
  44128. if (_super.prototype.hasTexture.call(this, texture)) {
  44129. return true;
  44130. }
  44131. if (this._diffuseTexture === texture) {
  44132. return true;
  44133. }
  44134. if (this._ambientTexture === texture) {
  44135. return true;
  44136. }
  44137. if (this._opacityTexture === texture) {
  44138. return true;
  44139. }
  44140. if (this._reflectionTexture === texture) {
  44141. return true;
  44142. }
  44143. if (this._emissiveTexture === texture) {
  44144. return true;
  44145. }
  44146. if (this._specularTexture === texture) {
  44147. return true;
  44148. }
  44149. if (this._bumpTexture === texture) {
  44150. return true;
  44151. }
  44152. if (this._lightmapTexture === texture) {
  44153. return true;
  44154. }
  44155. if (this._refractionTexture === texture) {
  44156. return true;
  44157. }
  44158. return false;
  44159. };
  44160. /**
  44161. * Disposes the material
  44162. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  44163. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  44164. */
  44165. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44166. if (forceDisposeTextures) {
  44167. if (this._diffuseTexture) {
  44168. this._diffuseTexture.dispose();
  44169. }
  44170. if (this._ambientTexture) {
  44171. this._ambientTexture.dispose();
  44172. }
  44173. if (this._opacityTexture) {
  44174. this._opacityTexture.dispose();
  44175. }
  44176. if (this._reflectionTexture) {
  44177. this._reflectionTexture.dispose();
  44178. }
  44179. if (this._emissiveTexture) {
  44180. this._emissiveTexture.dispose();
  44181. }
  44182. if (this._specularTexture) {
  44183. this._specularTexture.dispose();
  44184. }
  44185. if (this._bumpTexture) {
  44186. this._bumpTexture.dispose();
  44187. }
  44188. if (this._lightmapTexture) {
  44189. this._lightmapTexture.dispose();
  44190. }
  44191. if (this._refractionTexture) {
  44192. this._refractionTexture.dispose();
  44193. }
  44194. }
  44195. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44196. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44197. }
  44198. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44199. };
  44200. /**
  44201. * Makes a duplicate of the material, and gives it a new name
  44202. * @param name defines the new name for the duplicated material
  44203. * @returns the cloned material
  44204. */
  44205. StandardMaterial.prototype.clone = function (name) {
  44206. var _this = this;
  44207. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44208. result.name = name;
  44209. result.id = name;
  44210. return result;
  44211. };
  44212. /**
  44213. * Serializes this material in a JSON representation
  44214. * @returns the serialized material object
  44215. */
  44216. StandardMaterial.prototype.serialize = function () {
  44217. return BABYLON.SerializationHelper.Serialize(this);
  44218. };
  44219. /**
  44220. * Creates a standard material from parsed material data
  44221. * @param source defines the JSON represnetation of the material
  44222. * @param scene defines the hosting scene
  44223. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  44224. * @returns a new material
  44225. */
  44226. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44227. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44228. };
  44229. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44230. /**
  44231. * Are diffuse textures enabled in the application.
  44232. */
  44233. get: function () {
  44234. return StandardMaterial._DiffuseTextureEnabled;
  44235. },
  44236. set: function (value) {
  44237. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44238. return;
  44239. }
  44240. StandardMaterial._DiffuseTextureEnabled = value;
  44241. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44242. },
  44243. enumerable: true,
  44244. configurable: true
  44245. });
  44246. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44247. /**
  44248. * Are ambient textures enabled in the application.
  44249. */
  44250. get: function () {
  44251. return StandardMaterial._AmbientTextureEnabled;
  44252. },
  44253. set: function (value) {
  44254. if (StandardMaterial._AmbientTextureEnabled === value) {
  44255. return;
  44256. }
  44257. StandardMaterial._AmbientTextureEnabled = value;
  44258. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44259. },
  44260. enumerable: true,
  44261. configurable: true
  44262. });
  44263. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44264. /**
  44265. * Are opacity textures enabled in the application.
  44266. */
  44267. get: function () {
  44268. return StandardMaterial._OpacityTextureEnabled;
  44269. },
  44270. set: function (value) {
  44271. if (StandardMaterial._OpacityTextureEnabled === value) {
  44272. return;
  44273. }
  44274. StandardMaterial._OpacityTextureEnabled = value;
  44275. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44276. },
  44277. enumerable: true,
  44278. configurable: true
  44279. });
  44280. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44281. /**
  44282. * Are reflection textures enabled in the application.
  44283. */
  44284. get: function () {
  44285. return StandardMaterial._ReflectionTextureEnabled;
  44286. },
  44287. set: function (value) {
  44288. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44289. return;
  44290. }
  44291. StandardMaterial._ReflectionTextureEnabled = value;
  44292. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44293. },
  44294. enumerable: true,
  44295. configurable: true
  44296. });
  44297. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44298. /**
  44299. * Are emissive textures enabled in the application.
  44300. */
  44301. get: function () {
  44302. return StandardMaterial._EmissiveTextureEnabled;
  44303. },
  44304. set: function (value) {
  44305. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44306. return;
  44307. }
  44308. StandardMaterial._EmissiveTextureEnabled = value;
  44309. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44310. },
  44311. enumerable: true,
  44312. configurable: true
  44313. });
  44314. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44315. /**
  44316. * Are specular textures enabled in the application.
  44317. */
  44318. get: function () {
  44319. return StandardMaterial._SpecularTextureEnabled;
  44320. },
  44321. set: function (value) {
  44322. if (StandardMaterial._SpecularTextureEnabled === value) {
  44323. return;
  44324. }
  44325. StandardMaterial._SpecularTextureEnabled = value;
  44326. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44327. },
  44328. enumerable: true,
  44329. configurable: true
  44330. });
  44331. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44332. /**
  44333. * Are bump textures enabled in the application.
  44334. */
  44335. get: function () {
  44336. return StandardMaterial._BumpTextureEnabled;
  44337. },
  44338. set: function (value) {
  44339. if (StandardMaterial._BumpTextureEnabled === value) {
  44340. return;
  44341. }
  44342. StandardMaterial._BumpTextureEnabled = value;
  44343. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44344. },
  44345. enumerable: true,
  44346. configurable: true
  44347. });
  44348. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44349. /**
  44350. * Are lightmap textures enabled in the application.
  44351. */
  44352. get: function () {
  44353. return StandardMaterial._LightmapTextureEnabled;
  44354. },
  44355. set: function (value) {
  44356. if (StandardMaterial._LightmapTextureEnabled === value) {
  44357. return;
  44358. }
  44359. StandardMaterial._LightmapTextureEnabled = value;
  44360. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44361. },
  44362. enumerable: true,
  44363. configurable: true
  44364. });
  44365. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44366. /**
  44367. * Are refraction textures enabled in the application.
  44368. */
  44369. get: function () {
  44370. return StandardMaterial._RefractionTextureEnabled;
  44371. },
  44372. set: function (value) {
  44373. if (StandardMaterial._RefractionTextureEnabled === value) {
  44374. return;
  44375. }
  44376. StandardMaterial._RefractionTextureEnabled = value;
  44377. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44378. },
  44379. enumerable: true,
  44380. configurable: true
  44381. });
  44382. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44383. /**
  44384. * Are color grading textures enabled in the application.
  44385. */
  44386. get: function () {
  44387. return StandardMaterial._ColorGradingTextureEnabled;
  44388. },
  44389. set: function (value) {
  44390. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44391. return;
  44392. }
  44393. StandardMaterial._ColorGradingTextureEnabled = value;
  44394. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44395. },
  44396. enumerable: true,
  44397. configurable: true
  44398. });
  44399. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44400. /**
  44401. * Are fresnels enabled in the application.
  44402. */
  44403. get: function () {
  44404. return StandardMaterial._FresnelEnabled;
  44405. },
  44406. set: function (value) {
  44407. if (StandardMaterial._FresnelEnabled === value) {
  44408. return;
  44409. }
  44410. StandardMaterial._FresnelEnabled = value;
  44411. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44412. },
  44413. enumerable: true,
  44414. configurable: true
  44415. });
  44416. // Flags used to enable or disable a type of texture for all Standard Materials
  44417. StandardMaterial._DiffuseTextureEnabled = true;
  44418. StandardMaterial._AmbientTextureEnabled = true;
  44419. StandardMaterial._OpacityTextureEnabled = true;
  44420. StandardMaterial._ReflectionTextureEnabled = true;
  44421. StandardMaterial._EmissiveTextureEnabled = true;
  44422. StandardMaterial._SpecularTextureEnabled = true;
  44423. StandardMaterial._BumpTextureEnabled = true;
  44424. StandardMaterial._LightmapTextureEnabled = true;
  44425. StandardMaterial._RefractionTextureEnabled = true;
  44426. StandardMaterial._ColorGradingTextureEnabled = true;
  44427. StandardMaterial._FresnelEnabled = true;
  44428. __decorate([
  44429. BABYLON.serializeAsTexture("diffuseTexture")
  44430. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44431. __decorate([
  44432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44433. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44434. __decorate([
  44435. BABYLON.serializeAsTexture("ambientTexture")
  44436. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44437. __decorate([
  44438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44439. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44440. __decorate([
  44441. BABYLON.serializeAsTexture("opacityTexture")
  44442. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44443. __decorate([
  44444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44445. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44446. __decorate([
  44447. BABYLON.serializeAsTexture("reflectionTexture")
  44448. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44449. __decorate([
  44450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44451. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44452. __decorate([
  44453. BABYLON.serializeAsTexture("emissiveTexture")
  44454. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44455. __decorate([
  44456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44457. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44458. __decorate([
  44459. BABYLON.serializeAsTexture("specularTexture")
  44460. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44461. __decorate([
  44462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44463. ], StandardMaterial.prototype, "specularTexture", void 0);
  44464. __decorate([
  44465. BABYLON.serializeAsTexture("bumpTexture")
  44466. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44467. __decorate([
  44468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44469. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44470. __decorate([
  44471. BABYLON.serializeAsTexture("lightmapTexture")
  44472. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44473. __decorate([
  44474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44475. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44476. __decorate([
  44477. BABYLON.serializeAsTexture("refractionTexture")
  44478. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44479. __decorate([
  44480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44481. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44482. __decorate([
  44483. BABYLON.serializeAsColor3("ambient")
  44484. ], StandardMaterial.prototype, "ambientColor", void 0);
  44485. __decorate([
  44486. BABYLON.serializeAsColor3("diffuse")
  44487. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44488. __decorate([
  44489. BABYLON.serializeAsColor3("specular")
  44490. ], StandardMaterial.prototype, "specularColor", void 0);
  44491. __decorate([
  44492. BABYLON.serializeAsColor3("emissive")
  44493. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44494. __decorate([
  44495. BABYLON.serialize()
  44496. ], StandardMaterial.prototype, "specularPower", void 0);
  44497. __decorate([
  44498. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44499. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44500. __decorate([
  44501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44502. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44503. __decorate([
  44504. BABYLON.serialize("useEmissiveAsIllumination")
  44505. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44506. __decorate([
  44507. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44508. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44509. __decorate([
  44510. BABYLON.serialize("linkEmissiveWithDiffuse")
  44511. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44512. __decorate([
  44513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44514. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44515. __decorate([
  44516. BABYLON.serialize("useSpecularOverAlpha")
  44517. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44518. __decorate([
  44519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44520. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44521. __decorate([
  44522. BABYLON.serialize("useReflectionOverAlpha")
  44523. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44524. __decorate([
  44525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44526. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44527. __decorate([
  44528. BABYLON.serialize("disableLighting")
  44529. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44530. __decorate([
  44531. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44532. ], StandardMaterial.prototype, "disableLighting", void 0);
  44533. __decorate([
  44534. BABYLON.serialize("useObjectSpaceNormalMap")
  44535. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44536. __decorate([
  44537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44538. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44539. __decorate([
  44540. BABYLON.serialize("useParallax")
  44541. ], StandardMaterial.prototype, "_useParallax", void 0);
  44542. __decorate([
  44543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44544. ], StandardMaterial.prototype, "useParallax", void 0);
  44545. __decorate([
  44546. BABYLON.serialize("useParallaxOcclusion")
  44547. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44548. __decorate([
  44549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44550. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44551. __decorate([
  44552. BABYLON.serialize()
  44553. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44554. __decorate([
  44555. BABYLON.serialize("roughness")
  44556. ], StandardMaterial.prototype, "_roughness", void 0);
  44557. __decorate([
  44558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44559. ], StandardMaterial.prototype, "roughness", void 0);
  44560. __decorate([
  44561. BABYLON.serialize()
  44562. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44563. __decorate([
  44564. BABYLON.serialize()
  44565. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44566. __decorate([
  44567. BABYLON.serialize()
  44568. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44569. __decorate([
  44570. BABYLON.serialize("useLightmapAsShadowmap")
  44571. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44572. __decorate([
  44573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44574. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44575. __decorate([
  44576. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44577. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44578. __decorate([
  44579. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44580. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44581. __decorate([
  44582. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44583. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44584. __decorate([
  44585. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44586. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44587. __decorate([
  44588. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44589. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44590. __decorate([
  44591. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44592. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44593. __decorate([
  44594. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44595. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44596. __decorate([
  44597. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44598. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44599. __decorate([
  44600. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44601. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44602. __decorate([
  44603. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44604. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44605. __decorate([
  44606. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44607. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44608. __decorate([
  44609. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44610. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44611. __decorate([
  44612. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44613. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44614. __decorate([
  44615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44616. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44617. __decorate([
  44618. BABYLON.serialize("maxSimultaneousLights")
  44619. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44620. __decorate([
  44621. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44622. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44623. __decorate([
  44624. BABYLON.serialize("invertNormalMapX")
  44625. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44626. __decorate([
  44627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44628. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44629. __decorate([
  44630. BABYLON.serialize("invertNormalMapY")
  44631. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44632. __decorate([
  44633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44634. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44635. __decorate([
  44636. BABYLON.serialize("twoSidedLighting")
  44637. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44638. __decorate([
  44639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44640. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44641. __decorate([
  44642. BABYLON.serialize()
  44643. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44644. return StandardMaterial;
  44645. }(BABYLON.PushMaterial));
  44646. BABYLON.StandardMaterial = StandardMaterial;
  44647. })(BABYLON || (BABYLON = {}));
  44648. //# sourceMappingURL=babylon.standardMaterial.js.map
  44649. var BABYLON;
  44650. (function (BABYLON) {
  44651. /**
  44652. * Class representing spherical polynomial coefficients to the 3rd degree
  44653. */
  44654. var SphericalPolynomial = /** @class */ (function () {
  44655. function SphericalPolynomial() {
  44656. /**
  44657. * The x coefficients of the spherical polynomial
  44658. */
  44659. this.x = BABYLON.Vector3.Zero();
  44660. /**
  44661. * The y coefficients of the spherical polynomial
  44662. */
  44663. this.y = BABYLON.Vector3.Zero();
  44664. /**
  44665. * The z coefficients of the spherical polynomial
  44666. */
  44667. this.z = BABYLON.Vector3.Zero();
  44668. /**
  44669. * The xx coefficients of the spherical polynomial
  44670. */
  44671. this.xx = BABYLON.Vector3.Zero();
  44672. /**
  44673. * The yy coefficients of the spherical polynomial
  44674. */
  44675. this.yy = BABYLON.Vector3.Zero();
  44676. /**
  44677. * The zz coefficients of the spherical polynomial
  44678. */
  44679. this.zz = BABYLON.Vector3.Zero();
  44680. /**
  44681. * The xy coefficients of the spherical polynomial
  44682. */
  44683. this.xy = BABYLON.Vector3.Zero();
  44684. /**
  44685. * The yz coefficients of the spherical polynomial
  44686. */
  44687. this.yz = BABYLON.Vector3.Zero();
  44688. /**
  44689. * The zx coefficients of the spherical polynomial
  44690. */
  44691. this.zx = BABYLON.Vector3.Zero();
  44692. }
  44693. /**
  44694. * Adds an ambient color to the spherical polynomial
  44695. * @param color the color to add
  44696. */
  44697. SphericalPolynomial.prototype.addAmbient = function (color) {
  44698. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44699. this.xx = this.xx.add(colorVector);
  44700. this.yy = this.yy.add(colorVector);
  44701. this.zz = this.zz.add(colorVector);
  44702. };
  44703. /**
  44704. * Scales the spherical polynomial by the given amount
  44705. * @param scale the amount to scale
  44706. */
  44707. SphericalPolynomial.prototype.scale = function (scale) {
  44708. this.x = this.x.scale(scale);
  44709. this.y = this.y.scale(scale);
  44710. this.z = this.z.scale(scale);
  44711. this.xx = this.xx.scale(scale);
  44712. this.yy = this.yy.scale(scale);
  44713. this.zz = this.zz.scale(scale);
  44714. this.yz = this.yz.scale(scale);
  44715. this.zx = this.zx.scale(scale);
  44716. this.xy = this.xy.scale(scale);
  44717. };
  44718. /**
  44719. * Gets the spherical polynomial from harmonics
  44720. * @param harmonics the spherical harmonics
  44721. * @returns the spherical polynomial
  44722. */
  44723. SphericalPolynomial.FromHarmonics = function (harmonics) {
  44724. var result = new SphericalPolynomial();
  44725. result.x = harmonics.l11.scale(1.02333);
  44726. result.y = harmonics.l1_1.scale(1.02333);
  44727. result.z = harmonics.l10.scale(1.02333);
  44728. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  44729. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  44730. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  44731. result.yz = harmonics.l2_1.scale(0.858086);
  44732. result.zx = harmonics.l21.scale(0.858086);
  44733. result.xy = harmonics.l2_2.scale(0.858086);
  44734. result.scale(1.0 / Math.PI);
  44735. return result;
  44736. };
  44737. /**
  44738. * Constructs a spherical polynomial from an array.
  44739. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  44740. * @returns the spherical polynomial
  44741. */
  44742. SphericalPolynomial.FromArray = function (data) {
  44743. var sp = new SphericalPolynomial();
  44744. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  44745. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  44746. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  44747. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  44748. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  44749. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  44750. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  44751. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  44752. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  44753. return sp;
  44754. };
  44755. return SphericalPolynomial;
  44756. }());
  44757. BABYLON.SphericalPolynomial = SphericalPolynomial;
  44758. /**
  44759. * Class representing spherical harmonics coefficients to the 3rd degree
  44760. */
  44761. var SphericalHarmonics = /** @class */ (function () {
  44762. function SphericalHarmonics() {
  44763. /**
  44764. * The l0,0 coefficients of the spherical harmonics
  44765. */
  44766. this.l00 = BABYLON.Vector3.Zero();
  44767. /**
  44768. * The l1,-1 coefficients of the spherical harmonics
  44769. */
  44770. this.l1_1 = BABYLON.Vector3.Zero();
  44771. /**
  44772. * The l1,0 coefficients of the spherical harmonics
  44773. */
  44774. this.l10 = BABYLON.Vector3.Zero();
  44775. /**
  44776. * The l1,1 coefficients of the spherical harmonics
  44777. */
  44778. this.l11 = BABYLON.Vector3.Zero();
  44779. /**
  44780. * The l2,-2 coefficients of the spherical harmonics
  44781. */
  44782. this.l2_2 = BABYLON.Vector3.Zero();
  44783. /**
  44784. * The l2,-1 coefficients of the spherical harmonics
  44785. */
  44786. this.l2_1 = BABYLON.Vector3.Zero();
  44787. /**
  44788. * The l2,0 coefficients of the spherical harmonics
  44789. */
  44790. this.l20 = BABYLON.Vector3.Zero();
  44791. /**
  44792. * The l2,1 coefficients of the spherical harmonics
  44793. */
  44794. this.l21 = BABYLON.Vector3.Zero();
  44795. /**
  44796. * The l2,2 coefficients of the spherical harmonics
  44797. */
  44798. this.lL22 = BABYLON.Vector3.Zero();
  44799. }
  44800. /**
  44801. * Adds a light to the spherical harmonics
  44802. * @param direction the direction of the light
  44803. * @param color the color of the light
  44804. * @param deltaSolidAngle the delta solid angle of the light
  44805. */
  44806. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  44807. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44808. var c = colorVector.scale(deltaSolidAngle);
  44809. this.l00 = this.l00.add(c.scale(0.282095));
  44810. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  44811. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  44812. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  44813. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  44814. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  44815. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  44816. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  44817. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  44818. };
  44819. /**
  44820. * Scales the spherical harmonics by the given amount
  44821. * @param scale the amount to scale
  44822. */
  44823. SphericalHarmonics.prototype.scale = function (scale) {
  44824. this.l00 = this.l00.scale(scale);
  44825. this.l1_1 = this.l1_1.scale(scale);
  44826. this.l10 = this.l10.scale(scale);
  44827. this.l11 = this.l11.scale(scale);
  44828. this.l2_2 = this.l2_2.scale(scale);
  44829. this.l2_1 = this.l2_1.scale(scale);
  44830. this.l20 = this.l20.scale(scale);
  44831. this.l21 = this.l21.scale(scale);
  44832. this.lL22 = this.lL22.scale(scale);
  44833. };
  44834. /**
  44835. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  44836. *
  44837. * ```
  44838. * E_lm = A_l * L_lm
  44839. * ```
  44840. *
  44841. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  44842. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  44843. * the scaling factors are given in equation 9.
  44844. */
  44845. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  44846. // Constant (Band 0)
  44847. this.l00 = this.l00.scale(3.141593);
  44848. // Linear (Band 1)
  44849. this.l1_1 = this.l1_1.scale(2.094395);
  44850. this.l10 = this.l10.scale(2.094395);
  44851. this.l11 = this.l11.scale(2.094395);
  44852. // Quadratic (Band 2)
  44853. this.l2_2 = this.l2_2.scale(0.785398);
  44854. this.l2_1 = this.l2_1.scale(0.785398);
  44855. this.l20 = this.l20.scale(0.785398);
  44856. this.l21 = this.l21.scale(0.785398);
  44857. this.lL22 = this.lL22.scale(0.785398);
  44858. };
  44859. /**
  44860. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  44861. *
  44862. * ```
  44863. * L = (1/pi) * E * rho
  44864. * ```
  44865. *
  44866. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  44867. */
  44868. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  44869. this.scale(1.0 / Math.PI);
  44870. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  44871. // (The pixel shader must apply albedo after texture fetches, etc).
  44872. };
  44873. /**
  44874. * Gets the spherical harmonics from polynomial
  44875. * @param polynomial the spherical polynomial
  44876. * @returns the spherical harmonics
  44877. */
  44878. SphericalHarmonics.FromPolynomial = function (polynomial) {
  44879. var result = new SphericalHarmonics();
  44880. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  44881. result.l1_1 = polynomial.y.scale(0.977204);
  44882. result.l10 = polynomial.z.scale(0.977204);
  44883. result.l11 = polynomial.x.scale(0.977204);
  44884. result.l2_2 = polynomial.xy.scale(1.16538);
  44885. result.l2_1 = polynomial.yz.scale(1.16538);
  44886. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  44887. result.l21 = polynomial.zx.scale(1.16538);
  44888. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  44889. result.scale(Math.PI);
  44890. return result;
  44891. };
  44892. /**
  44893. * Constructs a spherical harmonics from an array.
  44894. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  44895. * @returns the spherical harmonics
  44896. */
  44897. SphericalHarmonics.FromArray = function (data) {
  44898. var sh = new SphericalHarmonics();
  44899. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  44900. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  44901. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  44902. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  44903. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  44904. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  44905. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  44906. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  44907. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  44908. return sh;
  44909. };
  44910. return SphericalHarmonics;
  44911. }());
  44912. BABYLON.SphericalHarmonics = SphericalHarmonics;
  44913. })(BABYLON || (BABYLON = {}));
  44914. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  44915. var BABYLON;
  44916. (function (BABYLON) {
  44917. var FileFaceOrientation = /** @class */ (function () {
  44918. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  44919. this.name = name;
  44920. this.worldAxisForNormal = worldAxisForNormal;
  44921. this.worldAxisForFileX = worldAxisForFileX;
  44922. this.worldAxisForFileY = worldAxisForFileY;
  44923. }
  44924. return FileFaceOrientation;
  44925. }());
  44926. /**
  44927. * Helper class dealing with the extraction of spherical polynomial dataArray
  44928. * from a cube map.
  44929. */
  44930. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  44931. function CubeMapToSphericalPolynomialTools() {
  44932. }
  44933. /**
  44934. * Converts a texture to the according Spherical Polynomial data.
  44935. * This extracts the first 3 orders only as they are the only one used in the lighting.
  44936. *
  44937. * @param texture The texture to extract the information from.
  44938. * @return The Spherical Polynomial data.
  44939. */
  44940. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  44941. if (!texture.isCube) {
  44942. // Only supports cube Textures currently.
  44943. return null;
  44944. }
  44945. var size = texture.getSize().width;
  44946. var right = texture.readPixels(0);
  44947. var left = texture.readPixels(1);
  44948. var up;
  44949. var down;
  44950. if (texture.isRenderTarget) {
  44951. up = texture.readPixels(3);
  44952. down = texture.readPixels(2);
  44953. }
  44954. else {
  44955. up = texture.readPixels(2);
  44956. down = texture.readPixels(3);
  44957. }
  44958. var front = texture.readPixels(4);
  44959. var back = texture.readPixels(5);
  44960. var gammaSpace = texture.gammaSpace;
  44961. // Always read as RGBA.
  44962. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  44963. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  44964. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44965. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  44966. }
  44967. var cubeInfo = {
  44968. size: size,
  44969. right: right,
  44970. left: left,
  44971. up: up,
  44972. down: down,
  44973. front: front,
  44974. back: back,
  44975. format: format,
  44976. type: type,
  44977. gammaSpace: gammaSpace,
  44978. };
  44979. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  44980. };
  44981. /**
  44982. * Converts a cubemap to the according Spherical Polynomial data.
  44983. * This extracts the first 3 orders only as they are the only one used in the lighting.
  44984. *
  44985. * @param cubeInfo The Cube map to extract the information from.
  44986. * @return The Spherical Polynomial data.
  44987. */
  44988. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  44989. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  44990. var totalSolidAngle = 0.0;
  44991. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  44992. var du = 2.0 / cubeInfo.size;
  44993. var dv = du;
  44994. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  44995. var minUV = du * 0.5 - 1.0;
  44996. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  44997. var fileFace = this.FileFaces[faceIndex];
  44998. var dataArray = cubeInfo[fileFace.name];
  44999. var v = minUV;
  45000. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  45001. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  45002. // Because SP is still linear, so summation is fine in that basis.
  45003. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  45004. for (var y = 0; y < cubeInfo.size; y++) {
  45005. var u = minUV;
  45006. for (var x = 0; x < cubeInfo.size; x++) {
  45007. // World direction (not normalised)
  45008. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  45009. worldDirection.normalize();
  45010. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  45011. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  45012. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  45013. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  45014. // Handle Integer types.
  45015. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  45016. r /= 255;
  45017. g /= 255;
  45018. b /= 255;
  45019. }
  45020. // Handle Gamma space textures.
  45021. if (cubeInfo.gammaSpace) {
  45022. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  45023. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  45024. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  45025. }
  45026. var color = new BABYLON.Color3(r, g, b);
  45027. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  45028. totalSolidAngle += deltaSolidAngle;
  45029. u += du;
  45030. }
  45031. v += dv;
  45032. }
  45033. }
  45034. // Solid angle for entire sphere is 4*pi
  45035. var sphereSolidAngle = 4.0 * Math.PI;
  45036. // Adjust the solid angle to allow for how many faces we processed.
  45037. var facesProcessed = 6.0;
  45038. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  45039. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  45040. // This is needed because the numerical integration over the cube uses a
  45041. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  45042. // and also to compensate for accumulative error due to float precision in the summation.
  45043. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  45044. sphericalHarmonics.scale(correctionFactor);
  45045. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  45046. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  45047. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  45048. };
  45049. CubeMapToSphericalPolynomialTools.FileFaces = [
  45050. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  45051. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  45052. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  45053. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  45054. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  45055. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  45056. ];
  45057. return CubeMapToSphericalPolynomialTools;
  45058. }());
  45059. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  45060. })(BABYLON || (BABYLON = {}));
  45061. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  45062. var BABYLON;
  45063. (function (BABYLON) {
  45064. /**
  45065. * Manages the defines for the PBR Material.
  45066. * @hiddenChildren
  45067. */
  45068. var PBRMaterialDefines = /** @class */ (function (_super) {
  45069. __extends(PBRMaterialDefines, _super);
  45070. /**
  45071. * Initializes the PBR Material defines.
  45072. */
  45073. function PBRMaterialDefines() {
  45074. var _this = _super.call(this) || this;
  45075. _this.PBR = true;
  45076. _this.MAINUV1 = false;
  45077. _this.MAINUV2 = false;
  45078. _this.UV1 = false;
  45079. _this.UV2 = false;
  45080. _this.ALBEDO = false;
  45081. _this.ALBEDODIRECTUV = 0;
  45082. _this.VERTEXCOLOR = false;
  45083. _this.AMBIENT = false;
  45084. _this.AMBIENTDIRECTUV = 0;
  45085. _this.AMBIENTINGRAYSCALE = false;
  45086. _this.OPACITY = false;
  45087. _this.VERTEXALPHA = false;
  45088. _this.OPACITYDIRECTUV = 0;
  45089. _this.OPACITYRGB = false;
  45090. _this.ALPHATEST = false;
  45091. _this.DEPTHPREPASS = false;
  45092. _this.ALPHABLEND = false;
  45093. _this.ALPHAFROMALBEDO = false;
  45094. _this.ALPHATESTVALUE = "0.5";
  45095. _this.SPECULAROVERALPHA = false;
  45096. _this.RADIANCEOVERALPHA = false;
  45097. _this.ALPHAFRESNEL = false;
  45098. _this.LINEARALPHAFRESNEL = false;
  45099. _this.PREMULTIPLYALPHA = false;
  45100. _this.EMISSIVE = false;
  45101. _this.EMISSIVEDIRECTUV = 0;
  45102. _this.REFLECTIVITY = false;
  45103. _this.REFLECTIVITYDIRECTUV = 0;
  45104. _this.SPECULARTERM = false;
  45105. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  45106. _this.MICROSURFACEAUTOMATIC = false;
  45107. _this.LODBASEDMICROSFURACE = false;
  45108. _this.MICROSURFACEMAP = false;
  45109. _this.MICROSURFACEMAPDIRECTUV = 0;
  45110. _this.METALLICWORKFLOW = false;
  45111. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  45112. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  45113. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  45114. _this.AOSTOREINMETALMAPRED = false;
  45115. _this.ENVIRONMENTBRDF = false;
  45116. _this.NORMAL = false;
  45117. _this.TANGENT = false;
  45118. _this.BUMP = false;
  45119. _this.BUMPDIRECTUV = 0;
  45120. _this.OBJECTSPACE_NORMALMAP = false;
  45121. _this.PARALLAX = false;
  45122. _this.PARALLAXOCCLUSION = false;
  45123. _this.NORMALXYSCALE = true;
  45124. _this.LIGHTMAP = false;
  45125. _this.LIGHTMAPDIRECTUV = 0;
  45126. _this.USELIGHTMAPASSHADOWMAP = false;
  45127. _this.GAMMALIGHTMAP = false;
  45128. _this.REFLECTION = false;
  45129. _this.REFLECTIONMAP_3D = false;
  45130. _this.REFLECTIONMAP_SPHERICAL = false;
  45131. _this.REFLECTIONMAP_PLANAR = false;
  45132. _this.REFLECTIONMAP_CUBIC = false;
  45133. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45134. _this.REFLECTIONMAP_PROJECTION = false;
  45135. _this.REFLECTIONMAP_SKYBOX = false;
  45136. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  45137. _this.REFLECTIONMAP_EXPLICIT = false;
  45138. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45139. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45140. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45141. _this.INVERTCUBICMAP = false;
  45142. _this.USESPHERICALFROMREFLECTIONMAP = false;
  45143. _this.USESPHERICALINVERTEX = false;
  45144. _this.REFLECTIONMAP_OPPOSITEZ = false;
  45145. _this.LODINREFLECTIONALPHA = false;
  45146. _this.GAMMAREFLECTION = false;
  45147. _this.RGBDREFLECTION = false;
  45148. _this.RADIANCEOCCLUSION = false;
  45149. _this.HORIZONOCCLUSION = false;
  45150. _this.REFRACTION = false;
  45151. _this.REFRACTIONMAP_3D = false;
  45152. _this.REFRACTIONMAP_OPPOSITEZ = false;
  45153. _this.LODINREFRACTIONALPHA = false;
  45154. _this.GAMMAREFRACTION = false;
  45155. _this.RGBDREFRACTION = false;
  45156. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  45157. _this.INSTANCES = false;
  45158. _this.NUM_BONE_INFLUENCERS = 0;
  45159. _this.BonesPerMesh = 0;
  45160. _this.NONUNIFORMSCALING = false;
  45161. _this.MORPHTARGETS = false;
  45162. _this.MORPHTARGETS_NORMAL = false;
  45163. _this.MORPHTARGETS_TANGENT = false;
  45164. _this.NUM_MORPH_INFLUENCERS = 0;
  45165. _this.IMAGEPROCESSING = false;
  45166. _this.VIGNETTE = false;
  45167. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  45168. _this.VIGNETTEBLENDMODEOPAQUE = false;
  45169. _this.TONEMAPPING = false;
  45170. _this.TONEMAPPING_ACES = false;
  45171. _this.CONTRAST = false;
  45172. _this.COLORCURVES = false;
  45173. _this.COLORGRADING = false;
  45174. _this.COLORGRADING3D = false;
  45175. _this.SAMPLER3DGREENDEPTH = false;
  45176. _this.SAMPLER3DBGRMAP = false;
  45177. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  45178. _this.EXPOSURE = false;
  45179. _this.USEPHYSICALLIGHTFALLOFF = false;
  45180. _this.USEGLTFLIGHTFALLOFF = false;
  45181. _this.TWOSIDEDLIGHTING = false;
  45182. _this.SHADOWFLOAT = false;
  45183. _this.CLIPPLANE = false;
  45184. _this.CLIPPLANE2 = false;
  45185. _this.CLIPPLANE3 = false;
  45186. _this.CLIPPLANE4 = false;
  45187. _this.POINTSIZE = false;
  45188. _this.FOG = false;
  45189. _this.LOGARITHMICDEPTH = false;
  45190. _this.FORCENORMALFORWARD = false;
  45191. _this.SPECULARAA = false;
  45192. _this.UNLIT = false;
  45193. _this.rebuild();
  45194. return _this;
  45195. }
  45196. /**
  45197. * Resets the PBR Material defines.
  45198. */
  45199. PBRMaterialDefines.prototype.reset = function () {
  45200. _super.prototype.reset.call(this);
  45201. this.ALPHATESTVALUE = "0.5";
  45202. this.PBR = true;
  45203. };
  45204. return PBRMaterialDefines;
  45205. }(BABYLON.MaterialDefines));
  45206. /**
  45207. * The Physically based material base class of BJS.
  45208. *
  45209. * This offers the main features of a standard PBR material.
  45210. * For more information, please refer to the documentation :
  45211. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45212. */
  45213. var PBRBaseMaterial = /** @class */ (function (_super) {
  45214. __extends(PBRBaseMaterial, _super);
  45215. /**
  45216. * Instantiates a new PBRMaterial instance.
  45217. *
  45218. * @param name The material name
  45219. * @param scene The scene the material will be use in.
  45220. */
  45221. function PBRBaseMaterial(name, scene) {
  45222. var _this = _super.call(this, name, scene) || this;
  45223. /**
  45224. * Intensity of the direct lights e.g. the four lights available in your scene.
  45225. * This impacts both the direct diffuse and specular highlights.
  45226. */
  45227. _this._directIntensity = 1.0;
  45228. /**
  45229. * Intensity of the emissive part of the material.
  45230. * This helps controlling the emissive effect without modifying the emissive color.
  45231. */
  45232. _this._emissiveIntensity = 1.0;
  45233. /**
  45234. * Intensity of the environment e.g. how much the environment will light the object
  45235. * either through harmonics for rough material or through the refelction for shiny ones.
  45236. */
  45237. _this._environmentIntensity = 1.0;
  45238. /**
  45239. * This is a special control allowing the reduction of the specular highlights coming from the
  45240. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45241. */
  45242. _this._specularIntensity = 1.0;
  45243. /**
  45244. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  45245. */
  45246. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  45247. /**
  45248. * Debug Control allowing disabling the bump map on this material.
  45249. */
  45250. _this._disableBumpMap = false;
  45251. /**
  45252. * AKA Occlusion Texture Intensity in other nomenclature.
  45253. */
  45254. _this._ambientTextureStrength = 1.0;
  45255. /**
  45256. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45257. * 1 means it completely occludes it
  45258. * 0 mean it has no impact
  45259. */
  45260. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45261. /**
  45262. * The color of a material in ambient lighting.
  45263. */
  45264. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  45265. /**
  45266. * AKA Diffuse Color in other nomenclature.
  45267. */
  45268. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  45269. /**
  45270. * AKA Specular Color in other nomenclature.
  45271. */
  45272. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45273. /**
  45274. * The color applied when light is reflected from a material.
  45275. */
  45276. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  45277. /**
  45278. * The color applied when light is emitted from a material.
  45279. */
  45280. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  45281. /**
  45282. * AKA Glossiness in other nomenclature.
  45283. */
  45284. _this._microSurface = 0.9;
  45285. /**
  45286. * source material index of refraction (IOR)' / 'destination material IOR.
  45287. */
  45288. _this._indexOfRefraction = 0.66;
  45289. /**
  45290. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45291. */
  45292. _this._invertRefractionY = false;
  45293. /**
  45294. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45295. * Materials half opaque for instance using refraction could benefit from this control.
  45296. */
  45297. _this._linkRefractionWithTransparency = false;
  45298. /**
  45299. * Specifies that the material will use the light map as a show map.
  45300. */
  45301. _this._useLightmapAsShadowmap = false;
  45302. /**
  45303. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45304. * makes the reflect vector face the model (under horizon).
  45305. */
  45306. _this._useHorizonOcclusion = true;
  45307. /**
  45308. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45309. * too much the area relying on ambient texture to define their ambient occlusion.
  45310. */
  45311. _this._useRadianceOcclusion = true;
  45312. /**
  45313. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45314. */
  45315. _this._useAlphaFromAlbedoTexture = false;
  45316. /**
  45317. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45318. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45319. */
  45320. _this._useSpecularOverAlpha = true;
  45321. /**
  45322. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45323. */
  45324. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  45325. /**
  45326. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45327. */
  45328. _this._useRoughnessFromMetallicTextureAlpha = true;
  45329. /**
  45330. * Specifies if the metallic texture contains the roughness information in its green channel.
  45331. */
  45332. _this._useRoughnessFromMetallicTextureGreen = false;
  45333. /**
  45334. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45335. */
  45336. _this._useMetallnessFromMetallicTextureBlue = false;
  45337. /**
  45338. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45339. */
  45340. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  45341. /**
  45342. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45343. */
  45344. _this._useAmbientInGrayScale = false;
  45345. /**
  45346. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45347. * The material will try to infer what glossiness each pixel should be.
  45348. */
  45349. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  45350. /**
  45351. * Defines the falloff type used in this material.
  45352. * It by default is Physical.
  45353. */
  45354. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45355. /**
  45356. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45357. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45358. */
  45359. _this._useRadianceOverAlpha = true;
  45360. /**
  45361. * Allows using an object space normal map (instead of tangent space).
  45362. */
  45363. _this._useObjectSpaceNormalMap = false;
  45364. /**
  45365. * Allows using the bump map in parallax mode.
  45366. */
  45367. _this._useParallax = false;
  45368. /**
  45369. * Allows using the bump map in parallax occlusion mode.
  45370. */
  45371. _this._useParallaxOcclusion = false;
  45372. /**
  45373. * Controls the scale bias of the parallax mode.
  45374. */
  45375. _this._parallaxScaleBias = 0.05;
  45376. /**
  45377. * If sets to true, disables all the lights affecting the material.
  45378. */
  45379. _this._disableLighting = false;
  45380. /**
  45381. * Number of Simultaneous lights allowed on the material.
  45382. */
  45383. _this._maxSimultaneousLights = 4;
  45384. /**
  45385. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  45386. */
  45387. _this._invertNormalMapX = false;
  45388. /**
  45389. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  45390. */
  45391. _this._invertNormalMapY = false;
  45392. /**
  45393. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45394. */
  45395. _this._twoSidedLighting = false;
  45396. /**
  45397. * Defines the alpha limits in alpha test mode.
  45398. */
  45399. _this._alphaCutOff = 0.4;
  45400. /**
  45401. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45402. */
  45403. _this._forceAlphaTest = false;
  45404. /**
  45405. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45406. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45407. */
  45408. _this._useAlphaFresnel = false;
  45409. /**
  45410. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45411. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45412. */
  45413. _this._useLinearAlphaFresnel = false;
  45414. /**
  45415. * The transparency mode of the material.
  45416. */
  45417. _this._transparencyMode = null;
  45418. /**
  45419. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  45420. * from cos thetav and roughness:
  45421. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  45422. */
  45423. _this._environmentBRDFTexture = null;
  45424. /**
  45425. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45426. */
  45427. _this._forceIrradianceInFragment = false;
  45428. /**
  45429. * Force normal to face away from face.
  45430. */
  45431. _this._forceNormalForward = false;
  45432. /**
  45433. * Enables specular anti aliasing in the PBR shader.
  45434. * It will both interacts on the Geometry for analytical and IBL lighting.
  45435. * It also prefilter the roughness map based on the bump values.
  45436. */
  45437. _this._enableSpecularAntiAliasing = false;
  45438. /**
  45439. * Stores the available render targets.
  45440. */
  45441. _this._renderTargets = new BABYLON.SmartArray(16);
  45442. /**
  45443. * Sets the global ambient color for the material used in lighting calculations.
  45444. */
  45445. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  45446. /**
  45447. * If set to true, no lighting calculations will be applied.
  45448. */
  45449. _this._unlit = false;
  45450. // Setup the default processing configuration to the scene.
  45451. _this._attachImageProcessingConfiguration(null);
  45452. _this.getRenderTargetTextures = function () {
  45453. _this._renderTargets.reset();
  45454. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  45455. _this._renderTargets.push(_this._reflectionTexture);
  45456. }
  45457. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  45458. _this._renderTargets.push(_this._refractionTexture);
  45459. }
  45460. return _this._renderTargets;
  45461. };
  45462. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45463. return _this;
  45464. }
  45465. /**
  45466. * Attaches a new image processing configuration to the PBR Material.
  45467. * @param configuration
  45468. */
  45469. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  45470. var _this = this;
  45471. if (configuration === this._imageProcessingConfiguration) {
  45472. return;
  45473. }
  45474. // Detaches observer.
  45475. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45476. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45477. }
  45478. // Pick the scene configuration if needed.
  45479. if (!configuration) {
  45480. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  45481. }
  45482. else {
  45483. this._imageProcessingConfiguration = configuration;
  45484. }
  45485. // Attaches observer.
  45486. if (this._imageProcessingConfiguration) {
  45487. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  45488. _this._markAllSubMeshesAsImageProcessingDirty();
  45489. });
  45490. }
  45491. };
  45492. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  45493. /**
  45494. * Gets a boolean indicating that current material needs to register RTT
  45495. */
  45496. get: function () {
  45497. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45498. return true;
  45499. }
  45500. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45501. return true;
  45502. }
  45503. return false;
  45504. },
  45505. enumerable: true,
  45506. configurable: true
  45507. });
  45508. /**
  45509. * Gets the name of the material class.
  45510. */
  45511. PBRBaseMaterial.prototype.getClassName = function () {
  45512. return "PBRBaseMaterial";
  45513. };
  45514. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  45515. /**
  45516. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45517. */
  45518. get: function () {
  45519. return this._useLogarithmicDepth;
  45520. },
  45521. /**
  45522. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45523. */
  45524. set: function (value) {
  45525. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  45526. },
  45527. enumerable: true,
  45528. configurable: true
  45529. });
  45530. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  45531. /**
  45532. * Gets the current transparency mode.
  45533. */
  45534. get: function () {
  45535. return this._transparencyMode;
  45536. },
  45537. /**
  45538. * Sets the transparency mode of the material.
  45539. *
  45540. * | Value | Type | Description |
  45541. * | ----- | ----------------------------------- | ----------- |
  45542. * | 0 | OPAQUE | |
  45543. * | 1 | ALPHATEST | |
  45544. * | 2 | ALPHABLEND | |
  45545. * | 3 | ALPHATESTANDBLEND | |
  45546. *
  45547. */
  45548. set: function (value) {
  45549. if (this._transparencyMode === value) {
  45550. return;
  45551. }
  45552. this._transparencyMode = value;
  45553. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  45554. this._markAllSubMeshesAsTexturesAndMiscDirty();
  45555. },
  45556. enumerable: true,
  45557. configurable: true
  45558. });
  45559. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  45560. /**
  45561. * Returns true if alpha blending should be disabled.
  45562. */
  45563. get: function () {
  45564. return (this._linkRefractionWithTransparency ||
  45565. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  45566. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45567. },
  45568. enumerable: true,
  45569. configurable: true
  45570. });
  45571. /**
  45572. * Specifies whether or not this material should be rendered in alpha blend mode.
  45573. */
  45574. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  45575. if (this._disableAlphaBlending) {
  45576. return false;
  45577. }
  45578. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  45579. };
  45580. /**
  45581. * Specifies if the mesh will require alpha blending.
  45582. * @param mesh - BJS mesh.
  45583. */
  45584. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  45585. if (this._disableAlphaBlending) {
  45586. return false;
  45587. }
  45588. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  45589. };
  45590. /**
  45591. * Specifies whether or not this material should be rendered in alpha test mode.
  45592. */
  45593. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  45594. if (this._forceAlphaTest) {
  45595. return true;
  45596. }
  45597. if (this._linkRefractionWithTransparency) {
  45598. return false;
  45599. }
  45600. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45601. };
  45602. /**
  45603. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  45604. */
  45605. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45606. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45607. };
  45608. /**
  45609. * Gets the texture used for the alpha test.
  45610. */
  45611. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45612. return this._albedoTexture;
  45613. };
  45614. /**
  45615. * Specifies that the submesh is ready to be used.
  45616. * @param mesh - BJS mesh.
  45617. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45618. * @param useInstances - Specifies that instances should be used.
  45619. * @returns - boolean indicating that the submesh is ready or not.
  45620. */
  45621. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45622. if (subMesh.effect && this.isFrozen) {
  45623. if (this._wasPreviouslyReady) {
  45624. return true;
  45625. }
  45626. }
  45627. if (!subMesh._materialDefines) {
  45628. subMesh._materialDefines = new PBRMaterialDefines();
  45629. }
  45630. var defines = subMesh._materialDefines;
  45631. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45632. if (defines._renderId === this.getScene().getRenderId()) {
  45633. return true;
  45634. }
  45635. }
  45636. var scene = this.getScene();
  45637. var engine = scene.getEngine();
  45638. if (defines._areTexturesDirty) {
  45639. if (scene.texturesEnabled) {
  45640. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45641. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45642. return false;
  45643. }
  45644. }
  45645. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45646. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45647. return false;
  45648. }
  45649. }
  45650. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45651. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45652. return false;
  45653. }
  45654. }
  45655. var reflectionTexture = this._getReflectionTexture();
  45656. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45657. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45658. return false;
  45659. }
  45660. }
  45661. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45662. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45663. return false;
  45664. }
  45665. }
  45666. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45667. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45668. return false;
  45669. }
  45670. }
  45671. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45672. if (this._metallicTexture) {
  45673. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45674. return false;
  45675. }
  45676. }
  45677. else if (this._reflectivityTexture) {
  45678. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45679. return false;
  45680. }
  45681. }
  45682. if (this._microSurfaceTexture) {
  45683. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45684. return false;
  45685. }
  45686. }
  45687. }
  45688. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45689. // Bump texture cannot be not blocking.
  45690. if (!this._bumpTexture.isReady()) {
  45691. return false;
  45692. }
  45693. }
  45694. var refractionTexture = this._getRefractionTexture();
  45695. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45696. if (!refractionTexture.isReadyOrNotBlocking()) {
  45697. return false;
  45698. }
  45699. }
  45700. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45701. // This is blocking.
  45702. if (!this._environmentBRDFTexture.isReady()) {
  45703. return false;
  45704. }
  45705. }
  45706. }
  45707. }
  45708. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  45709. if (!this._imageProcessingConfiguration.isReady()) {
  45710. return false;
  45711. }
  45712. }
  45713. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45714. mesh.createNormals(true);
  45715. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45716. }
  45717. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45718. if (effect) {
  45719. scene.resetCachedMaterial();
  45720. subMesh.setEffect(effect, defines);
  45721. this.buildUniformLayout();
  45722. }
  45723. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45724. return false;
  45725. }
  45726. defines._renderId = scene.getRenderId();
  45727. this._wasPreviouslyReady = true;
  45728. return true;
  45729. };
  45730. /**
  45731. * Specifies if the material uses metallic roughness workflow.
  45732. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45733. */
  45734. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45735. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45736. return true;
  45737. }
  45738. return false;
  45739. };
  45740. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45741. if (onCompiled === void 0) { onCompiled = null; }
  45742. if (onError === void 0) { onError = null; }
  45743. if (useInstances === void 0) { useInstances = null; }
  45744. if (useClipPlane === void 0) { useClipPlane = null; }
  45745. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45746. if (!defines.isDirty) {
  45747. return null;
  45748. }
  45749. defines.markAsProcessed();
  45750. var scene = this.getScene();
  45751. var engine = scene.getEngine();
  45752. // Fallbacks
  45753. var fallbacks = new BABYLON.EffectFallbacks();
  45754. var fallbackRank = 0;
  45755. if (defines.USESPHERICALINVERTEX) {
  45756. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45757. }
  45758. if (defines.FOG) {
  45759. fallbacks.addFallback(fallbackRank, "FOG");
  45760. }
  45761. if (defines.SPECULARAA) {
  45762. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45763. }
  45764. if (defines.POINTSIZE) {
  45765. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45766. }
  45767. if (defines.LOGARITHMICDEPTH) {
  45768. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45769. }
  45770. if (defines.PARALLAX) {
  45771. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45772. }
  45773. if (defines.PARALLAXOCCLUSION) {
  45774. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45775. }
  45776. if (defines.ENVIRONMENTBRDF) {
  45777. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45778. }
  45779. if (defines.TANGENT) {
  45780. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45781. }
  45782. if (defines.BUMP) {
  45783. fallbacks.addFallback(fallbackRank++, "BUMP");
  45784. }
  45785. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45786. if (defines.SPECULARTERM) {
  45787. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45788. }
  45789. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45790. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45791. }
  45792. if (defines.LIGHTMAP) {
  45793. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45794. }
  45795. if (defines.NORMAL) {
  45796. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45797. }
  45798. if (defines.AMBIENT) {
  45799. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45800. }
  45801. if (defines.EMISSIVE) {
  45802. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45803. }
  45804. if (defines.VERTEXCOLOR) {
  45805. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45806. }
  45807. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45808. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45809. }
  45810. if (defines.MORPHTARGETS) {
  45811. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45812. }
  45813. //Attributes
  45814. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45815. if (defines.NORMAL) {
  45816. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45817. }
  45818. if (defines.TANGENT) {
  45819. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45820. }
  45821. if (defines.UV1) {
  45822. attribs.push(BABYLON.VertexBuffer.UVKind);
  45823. }
  45824. if (defines.UV2) {
  45825. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45826. }
  45827. if (defines.VERTEXCOLOR) {
  45828. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45829. }
  45830. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45831. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45832. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45833. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45834. "vFogInfos", "vFogColor", "pointSize",
  45835. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45836. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45837. "mBones",
  45838. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45839. "vLightingIntensity",
  45840. "logarithmicDepthConstant",
  45841. "vSphericalX", "vSphericalY", "vSphericalZ",
  45842. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45843. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45844. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45845. "vTangentSpaceParams"
  45846. ];
  45847. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45848. "bumpSampler", "lightmapSampler", "opacitySampler",
  45849. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45850. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45851. "microSurfaceSampler", "environmentBrdfSampler"];
  45852. var uniformBuffers = ["Material", "Scene"];
  45853. if (BABYLON.ImageProcessingConfiguration) {
  45854. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45855. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45856. }
  45857. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45858. uniformsNames: uniforms,
  45859. uniformBuffersNames: uniformBuffers,
  45860. samplers: samplers,
  45861. defines: defines,
  45862. maxSimultaneousLights: this._maxSimultaneousLights
  45863. });
  45864. var join = defines.toString();
  45865. return engine.createEffect("pbr", {
  45866. attributes: attribs,
  45867. uniformsNames: uniforms,
  45868. uniformBuffersNames: uniformBuffers,
  45869. samplers: samplers,
  45870. defines: join,
  45871. fallbacks: fallbacks,
  45872. onCompiled: onCompiled,
  45873. onError: onError,
  45874. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45875. }, engine);
  45876. };
  45877. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45878. if (useInstances === void 0) { useInstances = null; }
  45879. if (useClipPlane === void 0) { useClipPlane = null; }
  45880. var scene = this.getScene();
  45881. var engine = scene.getEngine();
  45882. // Lights
  45883. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45884. defines._needNormals = true;
  45885. // Textures
  45886. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45887. if (defines._areTexturesDirty) {
  45888. defines._needUVs = false;
  45889. if (scene.texturesEnabled) {
  45890. if (scene.getEngine().getCaps().textureLOD) {
  45891. defines.LODBASEDMICROSFURACE = true;
  45892. }
  45893. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45894. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45895. }
  45896. else {
  45897. defines.ALBEDO = false;
  45898. }
  45899. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45900. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45901. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45902. }
  45903. else {
  45904. defines.AMBIENT = false;
  45905. }
  45906. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45907. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45908. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45909. }
  45910. else {
  45911. defines.OPACITY = false;
  45912. }
  45913. var reflectionTexture = this._getReflectionTexture();
  45914. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45915. defines.REFLECTION = true;
  45916. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45917. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  45918. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45919. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45920. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45921. defines.INVERTCUBICMAP = true;
  45922. }
  45923. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45924. switch (reflectionTexture.coordinatesMode) {
  45925. case BABYLON.Texture.EXPLICIT_MODE:
  45926. defines.REFLECTIONMAP_EXPLICIT = true;
  45927. break;
  45928. case BABYLON.Texture.PLANAR_MODE:
  45929. defines.REFLECTIONMAP_PLANAR = true;
  45930. break;
  45931. case BABYLON.Texture.PROJECTION_MODE:
  45932. defines.REFLECTIONMAP_PROJECTION = true;
  45933. break;
  45934. case BABYLON.Texture.SKYBOX_MODE:
  45935. defines.REFLECTIONMAP_SKYBOX = true;
  45936. break;
  45937. case BABYLON.Texture.SPHERICAL_MODE:
  45938. defines.REFLECTIONMAP_SPHERICAL = true;
  45939. break;
  45940. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45941. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45942. break;
  45943. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45944. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45945. break;
  45946. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45947. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45948. break;
  45949. case BABYLON.Texture.CUBIC_MODE:
  45950. case BABYLON.Texture.INVCUBIC_MODE:
  45951. default:
  45952. defines.REFLECTIONMAP_CUBIC = true;
  45953. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45954. break;
  45955. }
  45956. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45957. if (reflectionTexture.sphericalPolynomial) {
  45958. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45959. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45960. defines.USESPHERICALINVERTEX = false;
  45961. }
  45962. else {
  45963. defines.USESPHERICALINVERTEX = true;
  45964. }
  45965. }
  45966. }
  45967. else {
  45968. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  45969. }
  45970. }
  45971. else {
  45972. defines.REFLECTION = false;
  45973. defines.REFLECTIONMAP_3D = false;
  45974. defines.REFLECTIONMAP_SPHERICAL = false;
  45975. defines.REFLECTIONMAP_PLANAR = false;
  45976. defines.REFLECTIONMAP_CUBIC = false;
  45977. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45978. defines.REFLECTIONMAP_PROJECTION = false;
  45979. defines.REFLECTIONMAP_SKYBOX = false;
  45980. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  45981. defines.REFLECTIONMAP_EXPLICIT = false;
  45982. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45983. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45984. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45985. defines.INVERTCUBICMAP = false;
  45986. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45987. defines.USESPHERICALINVERTEX = false;
  45988. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45989. defines.LODINREFLECTIONALPHA = false;
  45990. defines.GAMMAREFLECTION = false;
  45991. defines.RGBDREFLECTION = false;
  45992. }
  45993. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45994. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45995. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45996. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45997. }
  45998. else {
  45999. defines.LIGHTMAP = false;
  46000. }
  46001. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46002. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  46003. }
  46004. else {
  46005. defines.EMISSIVE = false;
  46006. }
  46007. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46008. if (this._metallicTexture) {
  46009. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  46010. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  46011. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  46012. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  46013. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  46014. }
  46015. else if (this._reflectivityTexture) {
  46016. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  46017. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  46018. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  46019. }
  46020. else {
  46021. defines.REFLECTIVITY = false;
  46022. }
  46023. if (this._microSurfaceTexture) {
  46024. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  46025. }
  46026. else {
  46027. defines.MICROSURFACEMAP = false;
  46028. }
  46029. }
  46030. else {
  46031. defines.REFLECTIVITY = false;
  46032. defines.MICROSURFACEMAP = false;
  46033. }
  46034. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46035. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  46036. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46037. defines.PARALLAX = true;
  46038. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  46039. }
  46040. else {
  46041. defines.PARALLAX = false;
  46042. }
  46043. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  46044. }
  46045. else {
  46046. defines.BUMP = false;
  46047. }
  46048. var refractionTexture = this._getRefractionTexture();
  46049. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46050. defines.REFRACTION = true;
  46051. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  46052. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  46053. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  46054. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  46055. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  46056. if (this._linkRefractionWithTransparency) {
  46057. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  46058. }
  46059. }
  46060. else {
  46061. defines.REFRACTION = false;
  46062. }
  46063. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46064. defines.ENVIRONMENTBRDF = true;
  46065. }
  46066. else {
  46067. defines.ENVIRONMENTBRDF = false;
  46068. }
  46069. if (this._shouldUseAlphaFromAlbedoTexture()) {
  46070. defines.ALPHAFROMALBEDO = true;
  46071. }
  46072. else {
  46073. defines.ALPHAFROMALBEDO = false;
  46074. }
  46075. }
  46076. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  46077. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  46078. defines.USEPHYSICALLIGHTFALLOFF = false;
  46079. defines.USEGLTFLIGHTFALLOFF = false;
  46080. }
  46081. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  46082. defines.USEPHYSICALLIGHTFALLOFF = false;
  46083. defines.USEGLTFLIGHTFALLOFF = true;
  46084. }
  46085. else {
  46086. defines.USEPHYSICALLIGHTFALLOFF = true;
  46087. defines.USEGLTFLIGHTFALLOFF = false;
  46088. }
  46089. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  46090. if (!this.backFaceCulling && this._twoSidedLighting) {
  46091. defines.TWOSIDEDLIGHTING = true;
  46092. }
  46093. else {
  46094. defines.TWOSIDEDLIGHTING = false;
  46095. }
  46096. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  46097. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  46098. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  46099. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  46100. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  46101. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  46102. }
  46103. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  46104. this._imageProcessingConfiguration.prepareDefines(defines);
  46105. }
  46106. defines.FORCENORMALFORWARD = this._forceNormalForward;
  46107. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  46108. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  46109. // Misc.
  46110. if (defines._areMiscDirty) {
  46111. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  46112. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  46113. }
  46114. // Values that need to be evaluated on every frame
  46115. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  46116. // Attribs
  46117. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  46118. };
  46119. /**
  46120. * Force shader compilation
  46121. */
  46122. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  46123. var _this = this;
  46124. var localOptions = __assign({ clipPlane: false }, options);
  46125. var defines = new PBRMaterialDefines();
  46126. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  46127. if (effect.isReady()) {
  46128. if (onCompiled) {
  46129. onCompiled(this);
  46130. }
  46131. }
  46132. else {
  46133. effect.onCompileObservable.add(function () {
  46134. if (onCompiled) {
  46135. onCompiled(_this);
  46136. }
  46137. });
  46138. }
  46139. };
  46140. /**
  46141. * Initializes the uniform buffer layout for the shader.
  46142. */
  46143. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  46144. // Order is important !
  46145. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  46146. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  46147. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  46148. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  46149. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  46150. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  46151. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  46152. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  46153. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  46154. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  46155. this._uniformBuffer.addUniform("vReflectionSize", 3);
  46156. this._uniformBuffer.addUniform("vBumpInfos", 3);
  46157. this._uniformBuffer.addUniform("albedoMatrix", 16);
  46158. this._uniformBuffer.addUniform("ambientMatrix", 16);
  46159. this._uniformBuffer.addUniform("opacityMatrix", 16);
  46160. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  46161. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  46162. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  46163. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  46164. this._uniformBuffer.addUniform("bumpMatrix", 16);
  46165. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  46166. this._uniformBuffer.addUniform("refractionMatrix", 16);
  46167. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  46168. this._uniformBuffer.addUniform("vReflectionColor", 3);
  46169. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  46170. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  46171. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  46172. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  46173. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  46174. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  46175. this._uniformBuffer.addUniform("pointSize", 1);
  46176. this._uniformBuffer.create();
  46177. };
  46178. /**
  46179. * Unbinds the textures.
  46180. */
  46181. PBRBaseMaterial.prototype.unbind = function () {
  46182. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  46183. this._uniformBuffer.setTexture("reflectionSampler", null);
  46184. }
  46185. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  46186. this._uniformBuffer.setTexture("refractionSampler", null);
  46187. }
  46188. _super.prototype.unbind.call(this);
  46189. };
  46190. /**
  46191. * Binds the submesh data.
  46192. * @param world - The world matrix.
  46193. * @param mesh - The BJS mesh.
  46194. * @param subMesh - A submesh of the BJS mesh.
  46195. */
  46196. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  46197. var scene = this.getScene();
  46198. var defines = subMesh._materialDefines;
  46199. if (!defines) {
  46200. return;
  46201. }
  46202. var effect = subMesh.effect;
  46203. if (!effect) {
  46204. return;
  46205. }
  46206. this._activeEffect = effect;
  46207. // Matrices
  46208. this.bindOnlyWorldMatrix(world);
  46209. // Normal Matrix
  46210. if (defines.OBJECTSPACE_NORMALMAP) {
  46211. world.toNormalMatrix(this._normalMatrix);
  46212. this.bindOnlyNormalMatrix(this._normalMatrix);
  46213. }
  46214. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  46215. // Bones
  46216. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  46217. var reflectionTexture = null;
  46218. if (mustRebind) {
  46219. this._uniformBuffer.bindToEffect(effect, "Material");
  46220. this.bindViewProjection(effect);
  46221. reflectionTexture = this._getReflectionTexture();
  46222. var refractionTexture = this._getRefractionTexture();
  46223. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  46224. // Texture uniforms
  46225. if (scene.texturesEnabled) {
  46226. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46227. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  46228. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  46229. }
  46230. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46231. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  46232. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  46233. }
  46234. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46235. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  46236. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  46237. }
  46238. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46239. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  46240. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  46241. if (reflectionTexture.boundingBoxSize) {
  46242. var cubeTexture = reflectionTexture;
  46243. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  46244. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  46245. }
  46246. var polynomials = reflectionTexture.sphericalPolynomial;
  46247. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  46248. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  46249. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  46250. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  46251. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  46252. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  46253. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  46254. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  46255. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  46256. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  46257. }
  46258. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  46259. }
  46260. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46261. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  46262. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  46263. }
  46264. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46265. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  46266. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  46267. }
  46268. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46269. if (this._metallicTexture) {
  46270. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  46271. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  46272. }
  46273. else if (this._reflectivityTexture) {
  46274. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  46275. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  46276. }
  46277. if (this._microSurfaceTexture) {
  46278. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  46279. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  46280. }
  46281. }
  46282. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46283. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  46284. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  46285. if (scene._mirroredCameraPosition) {
  46286. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  46287. }
  46288. else {
  46289. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  46290. }
  46291. }
  46292. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46293. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  46294. var depth = 1.0;
  46295. if (!refractionTexture.isCube) {
  46296. if (refractionTexture.depth) {
  46297. depth = refractionTexture.depth;
  46298. }
  46299. }
  46300. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  46301. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  46302. }
  46303. }
  46304. // Point size
  46305. if (this.pointsCloud) {
  46306. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  46307. }
  46308. // Colors
  46309. if (defines.METALLICWORKFLOW) {
  46310. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  46311. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  46312. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  46313. }
  46314. else {
  46315. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  46316. }
  46317. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  46318. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  46319. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  46320. // Misc
  46321. this._lightingInfos.x = this._directIntensity;
  46322. this._lightingInfos.y = this._emissiveIntensity;
  46323. this._lightingInfos.z = this._environmentIntensity;
  46324. this._lightingInfos.w = this._specularIntensity;
  46325. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  46326. }
  46327. // Textures
  46328. if (scene.texturesEnabled) {
  46329. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46330. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  46331. }
  46332. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46333. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  46334. }
  46335. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46336. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  46337. }
  46338. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46339. if (defines.LODBASEDMICROSFURACE) {
  46340. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  46341. }
  46342. else {
  46343. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  46344. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  46345. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  46346. }
  46347. }
  46348. if (defines.ENVIRONMENTBRDF) {
  46349. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  46350. }
  46351. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46352. if (defines.LODBASEDMICROSFURACE) {
  46353. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  46354. }
  46355. else {
  46356. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  46357. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  46358. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  46359. }
  46360. }
  46361. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46362. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  46363. }
  46364. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46365. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  46366. }
  46367. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46368. if (this._metallicTexture) {
  46369. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  46370. }
  46371. else if (this._reflectivityTexture) {
  46372. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  46373. }
  46374. if (this._microSurfaceTexture) {
  46375. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  46376. }
  46377. }
  46378. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46379. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  46380. }
  46381. }
  46382. // Clip plane
  46383. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  46384. // Colors
  46385. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  46386. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  46387. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  46388. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  46389. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  46390. }
  46391. if (mustRebind || !this.isFrozen) {
  46392. // Lights
  46393. if (scene.lightsEnabled && !this._disableLighting) {
  46394. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  46395. }
  46396. // View
  46397. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  46398. this.bindView(effect);
  46399. }
  46400. // Fog
  46401. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  46402. // Morph targets
  46403. if (defines.NUM_MORPH_INFLUENCERS) {
  46404. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  46405. }
  46406. // image processing
  46407. this._imageProcessingConfiguration.bind(this._activeEffect);
  46408. // Log. depth
  46409. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  46410. }
  46411. this._uniformBuffer.update();
  46412. this._afterBind(mesh, this._activeEffect);
  46413. };
  46414. /**
  46415. * Returns the animatable textures.
  46416. * @returns - Array of animatable textures.
  46417. */
  46418. PBRBaseMaterial.prototype.getAnimatables = function () {
  46419. var results = [];
  46420. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  46421. results.push(this._albedoTexture);
  46422. }
  46423. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  46424. results.push(this._ambientTexture);
  46425. }
  46426. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  46427. results.push(this._opacityTexture);
  46428. }
  46429. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  46430. results.push(this._reflectionTexture);
  46431. }
  46432. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  46433. results.push(this._emissiveTexture);
  46434. }
  46435. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  46436. results.push(this._metallicTexture);
  46437. }
  46438. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  46439. results.push(this._reflectivityTexture);
  46440. }
  46441. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  46442. results.push(this._bumpTexture);
  46443. }
  46444. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  46445. results.push(this._lightmapTexture);
  46446. }
  46447. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  46448. results.push(this._refractionTexture);
  46449. }
  46450. return results;
  46451. };
  46452. /**
  46453. * Returns the texture used for reflections.
  46454. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  46455. */
  46456. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  46457. if (this._reflectionTexture) {
  46458. return this._reflectionTexture;
  46459. }
  46460. return this.getScene().environmentTexture;
  46461. };
  46462. /**
  46463. * Returns the texture used for refraction or null if none is used.
  46464. * @returns - Refection texture if present. If no refraction texture and refraction
  46465. * is linked with transparency, returns environment texture. Otherwise, returns null.
  46466. */
  46467. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  46468. if (this._refractionTexture) {
  46469. return this._refractionTexture;
  46470. }
  46471. if (this._linkRefractionWithTransparency) {
  46472. return this.getScene().environmentTexture;
  46473. }
  46474. return null;
  46475. };
  46476. /**
  46477. * Disposes the resources of the material.
  46478. * @param forceDisposeEffect - Forces the disposal of effects.
  46479. * @param forceDisposeTextures - Forces the disposal of all textures.
  46480. */
  46481. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46482. if (forceDisposeTextures) {
  46483. if (this._albedoTexture) {
  46484. this._albedoTexture.dispose();
  46485. }
  46486. if (this._ambientTexture) {
  46487. this._ambientTexture.dispose();
  46488. }
  46489. if (this._opacityTexture) {
  46490. this._opacityTexture.dispose();
  46491. }
  46492. if (this._reflectionTexture) {
  46493. this._reflectionTexture.dispose();
  46494. }
  46495. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  46496. this._environmentBRDFTexture.dispose();
  46497. }
  46498. if (this._emissiveTexture) {
  46499. this._emissiveTexture.dispose();
  46500. }
  46501. if (this._metallicTexture) {
  46502. this._metallicTexture.dispose();
  46503. }
  46504. if (this._reflectivityTexture) {
  46505. this._reflectivityTexture.dispose();
  46506. }
  46507. if (this._bumpTexture) {
  46508. this._bumpTexture.dispose();
  46509. }
  46510. if (this._lightmapTexture) {
  46511. this._lightmapTexture.dispose();
  46512. }
  46513. if (this._refractionTexture) {
  46514. this._refractionTexture.dispose();
  46515. }
  46516. }
  46517. this._renderTargets.dispose();
  46518. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  46519. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  46520. }
  46521. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46522. };
  46523. /**
  46524. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  46525. */
  46526. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  46527. /**
  46528. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  46529. * to enhance interoperability with other engines.
  46530. */
  46531. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  46532. /**
  46533. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  46534. * to enhance interoperability with other materials.
  46535. */
  46536. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  46537. /**
  46538. * Stores the reflectivity values based on metallic roughness workflow.
  46539. */
  46540. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  46541. __decorate([
  46542. BABYLON.serializeAsImageProcessingConfiguration()
  46543. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  46544. __decorate([
  46545. BABYLON.serialize()
  46546. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  46547. __decorate([
  46548. BABYLON.serialize()
  46549. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  46550. return PBRBaseMaterial;
  46551. }(BABYLON.PushMaterial));
  46552. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  46553. })(BABYLON || (BABYLON = {}));
  46554. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  46555. var BABYLON;
  46556. (function (BABYLON) {
  46557. /**
  46558. * The Physically based simple base material of BJS.
  46559. *
  46560. * This enables better naming and convention enforcements on top of the pbrMaterial.
  46561. * It is used as the base class for both the specGloss and metalRough conventions.
  46562. */
  46563. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  46564. __extends(PBRBaseSimpleMaterial, _super);
  46565. /**
  46566. * Instantiates a new PBRMaterial instance.
  46567. *
  46568. * @param name The material name
  46569. * @param scene The scene the material will be use in.
  46570. */
  46571. function PBRBaseSimpleMaterial(name, scene) {
  46572. var _this = _super.call(this, name, scene) || this;
  46573. /**
  46574. * Number of Simultaneous lights allowed on the material.
  46575. */
  46576. _this.maxSimultaneousLights = 4;
  46577. /**
  46578. * If sets to true, disables all the lights affecting the material.
  46579. */
  46580. _this.disableLighting = false;
  46581. /**
  46582. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46583. */
  46584. _this.invertNormalMapX = false;
  46585. /**
  46586. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46587. */
  46588. _this.invertNormalMapY = false;
  46589. /**
  46590. * Emissivie color used to self-illuminate the model.
  46591. */
  46592. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46593. /**
  46594. * Occlusion Channel Strenght.
  46595. */
  46596. _this.occlusionStrength = 1.0;
  46597. /**
  46598. * If true, the light map contains occlusion information instead of lighting info.
  46599. */
  46600. _this.useLightmapAsShadowmap = false;
  46601. _this._useAlphaFromAlbedoTexture = true;
  46602. _this._useAmbientInGrayScale = true;
  46603. return _this;
  46604. }
  46605. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  46606. /**
  46607. * Gets the current double sided mode.
  46608. */
  46609. get: function () {
  46610. return this._twoSidedLighting;
  46611. },
  46612. /**
  46613. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46614. */
  46615. set: function (value) {
  46616. if (this._twoSidedLighting === value) {
  46617. return;
  46618. }
  46619. this._twoSidedLighting = value;
  46620. this.backFaceCulling = !value;
  46621. this._markAllSubMeshesAsTexturesDirty();
  46622. },
  46623. enumerable: true,
  46624. configurable: true
  46625. });
  46626. /**
  46627. * Return the active textures of the material.
  46628. */
  46629. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  46630. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46631. if (this.environmentTexture) {
  46632. activeTextures.push(this.environmentTexture);
  46633. }
  46634. if (this.normalTexture) {
  46635. activeTextures.push(this.normalTexture);
  46636. }
  46637. if (this.emissiveTexture) {
  46638. activeTextures.push(this.emissiveTexture);
  46639. }
  46640. if (this.occlusionTexture) {
  46641. activeTextures.push(this.occlusionTexture);
  46642. }
  46643. if (this.lightmapTexture) {
  46644. activeTextures.push(this.lightmapTexture);
  46645. }
  46646. return activeTextures;
  46647. };
  46648. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  46649. if (_super.prototype.hasTexture.call(this, texture)) {
  46650. return true;
  46651. }
  46652. if (this.lightmapTexture === texture) {
  46653. return true;
  46654. }
  46655. return false;
  46656. };
  46657. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  46658. return "PBRBaseSimpleMaterial";
  46659. };
  46660. __decorate([
  46661. BABYLON.serialize(),
  46662. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46663. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46664. __decorate([
  46665. BABYLON.serialize(),
  46666. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46667. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46668. __decorate([
  46669. BABYLON.serializeAsTexture(),
  46670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46671. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46672. __decorate([
  46673. BABYLON.serialize(),
  46674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46675. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46676. __decorate([
  46677. BABYLON.serialize(),
  46678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46679. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46680. __decorate([
  46681. BABYLON.serializeAsTexture(),
  46682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46683. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46684. __decorate([
  46685. BABYLON.serializeAsColor3("emissive"),
  46686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46687. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46688. __decorate([
  46689. BABYLON.serializeAsTexture(),
  46690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46691. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46692. __decorate([
  46693. BABYLON.serialize(),
  46694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46695. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46696. __decorate([
  46697. BABYLON.serializeAsTexture(),
  46698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46699. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46700. __decorate([
  46701. BABYLON.serialize(),
  46702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46703. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46704. __decorate([
  46705. BABYLON.serialize()
  46706. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46707. __decorate([
  46708. BABYLON.serializeAsTexture(),
  46709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46710. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46711. __decorate([
  46712. BABYLON.serialize(),
  46713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46714. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46715. return PBRBaseSimpleMaterial;
  46716. }(BABYLON.PBRBaseMaterial));
  46717. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46718. })(BABYLON || (BABYLON = {}));
  46719. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46720. var BABYLON;
  46721. (function (BABYLON) {
  46722. /**
  46723. * The Physically based material of BJS.
  46724. *
  46725. * This offers the main features of a standard PBR material.
  46726. * For more information, please refer to the documentation :
  46727. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46728. */
  46729. var PBRMaterial = /** @class */ (function (_super) {
  46730. __extends(PBRMaterial, _super);
  46731. /**
  46732. * Instantiates a new PBRMaterial instance.
  46733. *
  46734. * @param name The material name
  46735. * @param scene The scene the material will be use in.
  46736. */
  46737. function PBRMaterial(name, scene) {
  46738. var _this = _super.call(this, name, scene) || this;
  46739. /**
  46740. * Intensity of the direct lights e.g. the four lights available in your scene.
  46741. * This impacts both the direct diffuse and specular highlights.
  46742. */
  46743. _this.directIntensity = 1.0;
  46744. /**
  46745. * Intensity of the emissive part of the material.
  46746. * This helps controlling the emissive effect without modifying the emissive color.
  46747. */
  46748. _this.emissiveIntensity = 1.0;
  46749. /**
  46750. * Intensity of the environment e.g. how much the environment will light the object
  46751. * either through harmonics for rough material or through the refelction for shiny ones.
  46752. */
  46753. _this.environmentIntensity = 1.0;
  46754. /**
  46755. * This is a special control allowing the reduction of the specular highlights coming from the
  46756. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46757. */
  46758. _this.specularIntensity = 1.0;
  46759. /**
  46760. * Debug Control allowing disabling the bump map on this material.
  46761. */
  46762. _this.disableBumpMap = false;
  46763. /**
  46764. * AKA Occlusion Texture Intensity in other nomenclature.
  46765. */
  46766. _this.ambientTextureStrength = 1.0;
  46767. /**
  46768. * Defines how much the AO map is occluding the analytical lights (point spot...).
  46769. * 1 means it completely occludes it
  46770. * 0 mean it has no impact
  46771. */
  46772. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  46773. /**
  46774. * The color of a material in ambient lighting.
  46775. */
  46776. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46777. /**
  46778. * AKA Diffuse Color in other nomenclature.
  46779. */
  46780. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46781. /**
  46782. * AKA Specular Color in other nomenclature.
  46783. */
  46784. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46785. /**
  46786. * The color reflected from the material.
  46787. */
  46788. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46789. /**
  46790. * The color emitted from the material.
  46791. */
  46792. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46793. /**
  46794. * AKA Glossiness in other nomenclature.
  46795. */
  46796. _this.microSurface = 1.0;
  46797. /**
  46798. * source material index of refraction (IOR)' / 'destination material IOR.
  46799. */
  46800. _this.indexOfRefraction = 0.66;
  46801. /**
  46802. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46803. */
  46804. _this.invertRefractionY = false;
  46805. /**
  46806. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46807. * Materials half opaque for instance using refraction could benefit from this control.
  46808. */
  46809. _this.linkRefractionWithTransparency = false;
  46810. /**
  46811. * If true, the light map contains occlusion information instead of lighting info.
  46812. */
  46813. _this.useLightmapAsShadowmap = false;
  46814. /**
  46815. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46816. */
  46817. _this.useAlphaFromAlbedoTexture = false;
  46818. /**
  46819. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46820. */
  46821. _this.forceAlphaTest = false;
  46822. /**
  46823. * Defines the alpha limits in alpha test mode.
  46824. */
  46825. _this.alphaCutOff = 0.4;
  46826. /**
  46827. * Specifies that the material will keep the specular highlights over a transparent surface (only the most limunous ones).
  46828. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46829. */
  46830. _this.useSpecularOverAlpha = true;
  46831. /**
  46832. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46833. */
  46834. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46835. /**
  46836. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46837. */
  46838. _this.useRoughnessFromMetallicTextureAlpha = true;
  46839. /**
  46840. * Specifies if the metallic texture contains the roughness information in its green channel.
  46841. */
  46842. _this.useRoughnessFromMetallicTextureGreen = false;
  46843. /**
  46844. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46845. */
  46846. _this.useMetallnessFromMetallicTextureBlue = false;
  46847. /**
  46848. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46849. */
  46850. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46851. /**
  46852. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46853. */
  46854. _this.useAmbientInGrayScale = false;
  46855. /**
  46856. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46857. * The material will try to infer what glossiness each pixel should be.
  46858. */
  46859. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46860. /**
  46861. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46862. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46863. */
  46864. _this.useRadianceOverAlpha = true;
  46865. /**
  46866. * Allows using an object space normal map (instead of tangent space).
  46867. */
  46868. _this.useObjectSpaceNormalMap = false;
  46869. /**
  46870. * Allows using the bump map in parallax mode.
  46871. */
  46872. _this.useParallax = false;
  46873. /**
  46874. * Allows using the bump map in parallax occlusion mode.
  46875. */
  46876. _this.useParallaxOcclusion = false;
  46877. /**
  46878. * Controls the scale bias of the parallax mode.
  46879. */
  46880. _this.parallaxScaleBias = 0.05;
  46881. /**
  46882. * If sets to true, disables all the lights affecting the material.
  46883. */
  46884. _this.disableLighting = false;
  46885. /**
  46886. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46887. */
  46888. _this.forceIrradianceInFragment = false;
  46889. /**
  46890. * Number of Simultaneous lights allowed on the material.
  46891. */
  46892. _this.maxSimultaneousLights = 4;
  46893. /**
  46894. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46895. */
  46896. _this.invertNormalMapX = false;
  46897. /**
  46898. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46899. */
  46900. _this.invertNormalMapY = false;
  46901. /**
  46902. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46903. */
  46904. _this.twoSidedLighting = false;
  46905. /**
  46906. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46907. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46908. */
  46909. _this.useAlphaFresnel = false;
  46910. /**
  46911. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46912. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46913. */
  46914. _this.useLinearAlphaFresnel = false;
  46915. /**
  46916. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46917. * And/Or occlude the blended part.
  46918. */
  46919. _this.environmentBRDFTexture = null;
  46920. /**
  46921. * Force normal to face away from face.
  46922. */
  46923. _this.forceNormalForward = false;
  46924. /**
  46925. * Enables specular anti aliasing in the PBR shader.
  46926. * It will both interacts on the Geometry for analytical and IBL lighting.
  46927. * It also prefilter the roughness map based on the bump values.
  46928. */
  46929. _this.enableSpecularAntiAliasing = false;
  46930. /**
  46931. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46932. * makes the reflect vector face the model (under horizon).
  46933. */
  46934. _this.useHorizonOcclusion = true;
  46935. /**
  46936. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46937. * too much the area relying on ambient texture to define their ambient occlusion.
  46938. */
  46939. _this.useRadianceOcclusion = true;
  46940. /**
  46941. * If set to true, no lighting calculations will be applied.
  46942. */
  46943. _this.unlit = false;
  46944. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46945. return _this;
  46946. }
  46947. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  46948. /**
  46949. * BJS is using an harcoded light falloff based on a manually sets up range.
  46950. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46951. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46952. */
  46953. get: function () {
  46954. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46955. },
  46956. /**
  46957. * BJS is using an harcoded light falloff based on a manually sets up range.
  46958. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46959. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46960. */
  46961. set: function (value) {
  46962. if (value !== this.usePhysicalLightFalloff) {
  46963. // Ensure the effect will be rebuilt.
  46964. this._markAllSubMeshesAsTexturesDirty();
  46965. if (value) {
  46966. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46967. }
  46968. else {
  46969. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  46970. }
  46971. }
  46972. },
  46973. enumerable: true,
  46974. configurable: true
  46975. });
  46976. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  46977. /**
  46978. * In order to support the falloff compatibility with gltf, a special mode has been added
  46979. * to reproduce the gltf light falloff.
  46980. */
  46981. get: function () {
  46982. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  46983. },
  46984. /**
  46985. * In order to support the falloff compatibility with gltf, a special mode has been added
  46986. * to reproduce the gltf light falloff.
  46987. */
  46988. set: function (value) {
  46989. if (value !== this.useGLTFLightFalloff) {
  46990. // Ensure the effect will be rebuilt.
  46991. this._markAllSubMeshesAsTexturesDirty();
  46992. if (value) {
  46993. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  46994. }
  46995. else {
  46996. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  46997. }
  46998. }
  46999. },
  47000. enumerable: true,
  47001. configurable: true
  47002. });
  47003. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  47004. /**
  47005. * Gets the image processing configuration used either in this material.
  47006. */
  47007. get: function () {
  47008. return this._imageProcessingConfiguration;
  47009. },
  47010. /**
  47011. * Sets the Default image processing configuration used either in the this material.
  47012. *
  47013. * If sets to null, the scene one is in use.
  47014. */
  47015. set: function (value) {
  47016. this._attachImageProcessingConfiguration(value);
  47017. // Ensure the effect will be rebuilt.
  47018. this._markAllSubMeshesAsTexturesDirty();
  47019. },
  47020. enumerable: true,
  47021. configurable: true
  47022. });
  47023. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  47024. /**
  47025. * Gets wether the color curves effect is enabled.
  47026. */
  47027. get: function () {
  47028. return this.imageProcessingConfiguration.colorCurvesEnabled;
  47029. },
  47030. /**
  47031. * Sets wether the color curves effect is enabled.
  47032. */
  47033. set: function (value) {
  47034. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  47035. },
  47036. enumerable: true,
  47037. configurable: true
  47038. });
  47039. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  47040. /**
  47041. * Gets wether the color grading effect is enabled.
  47042. */
  47043. get: function () {
  47044. return this.imageProcessingConfiguration.colorGradingEnabled;
  47045. },
  47046. /**
  47047. * Gets wether the color grading effect is enabled.
  47048. */
  47049. set: function (value) {
  47050. this.imageProcessingConfiguration.colorGradingEnabled = value;
  47051. },
  47052. enumerable: true,
  47053. configurable: true
  47054. });
  47055. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  47056. /**
  47057. * Gets wether tonemapping is enabled or not.
  47058. */
  47059. get: function () {
  47060. return this._imageProcessingConfiguration.toneMappingEnabled;
  47061. },
  47062. /**
  47063. * Sets wether tonemapping is enabled or not
  47064. */
  47065. set: function (value) {
  47066. this._imageProcessingConfiguration.toneMappingEnabled = value;
  47067. },
  47068. enumerable: true,
  47069. configurable: true
  47070. });
  47071. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  47072. /**
  47073. * The camera exposure used on this material.
  47074. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  47075. * This corresponds to a photographic exposure.
  47076. */
  47077. get: function () {
  47078. return this._imageProcessingConfiguration.exposure;
  47079. },
  47080. /**
  47081. * The camera exposure used on this material.
  47082. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  47083. * This corresponds to a photographic exposure.
  47084. */
  47085. set: function (value) {
  47086. this._imageProcessingConfiguration.exposure = value;
  47087. },
  47088. enumerable: true,
  47089. configurable: true
  47090. });
  47091. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  47092. /**
  47093. * Gets The camera contrast used on this material.
  47094. */
  47095. get: function () {
  47096. return this._imageProcessingConfiguration.contrast;
  47097. },
  47098. /**
  47099. * Sets The camera contrast used on this material.
  47100. */
  47101. set: function (value) {
  47102. this._imageProcessingConfiguration.contrast = value;
  47103. },
  47104. enumerable: true,
  47105. configurable: true
  47106. });
  47107. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  47108. /**
  47109. * Gets the Color Grading 2D Lookup Texture.
  47110. */
  47111. get: function () {
  47112. return this._imageProcessingConfiguration.colorGradingTexture;
  47113. },
  47114. /**
  47115. * Sets the Color Grading 2D Lookup Texture.
  47116. */
  47117. set: function (value) {
  47118. this._imageProcessingConfiguration.colorGradingTexture = value;
  47119. },
  47120. enumerable: true,
  47121. configurable: true
  47122. });
  47123. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  47124. /**
  47125. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  47126. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  47127. * 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;
  47128. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  47129. */
  47130. get: function () {
  47131. return this._imageProcessingConfiguration.colorCurves;
  47132. },
  47133. /**
  47134. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  47135. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  47136. * 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;
  47137. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  47138. */
  47139. set: function (value) {
  47140. this._imageProcessingConfiguration.colorCurves = value;
  47141. },
  47142. enumerable: true,
  47143. configurable: true
  47144. });
  47145. /**
  47146. * Returns the name of this material class.
  47147. */
  47148. PBRMaterial.prototype.getClassName = function () {
  47149. return "PBRMaterial";
  47150. };
  47151. /**
  47152. * Returns an array of the actively used textures.
  47153. * @returns - Array of BaseTextures
  47154. */
  47155. PBRMaterial.prototype.getActiveTextures = function () {
  47156. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47157. if (this._albedoTexture) {
  47158. activeTextures.push(this._albedoTexture);
  47159. }
  47160. if (this._ambientTexture) {
  47161. activeTextures.push(this._ambientTexture);
  47162. }
  47163. if (this._opacityTexture) {
  47164. activeTextures.push(this._opacityTexture);
  47165. }
  47166. if (this._reflectionTexture) {
  47167. activeTextures.push(this._reflectionTexture);
  47168. }
  47169. if (this._emissiveTexture) {
  47170. activeTextures.push(this._emissiveTexture);
  47171. }
  47172. if (this._reflectivityTexture) {
  47173. activeTextures.push(this._reflectivityTexture);
  47174. }
  47175. if (this._metallicTexture) {
  47176. activeTextures.push(this._metallicTexture);
  47177. }
  47178. if (this._microSurfaceTexture) {
  47179. activeTextures.push(this._microSurfaceTexture);
  47180. }
  47181. if (this._bumpTexture) {
  47182. activeTextures.push(this._bumpTexture);
  47183. }
  47184. if (this._lightmapTexture) {
  47185. activeTextures.push(this._lightmapTexture);
  47186. }
  47187. if (this._refractionTexture) {
  47188. activeTextures.push(this._refractionTexture);
  47189. }
  47190. return activeTextures;
  47191. };
  47192. /**
  47193. * Checks to see if a texture is used in the material.
  47194. * @param texture - Base texture to use.
  47195. * @returns - Boolean specifying if a texture is used in the material.
  47196. */
  47197. PBRMaterial.prototype.hasTexture = function (texture) {
  47198. if (_super.prototype.hasTexture.call(this, texture)) {
  47199. return true;
  47200. }
  47201. if (this._albedoTexture === texture) {
  47202. return true;
  47203. }
  47204. if (this._ambientTexture === texture) {
  47205. return true;
  47206. }
  47207. if (this._opacityTexture === texture) {
  47208. return true;
  47209. }
  47210. if (this._reflectionTexture === texture) {
  47211. return true;
  47212. }
  47213. if (this._reflectivityTexture === texture) {
  47214. return true;
  47215. }
  47216. if (this._metallicTexture === texture) {
  47217. return true;
  47218. }
  47219. if (this._microSurfaceTexture === texture) {
  47220. return true;
  47221. }
  47222. if (this._bumpTexture === texture) {
  47223. return true;
  47224. }
  47225. if (this._lightmapTexture === texture) {
  47226. return true;
  47227. }
  47228. if (this._refractionTexture === texture) {
  47229. return true;
  47230. }
  47231. return false;
  47232. };
  47233. /**
  47234. * Makes a duplicate of the current material.
  47235. * @param name - name to use for the new material.
  47236. */
  47237. PBRMaterial.prototype.clone = function (name) {
  47238. var _this = this;
  47239. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  47240. clone.id = name;
  47241. clone.name = name;
  47242. return clone;
  47243. };
  47244. /**
  47245. * Serializes this PBR Material.
  47246. * @returns - An object with the serialized material.
  47247. */
  47248. PBRMaterial.prototype.serialize = function () {
  47249. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47250. serializationObject.customType = "BABYLON.PBRMaterial";
  47251. return serializationObject;
  47252. };
  47253. // Statics
  47254. /**
  47255. * Parses a PBR Material from a serialized object.
  47256. * @param source - Serialized object.
  47257. * @param scene - BJS scene instance.
  47258. * @param rootUrl - url for the scene object
  47259. * @returns - PBRMaterial
  47260. */
  47261. PBRMaterial.Parse = function (source, scene, rootUrl) {
  47262. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  47263. };
  47264. /**
  47265. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  47266. */
  47267. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  47268. /**
  47269. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  47270. */
  47271. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  47272. /**
  47273. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47274. */
  47275. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  47276. /**
  47277. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47278. * They are also discarded below the alpha cutoff threshold to improve performances.
  47279. */
  47280. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  47281. /**
  47282. * Defines the default value of how much AO map is occluding the analytical lights
  47283. * (point spot...).
  47284. */
  47285. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  47286. __decorate([
  47287. BABYLON.serialize(),
  47288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47289. ], PBRMaterial.prototype, "directIntensity", void 0);
  47290. __decorate([
  47291. BABYLON.serialize(),
  47292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47293. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  47294. __decorate([
  47295. BABYLON.serialize(),
  47296. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47297. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  47298. __decorate([
  47299. BABYLON.serialize(),
  47300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47301. ], PBRMaterial.prototype, "specularIntensity", void 0);
  47302. __decorate([
  47303. BABYLON.serialize(),
  47304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47305. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  47306. __decorate([
  47307. BABYLON.serializeAsTexture(),
  47308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47309. ], PBRMaterial.prototype, "albedoTexture", void 0);
  47310. __decorate([
  47311. BABYLON.serializeAsTexture(),
  47312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47313. ], PBRMaterial.prototype, "ambientTexture", void 0);
  47314. __decorate([
  47315. BABYLON.serialize(),
  47316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47317. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  47318. __decorate([
  47319. BABYLON.serialize(),
  47320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47321. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  47322. __decorate([
  47323. BABYLON.serializeAsTexture(),
  47324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47325. ], PBRMaterial.prototype, "opacityTexture", void 0);
  47326. __decorate([
  47327. BABYLON.serializeAsTexture(),
  47328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47329. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  47330. __decorate([
  47331. BABYLON.serializeAsTexture(),
  47332. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47333. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  47334. __decorate([
  47335. BABYLON.serializeAsTexture(),
  47336. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47337. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  47338. __decorate([
  47339. BABYLON.serializeAsTexture(),
  47340. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47341. ], PBRMaterial.prototype, "metallicTexture", void 0);
  47342. __decorate([
  47343. BABYLON.serialize(),
  47344. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47345. ], PBRMaterial.prototype, "metallic", void 0);
  47346. __decorate([
  47347. BABYLON.serialize(),
  47348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47349. ], PBRMaterial.prototype, "roughness", void 0);
  47350. __decorate([
  47351. BABYLON.serializeAsTexture(),
  47352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47353. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  47354. __decorate([
  47355. BABYLON.serializeAsTexture(),
  47356. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47357. ], PBRMaterial.prototype, "bumpTexture", void 0);
  47358. __decorate([
  47359. BABYLON.serializeAsTexture(),
  47360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  47361. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  47362. __decorate([
  47363. BABYLON.serializeAsTexture(),
  47364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47365. ], PBRMaterial.prototype, "refractionTexture", void 0);
  47366. __decorate([
  47367. BABYLON.serializeAsColor3("ambient"),
  47368. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47369. ], PBRMaterial.prototype, "ambientColor", void 0);
  47370. __decorate([
  47371. BABYLON.serializeAsColor3("albedo"),
  47372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47373. ], PBRMaterial.prototype, "albedoColor", void 0);
  47374. __decorate([
  47375. BABYLON.serializeAsColor3("reflectivity"),
  47376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47377. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  47378. __decorate([
  47379. BABYLON.serializeAsColor3("reflection"),
  47380. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47381. ], PBRMaterial.prototype, "reflectionColor", void 0);
  47382. __decorate([
  47383. BABYLON.serializeAsColor3("emissive"),
  47384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47385. ], PBRMaterial.prototype, "emissiveColor", void 0);
  47386. __decorate([
  47387. BABYLON.serialize(),
  47388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47389. ], PBRMaterial.prototype, "microSurface", void 0);
  47390. __decorate([
  47391. BABYLON.serialize(),
  47392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47393. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  47394. __decorate([
  47395. BABYLON.serialize(),
  47396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47397. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  47398. __decorate([
  47399. BABYLON.serialize(),
  47400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47401. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  47402. __decorate([
  47403. BABYLON.serialize(),
  47404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47405. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  47406. __decorate([
  47407. BABYLON.serialize(),
  47408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47409. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  47410. __decorate([
  47411. BABYLON.serialize(),
  47412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47413. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  47414. __decorate([
  47415. BABYLON.serialize(),
  47416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47417. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  47418. __decorate([
  47419. BABYLON.serialize(),
  47420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47421. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  47422. __decorate([
  47423. BABYLON.serialize(),
  47424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47425. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  47426. __decorate([
  47427. BABYLON.serialize(),
  47428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47429. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  47430. __decorate([
  47431. BABYLON.serialize(),
  47432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47433. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  47434. __decorate([
  47435. BABYLON.serialize(),
  47436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47437. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  47438. __decorate([
  47439. BABYLON.serialize(),
  47440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47441. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  47442. __decorate([
  47443. BABYLON.serialize(),
  47444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47445. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  47446. __decorate([
  47447. BABYLON.serialize(),
  47448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47449. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  47450. __decorate([
  47451. BABYLON.serialize()
  47452. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  47453. __decorate([
  47454. BABYLON.serialize()
  47455. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  47456. __decorate([
  47457. BABYLON.serialize(),
  47458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47459. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  47460. __decorate([
  47461. BABYLON.serialize(),
  47462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47463. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  47464. __decorate([
  47465. BABYLON.serialize(),
  47466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47467. ], PBRMaterial.prototype, "useParallax", void 0);
  47468. __decorate([
  47469. BABYLON.serialize(),
  47470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47471. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  47472. __decorate([
  47473. BABYLON.serialize(),
  47474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47475. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  47476. __decorate([
  47477. BABYLON.serialize(),
  47478. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47479. ], PBRMaterial.prototype, "disableLighting", void 0);
  47480. __decorate([
  47481. BABYLON.serialize(),
  47482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47483. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  47484. __decorate([
  47485. BABYLON.serialize(),
  47486. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47487. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  47488. __decorate([
  47489. BABYLON.serialize(),
  47490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47491. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  47492. __decorate([
  47493. BABYLON.serialize(),
  47494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47495. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  47496. __decorate([
  47497. BABYLON.serialize(),
  47498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47499. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  47500. __decorate([
  47501. BABYLON.serialize(),
  47502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47503. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  47504. __decorate([
  47505. BABYLON.serialize(),
  47506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47507. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  47508. __decorate([
  47509. BABYLON.serializeAsTexture(),
  47510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47511. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  47512. __decorate([
  47513. BABYLON.serialize(),
  47514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47515. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  47516. __decorate([
  47517. BABYLON.serialize(),
  47518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47519. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  47520. __decorate([
  47521. BABYLON.serialize(),
  47522. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47523. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  47524. __decorate([
  47525. BABYLON.serialize(),
  47526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47527. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  47528. __decorate([
  47529. BABYLON.serialize(),
  47530. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  47531. ], PBRMaterial.prototype, "unlit", void 0);
  47532. return PBRMaterial;
  47533. }(BABYLON.PBRBaseMaterial));
  47534. BABYLON.PBRMaterial = PBRMaterial;
  47535. })(BABYLON || (BABYLON = {}));
  47536. //# sourceMappingURL=babylon.pbrMaterial.js.map
  47537. var BABYLON;
  47538. (function (BABYLON) {
  47539. /**
  47540. * The PBR material of BJS following the metal roughness convention.
  47541. *
  47542. * This fits to the PBR convention in the GLTF definition:
  47543. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  47544. */
  47545. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  47546. __extends(PBRMetallicRoughnessMaterial, _super);
  47547. /**
  47548. * Instantiates a new PBRMetalRoughnessMaterial instance.
  47549. *
  47550. * @param name The material name
  47551. * @param scene The scene the material will be use in.
  47552. */
  47553. function PBRMetallicRoughnessMaterial(name, scene) {
  47554. var _this = _super.call(this, name, scene) || this;
  47555. _this._useRoughnessFromMetallicTextureAlpha = false;
  47556. _this._useRoughnessFromMetallicTextureGreen = true;
  47557. _this._useMetallnessFromMetallicTextureBlue = true;
  47558. _this.metallic = 1.0;
  47559. _this.roughness = 1.0;
  47560. return _this;
  47561. }
  47562. /**
  47563. * Return the currrent class name of the material.
  47564. */
  47565. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  47566. return "PBRMetallicRoughnessMaterial";
  47567. };
  47568. /**
  47569. * Return the active textures of the material.
  47570. */
  47571. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  47572. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47573. if (this.baseTexture) {
  47574. activeTextures.push(this.baseTexture);
  47575. }
  47576. if (this.metallicRoughnessTexture) {
  47577. activeTextures.push(this.metallicRoughnessTexture);
  47578. }
  47579. return activeTextures;
  47580. };
  47581. /**
  47582. * Checks to see if a texture is used in the material.
  47583. * @param texture - Base texture to use.
  47584. * @returns - Boolean specifying if a texture is used in the material.
  47585. */
  47586. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  47587. if (_super.prototype.hasTexture.call(this, texture)) {
  47588. return true;
  47589. }
  47590. if (this.baseTexture === texture) {
  47591. return true;
  47592. }
  47593. if (this.metallicRoughnessTexture === texture) {
  47594. return true;
  47595. }
  47596. return false;
  47597. };
  47598. /**
  47599. * Makes a duplicate of the current material.
  47600. * @param name - name to use for the new material.
  47601. */
  47602. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  47603. var _this = this;
  47604. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  47605. clone.id = name;
  47606. clone.name = name;
  47607. return clone;
  47608. };
  47609. /**
  47610. * Serialize the material to a parsable JSON object.
  47611. */
  47612. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  47613. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47614. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  47615. return serializationObject;
  47616. };
  47617. /**
  47618. * Parses a JSON object correponding to the serialize function.
  47619. */
  47620. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  47621. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  47622. };
  47623. __decorate([
  47624. BABYLON.serializeAsColor3(),
  47625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47626. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  47627. __decorate([
  47628. BABYLON.serializeAsTexture(),
  47629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47630. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  47631. __decorate([
  47632. BABYLON.serialize(),
  47633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47634. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  47635. __decorate([
  47636. BABYLON.serialize(),
  47637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47638. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  47639. __decorate([
  47640. BABYLON.serializeAsTexture(),
  47641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  47642. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  47643. return PBRMetallicRoughnessMaterial;
  47644. }(BABYLON.PBRBaseSimpleMaterial));
  47645. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  47646. })(BABYLON || (BABYLON = {}));
  47647. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  47648. var BABYLON;
  47649. (function (BABYLON) {
  47650. /**
  47651. * The PBR material of BJS following the specular glossiness convention.
  47652. *
  47653. * This fits to the PBR convention in the GLTF definition:
  47654. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  47655. */
  47656. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  47657. __extends(PBRSpecularGlossinessMaterial, _super);
  47658. /**
  47659. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  47660. *
  47661. * @param name The material name
  47662. * @param scene The scene the material will be use in.
  47663. */
  47664. function PBRSpecularGlossinessMaterial(name, scene) {
  47665. var _this = _super.call(this, name, scene) || this;
  47666. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  47667. return _this;
  47668. }
  47669. /**
  47670. * Return the currrent class name of the material.
  47671. */
  47672. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  47673. return "PBRSpecularGlossinessMaterial";
  47674. };
  47675. /**
  47676. * Return the active textures of the material.
  47677. */
  47678. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  47679. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47680. if (this.diffuseTexture) {
  47681. activeTextures.push(this.diffuseTexture);
  47682. }
  47683. if (this.specularGlossinessTexture) {
  47684. activeTextures.push(this.specularGlossinessTexture);
  47685. }
  47686. return activeTextures;
  47687. };
  47688. /**
  47689. * Checks to see if a texture is used in the material.
  47690. * @param texture - Base texture to use.
  47691. * @returns - Boolean specifying if a texture is used in the material.
  47692. */
  47693. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  47694. if (_super.prototype.hasTexture.call(this, texture)) {
  47695. return true;
  47696. }
  47697. if (this.diffuseTexture === texture) {
  47698. return true;
  47699. }
  47700. if (this.specularGlossinessTexture === texture) {
  47701. return true;
  47702. }
  47703. return false;
  47704. };
  47705. /**
  47706. * Makes a duplicate of the current material.
  47707. * @param name - name to use for the new material.
  47708. */
  47709. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  47710. var _this = this;
  47711. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  47712. clone.id = name;
  47713. clone.name = name;
  47714. return clone;
  47715. };
  47716. /**
  47717. * Serialize the material to a parsable JSON object.
  47718. */
  47719. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47720. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47721. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47722. return serializationObject;
  47723. };
  47724. /**
  47725. * Parses a JSON object correponding to the serialize function.
  47726. */
  47727. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  47728. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  47729. };
  47730. __decorate([
  47731. BABYLON.serializeAsColor3("diffuse"),
  47732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47733. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  47734. __decorate([
  47735. BABYLON.serializeAsTexture(),
  47736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47737. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  47738. __decorate([
  47739. BABYLON.serializeAsColor3("specular"),
  47740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  47741. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  47742. __decorate([
  47743. BABYLON.serialize(),
  47744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  47745. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  47746. __decorate([
  47747. BABYLON.serializeAsTexture(),
  47748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  47749. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  47750. return PBRSpecularGlossinessMaterial;
  47751. }(BABYLON.PBRBaseSimpleMaterial));
  47752. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  47753. })(BABYLON || (BABYLON = {}));
  47754. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  47755. var BABYLON;
  47756. (function (BABYLON) {
  47757. /**
  47758. * @ignore
  47759. * This is a list of all the different input types that are available in the application.
  47760. * Fo instance: ArcRotateCameraGamepadInput...
  47761. */
  47762. BABYLON.CameraInputTypes = {};
  47763. /**
  47764. * This represents the input manager used within a camera.
  47765. * It helps dealing with all the different kind of input attached to a camera.
  47766. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47767. */
  47768. var CameraInputsManager = /** @class */ (function () {
  47769. /**
  47770. * Instantiate a new Camera Input Manager.
  47771. * @param camera Defines the camera the input manager blongs to
  47772. */
  47773. function CameraInputsManager(camera) {
  47774. this.attached = {};
  47775. this.camera = camera;
  47776. this.checkInputs = function () { };
  47777. }
  47778. /**
  47779. * Add an input method to a camera
  47780. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47781. * @param input camera input method
  47782. */
  47783. CameraInputsManager.prototype.add = function (input) {
  47784. var type = input.getSimpleName();
  47785. if (this.attached[type]) {
  47786. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47787. return;
  47788. }
  47789. this.attached[type] = input;
  47790. input.camera = this.camera;
  47791. //for checkInputs, we are dynamically creating a function
  47792. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47793. if (input.checkInputs) {
  47794. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47795. }
  47796. if (this.attachedElement) {
  47797. input.attachControl(this.attachedElement);
  47798. }
  47799. };
  47800. /**
  47801. * Remove a specific input method from a camera
  47802. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47803. * @param inputToRemove camera input method
  47804. */
  47805. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47806. for (var cam in this.attached) {
  47807. var input = this.attached[cam];
  47808. if (input === inputToRemove) {
  47809. input.detachControl(this.attachedElement);
  47810. input.camera = null;
  47811. delete this.attached[cam];
  47812. this.rebuildInputCheck();
  47813. }
  47814. }
  47815. };
  47816. /**
  47817. * Remove a specific input type from a camera
  47818. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  47819. * @param inputType the type of the input to remove
  47820. */
  47821. CameraInputsManager.prototype.removeByType = function (inputType) {
  47822. for (var cam in this.attached) {
  47823. var input = this.attached[cam];
  47824. if (input.getClassName() === inputType) {
  47825. input.detachControl(this.attachedElement);
  47826. input.camera = null;
  47827. delete this.attached[cam];
  47828. this.rebuildInputCheck();
  47829. }
  47830. }
  47831. };
  47832. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47833. var current = this.checkInputs;
  47834. return function () {
  47835. current();
  47836. fn();
  47837. };
  47838. };
  47839. /**
  47840. * Attach the input controls to the currently attached dom element to listen the events from.
  47841. * @param input Defines the input to attach
  47842. */
  47843. CameraInputsManager.prototype.attachInput = function (input) {
  47844. if (this.attachedElement) {
  47845. input.attachControl(this.attachedElement, this.noPreventDefault);
  47846. }
  47847. };
  47848. /**
  47849. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  47850. * @param element Defines the dom element to collect the events from
  47851. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47852. */
  47853. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47854. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47855. if (this.attachedElement) {
  47856. return;
  47857. }
  47858. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47859. this.attachedElement = element;
  47860. this.noPreventDefault = noPreventDefault;
  47861. for (var cam in this.attached) {
  47862. this.attached[cam].attachControl(element, noPreventDefault);
  47863. }
  47864. };
  47865. /**
  47866. * Detach the current manager inputs controls from a specific dom element.
  47867. * @param element Defines the dom element to collect the events from
  47868. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  47869. */
  47870. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47871. if (disconnect === void 0) { disconnect = false; }
  47872. if (this.attachedElement !== element) {
  47873. return;
  47874. }
  47875. for (var cam in this.attached) {
  47876. this.attached[cam].detachControl(element);
  47877. if (disconnect) {
  47878. this.attached[cam].camera = null;
  47879. }
  47880. }
  47881. this.attachedElement = null;
  47882. };
  47883. /**
  47884. * Rebuild the dynamic inputCheck function from the current list of
  47885. * defined inputs in the manager.
  47886. */
  47887. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47888. this.checkInputs = function () { };
  47889. for (var cam in this.attached) {
  47890. var input = this.attached[cam];
  47891. if (input.checkInputs) {
  47892. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47893. }
  47894. }
  47895. };
  47896. /**
  47897. * Remove all attached input methods from a camera
  47898. */
  47899. CameraInputsManager.prototype.clear = function () {
  47900. if (this.attachedElement) {
  47901. this.detachElement(this.attachedElement, true);
  47902. }
  47903. this.attached = {};
  47904. this.attachedElement = null;
  47905. this.checkInputs = function () { };
  47906. };
  47907. /**
  47908. * Serialize the current input manager attached to a camera.
  47909. * This ensures than once parsed,
  47910. * the input associated to the camera will be identical to the current ones
  47911. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  47912. */
  47913. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47914. var inputs = {};
  47915. for (var cam in this.attached) {
  47916. var input = this.attached[cam];
  47917. var res = BABYLON.SerializationHelper.Serialize(input);
  47918. inputs[input.getClassName()] = res;
  47919. }
  47920. serializedCamera.inputsmgr = inputs;
  47921. };
  47922. /**
  47923. * Parses an input manager serialized JSON to restore the previous list of inputs
  47924. * and states associated to a camera.
  47925. * @param parsedCamera Defines the JSON to parse
  47926. */
  47927. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47928. var parsedInputs = parsedCamera.inputsmgr;
  47929. if (parsedInputs) {
  47930. this.clear();
  47931. for (var n in parsedInputs) {
  47932. var construct = BABYLON.CameraInputTypes[n];
  47933. if (construct) {
  47934. var parsedinput = parsedInputs[n];
  47935. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47936. this.add(input);
  47937. }
  47938. }
  47939. }
  47940. else {
  47941. //2016-03-08 this part is for managing backward compatibility
  47942. for (var n in this.attached) {
  47943. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47944. if (construct) {
  47945. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47946. this.remove(this.attached[n]);
  47947. this.add(input);
  47948. }
  47949. }
  47950. }
  47951. };
  47952. return CameraInputsManager;
  47953. }());
  47954. BABYLON.CameraInputsManager = CameraInputsManager;
  47955. })(BABYLON || (BABYLON = {}));
  47956. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47957. var BABYLON;
  47958. (function (BABYLON) {
  47959. /**
  47960. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  47961. * This is the base of the follow, arc rotate cameras and Free camera
  47962. * @see http://doc.babylonjs.com/features/cameras
  47963. */
  47964. var TargetCamera = /** @class */ (function (_super) {
  47965. __extends(TargetCamera, _super);
  47966. /**
  47967. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  47968. * This is the base of the follow, arc rotate cameras and Free camera
  47969. * @see http://doc.babylonjs.com/features/cameras
  47970. * @param name Defines the name of the camera in the scene
  47971. * @param position Defines the start position of the camera in the scene
  47972. * @param scene Defines the scene the camera belongs to
  47973. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47974. */
  47975. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47976. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47977. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47978. /**
  47979. * Define the current direction the camera is moving to
  47980. */
  47981. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47982. /**
  47983. * Define the current rotation the camera is rotating to
  47984. */
  47985. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47986. /**
  47987. * Define the current rotation of the camera
  47988. */
  47989. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47990. /**
  47991. * Define the current speed of the camera
  47992. */
  47993. _this.speed = 2.0;
  47994. /**
  47995. * Add cconstraint to the camera to prevent it to move freely in all directions and
  47996. * around all axis.
  47997. */
  47998. _this.noRotationConstraint = false;
  47999. /**
  48000. * Define the current target of the camera as an object or a position.
  48001. */
  48002. _this.lockedTarget = null;
  48003. /** @hidden */
  48004. _this._currentTarget = BABYLON.Vector3.Zero();
  48005. /** @hidden */
  48006. _this._viewMatrix = BABYLON.Matrix.Zero();
  48007. /** @hidden */
  48008. _this._camMatrix = BABYLON.Matrix.Zero();
  48009. /** @hidden */
  48010. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  48011. /** @hidden */
  48012. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  48013. /** @hidden */
  48014. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  48015. /** @hidden */
  48016. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  48017. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  48018. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  48019. _this._defaultUp = BABYLON.Vector3.Up();
  48020. _this._cachedRotationZ = 0;
  48021. _this._cachedQuaternionRotationZ = 0;
  48022. return _this;
  48023. }
  48024. /**
  48025. * Gets the position in front of the camera at a given distance.
  48026. * @param distance The distance from the camera we want the position to be
  48027. * @returns the position
  48028. */
  48029. TargetCamera.prototype.getFrontPosition = function (distance) {
  48030. this.getWorldMatrix();
  48031. var direction = this.getTarget().subtract(this.position);
  48032. direction.normalize();
  48033. direction.scaleInPlace(distance);
  48034. return this.globalPosition.add(direction);
  48035. };
  48036. /** @hidden */
  48037. TargetCamera.prototype._getLockedTargetPosition = function () {
  48038. if (!this.lockedTarget) {
  48039. return null;
  48040. }
  48041. if (this.lockedTarget.absolutePosition) {
  48042. this.lockedTarget.computeWorldMatrix();
  48043. }
  48044. return this.lockedTarget.absolutePosition || this.lockedTarget;
  48045. };
  48046. /**
  48047. * Store current camera state of the camera (fov, position, rotation, etc..)
  48048. * @returns the camera
  48049. */
  48050. TargetCamera.prototype.storeState = function () {
  48051. this._storedPosition = this.position.clone();
  48052. this._storedRotation = this.rotation.clone();
  48053. if (this.rotationQuaternion) {
  48054. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  48055. }
  48056. return _super.prototype.storeState.call(this);
  48057. };
  48058. /**
  48059. * Restored camera state. You must call storeState() first
  48060. * @returns whether it was successful or not
  48061. * @hidden
  48062. */
  48063. TargetCamera.prototype._restoreStateValues = function () {
  48064. if (!_super.prototype._restoreStateValues.call(this)) {
  48065. return false;
  48066. }
  48067. this.position = this._storedPosition.clone();
  48068. this.rotation = this._storedRotation.clone();
  48069. if (this.rotationQuaternion) {
  48070. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  48071. }
  48072. this.cameraDirection.copyFromFloats(0, 0, 0);
  48073. this.cameraRotation.copyFromFloats(0, 0);
  48074. return true;
  48075. };
  48076. /** @hidden */
  48077. TargetCamera.prototype._initCache = function () {
  48078. _super.prototype._initCache.call(this);
  48079. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48080. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48081. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48082. };
  48083. /** @hidden */
  48084. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  48085. if (!ignoreParentClass) {
  48086. _super.prototype._updateCache.call(this);
  48087. }
  48088. var lockedTargetPosition = this._getLockedTargetPosition();
  48089. if (!lockedTargetPosition) {
  48090. this._cache.lockedTarget = null;
  48091. }
  48092. else {
  48093. if (!this._cache.lockedTarget) {
  48094. this._cache.lockedTarget = lockedTargetPosition.clone();
  48095. }
  48096. else {
  48097. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  48098. }
  48099. }
  48100. this._cache.rotation.copyFrom(this.rotation);
  48101. if (this.rotationQuaternion) {
  48102. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48103. }
  48104. };
  48105. // Synchronized
  48106. /** @hidden */
  48107. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  48108. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  48109. return false;
  48110. }
  48111. var lockedTargetPosition = this._getLockedTargetPosition();
  48112. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  48113. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  48114. };
  48115. // Methods
  48116. /** @hidden */
  48117. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  48118. var engine = this.getEngine();
  48119. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  48120. };
  48121. // Target
  48122. /** @hidden */
  48123. TargetCamera.prototype.setTarget = function (target) {
  48124. this.upVector.normalize();
  48125. if (this.position.z === target.z) {
  48126. this.position.z += BABYLON.Epsilon;
  48127. }
  48128. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  48129. this._camMatrix.invert();
  48130. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  48131. var vDir = target.subtract(this.position);
  48132. if (vDir.x >= 0.0) {
  48133. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  48134. }
  48135. else {
  48136. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  48137. }
  48138. this.rotation.z = 0;
  48139. if (isNaN(this.rotation.x)) {
  48140. this.rotation.x = 0;
  48141. }
  48142. if (isNaN(this.rotation.y)) {
  48143. this.rotation.y = 0;
  48144. }
  48145. if (isNaN(this.rotation.z)) {
  48146. this.rotation.z = 0;
  48147. }
  48148. if (this.rotationQuaternion) {
  48149. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  48150. }
  48151. };
  48152. /**
  48153. * Return the current target position of the camera. This value is expressed in local space.
  48154. * @returns the target position
  48155. */
  48156. TargetCamera.prototype.getTarget = function () {
  48157. return this._currentTarget;
  48158. };
  48159. /** @hidden */
  48160. TargetCamera.prototype._decideIfNeedsToMove = function () {
  48161. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48162. };
  48163. /** @hidden */
  48164. TargetCamera.prototype._updatePosition = function () {
  48165. if (this.parent) {
  48166. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  48167. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  48168. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  48169. return;
  48170. }
  48171. this.position.addInPlace(this.cameraDirection);
  48172. };
  48173. /** @hidden */
  48174. TargetCamera.prototype._checkInputs = function () {
  48175. var needToMove = this._decideIfNeedsToMove();
  48176. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  48177. // Move
  48178. if (needToMove) {
  48179. this._updatePosition();
  48180. }
  48181. // Rotate
  48182. if (needToRotate) {
  48183. this.rotation.x += this.cameraRotation.x;
  48184. this.rotation.y += this.cameraRotation.y;
  48185. //rotate, if quaternion is set and rotation was used
  48186. if (this.rotationQuaternion) {
  48187. var len = this.rotation.lengthSquared();
  48188. if (len) {
  48189. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  48190. }
  48191. }
  48192. if (!this.noRotationConstraint) {
  48193. var limit = (Math.PI / 2) * 0.95;
  48194. if (this.rotation.x > limit) {
  48195. this.rotation.x = limit;
  48196. }
  48197. if (this.rotation.x < -limit) {
  48198. this.rotation.x = -limit;
  48199. }
  48200. }
  48201. }
  48202. // Inertia
  48203. if (needToMove) {
  48204. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  48205. this.cameraDirection.x = 0;
  48206. }
  48207. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  48208. this.cameraDirection.y = 0;
  48209. }
  48210. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  48211. this.cameraDirection.z = 0;
  48212. }
  48213. this.cameraDirection.scaleInPlace(this.inertia);
  48214. }
  48215. if (needToRotate) {
  48216. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  48217. this.cameraRotation.x = 0;
  48218. }
  48219. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  48220. this.cameraRotation.y = 0;
  48221. }
  48222. this.cameraRotation.scaleInPlace(this.inertia);
  48223. }
  48224. _super.prototype._checkInputs.call(this);
  48225. };
  48226. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  48227. if (this.rotationQuaternion) {
  48228. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  48229. }
  48230. else {
  48231. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  48232. }
  48233. };
  48234. /**
  48235. * 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)
  48236. * @returns the current camera
  48237. */
  48238. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  48239. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  48240. return this;
  48241. };
  48242. /** @hidden */
  48243. TargetCamera.prototype._getViewMatrix = function () {
  48244. if (this.lockedTarget) {
  48245. this.setTarget(this._getLockedTargetPosition());
  48246. }
  48247. // Compute
  48248. this._updateCameraRotationMatrix();
  48249. // Apply the changed rotation to the upVector
  48250. if (this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z) {
  48251. this._rotateUpVectorWithCameraRotationMatrix();
  48252. this._cachedQuaternionRotationZ = this.rotationQuaternion.z;
  48253. }
  48254. else if (this._cachedRotationZ != this.rotation.z) {
  48255. this._rotateUpVectorWithCameraRotationMatrix();
  48256. this._cachedRotationZ = this.rotation.z;
  48257. }
  48258. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  48259. // Computing target and final matrix
  48260. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  48261. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  48262. return this._viewMatrix;
  48263. };
  48264. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  48265. if (this.parent) {
  48266. var parentWorldMatrix = this.parent.getWorldMatrix();
  48267. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  48268. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  48269. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  48270. this._markSyncedWithParent();
  48271. }
  48272. else {
  48273. this._globalPosition.copyFrom(position);
  48274. this._globalCurrentTarget.copyFrom(target);
  48275. this._globalCurrentUpVector.copyFrom(up);
  48276. }
  48277. if (this.getScene().useRightHandedSystem) {
  48278. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  48279. }
  48280. else {
  48281. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  48282. }
  48283. };
  48284. /**
  48285. * @hidden
  48286. */
  48287. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48288. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  48289. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  48290. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  48291. if (!this.rotationQuaternion) {
  48292. this.rotationQuaternion = new BABYLON.Quaternion();
  48293. }
  48294. rigCamera._cameraRigParams = {};
  48295. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  48296. }
  48297. return rigCamera;
  48298. }
  48299. return null;
  48300. };
  48301. /**
  48302. * @hidden
  48303. */
  48304. TargetCamera.prototype._updateRigCameras = function () {
  48305. var camLeft = this._rigCameras[0];
  48306. var camRight = this._rigCameras[1];
  48307. switch (this.cameraRigMode) {
  48308. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48309. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48310. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48311. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48312. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  48313. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  48314. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  48315. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  48316. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  48317. camLeft.setTarget(this.getTarget());
  48318. camRight.setTarget(this.getTarget());
  48319. break;
  48320. case BABYLON.Camera.RIG_MODE_VR:
  48321. if (camLeft.rotationQuaternion) {
  48322. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48323. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48324. }
  48325. else {
  48326. camLeft.rotation.copyFrom(this.rotation);
  48327. camRight.rotation.copyFrom(this.rotation);
  48328. }
  48329. camLeft.position.copyFrom(this.position);
  48330. camRight.position.copyFrom(this.position);
  48331. break;
  48332. }
  48333. _super.prototype._updateRigCameras.call(this);
  48334. };
  48335. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  48336. if (!this._rigCamTransformMatrix) {
  48337. this._rigCamTransformMatrix = new BABYLON.Matrix();
  48338. }
  48339. var target = this.getTarget();
  48340. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  48341. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  48342. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  48343. };
  48344. /**
  48345. * Gets the current object class name.
  48346. * @return the class name
  48347. */
  48348. TargetCamera.prototype.getClassName = function () {
  48349. return "TargetCamera";
  48350. };
  48351. __decorate([
  48352. BABYLON.serializeAsVector3()
  48353. ], TargetCamera.prototype, "rotation", void 0);
  48354. __decorate([
  48355. BABYLON.serialize()
  48356. ], TargetCamera.prototype, "speed", void 0);
  48357. __decorate([
  48358. BABYLON.serializeAsMeshReference("lockedTargetId")
  48359. ], TargetCamera.prototype, "lockedTarget", void 0);
  48360. return TargetCamera;
  48361. }(BABYLON.Camera));
  48362. BABYLON.TargetCamera = TargetCamera;
  48363. })(BABYLON || (BABYLON = {}));
  48364. //# sourceMappingURL=babylon.targetCamera.js.map
  48365. var BABYLON;
  48366. (function (BABYLON) {
  48367. /**
  48368. * Manage the mouse inputs to control the movement of a free camera.
  48369. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48370. */
  48371. var FreeCameraMouseInput = /** @class */ (function () {
  48372. /**
  48373. * Manage the mouse inputs to control the movement of a free camera.
  48374. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48375. * @param touchEnabled Defines if touch is enabled or not
  48376. */
  48377. function FreeCameraMouseInput(
  48378. /**
  48379. * Define if touch is enabled in the mouse input
  48380. */
  48381. touchEnabled) {
  48382. if (touchEnabled === void 0) { touchEnabled = true; }
  48383. this.touchEnabled = touchEnabled;
  48384. /**
  48385. * Defines the buttons associated with the input to handle camera move.
  48386. */
  48387. this.buttons = [0, 1, 2];
  48388. /**
  48389. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  48390. */
  48391. this.angularSensibility = 2000.0;
  48392. this.previousPosition = null;
  48393. }
  48394. /**
  48395. * Attach the input controls to a specific dom element to get the input from.
  48396. * @param element Defines the element the controls should be listened from
  48397. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48398. */
  48399. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  48400. var _this = this;
  48401. var engine = this.camera.getEngine();
  48402. if (!this._pointerInput) {
  48403. this._pointerInput = function (p, s) {
  48404. var evt = p.event;
  48405. if (engine.isInVRExclusivePointerMode) {
  48406. return;
  48407. }
  48408. if (!_this.touchEnabled && evt.pointerType === "touch") {
  48409. return;
  48410. }
  48411. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48412. return;
  48413. }
  48414. var srcElement = (evt.srcElement || evt.target);
  48415. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48416. try {
  48417. srcElement.setPointerCapture(evt.pointerId);
  48418. }
  48419. catch (e) {
  48420. //Nothing to do with the error. Execution will continue.
  48421. }
  48422. _this.previousPosition = {
  48423. x: evt.clientX,
  48424. y: evt.clientY
  48425. };
  48426. if (!noPreventDefault) {
  48427. evt.preventDefault();
  48428. element.focus();
  48429. }
  48430. }
  48431. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48432. try {
  48433. srcElement.releasePointerCapture(evt.pointerId);
  48434. }
  48435. catch (e) {
  48436. //Nothing to do with the error.
  48437. }
  48438. _this.previousPosition = null;
  48439. if (!noPreventDefault) {
  48440. evt.preventDefault();
  48441. }
  48442. }
  48443. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48444. if (!_this.previousPosition || engine.isPointerLock) {
  48445. return;
  48446. }
  48447. var offsetX = evt.clientX - _this.previousPosition.x;
  48448. if (_this.camera.getScene().useRightHandedSystem) {
  48449. offsetX *= -1;
  48450. }
  48451. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
  48452. offsetX *= -1;
  48453. }
  48454. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  48455. var offsetY = evt.clientY - _this.previousPosition.y;
  48456. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  48457. _this.previousPosition = {
  48458. x: evt.clientX,
  48459. y: evt.clientY
  48460. };
  48461. if (!noPreventDefault) {
  48462. evt.preventDefault();
  48463. }
  48464. }
  48465. };
  48466. }
  48467. this._onMouseMove = function (evt) {
  48468. if (!engine.isPointerLock) {
  48469. return;
  48470. }
  48471. if (engine.isInVRExclusivePointerMode) {
  48472. return;
  48473. }
  48474. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48475. if (_this.camera.getScene().useRightHandedSystem) {
  48476. offsetX *= -1;
  48477. }
  48478. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
  48479. offsetX *= -1;
  48480. }
  48481. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  48482. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48483. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  48484. _this.previousPosition = null;
  48485. if (!noPreventDefault) {
  48486. evt.preventDefault();
  48487. }
  48488. };
  48489. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  48490. element.addEventListener("mousemove", this._onMouseMove, false);
  48491. };
  48492. /**
  48493. * Detach the current controls from the specified dom element.
  48494. * @param element Defines the element to stop listening the inputs from
  48495. */
  48496. FreeCameraMouseInput.prototype.detachControl = function (element) {
  48497. if (this._observer && element) {
  48498. this.camera.getScene().onPointerObservable.remove(this._observer);
  48499. if (this._onMouseMove) {
  48500. element.removeEventListener("mousemove", this._onMouseMove);
  48501. }
  48502. this._observer = null;
  48503. this._onMouseMove = null;
  48504. this.previousPosition = null;
  48505. }
  48506. };
  48507. /**
  48508. * Gets the class name of the current intput.
  48509. * @returns the class name
  48510. */
  48511. FreeCameraMouseInput.prototype.getClassName = function () {
  48512. return "FreeCameraMouseInput";
  48513. };
  48514. /**
  48515. * Get the friendly name associated with the input class.
  48516. * @returns the input friendly name
  48517. */
  48518. FreeCameraMouseInput.prototype.getSimpleName = function () {
  48519. return "mouse";
  48520. };
  48521. __decorate([
  48522. BABYLON.serialize()
  48523. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  48524. __decorate([
  48525. BABYLON.serialize()
  48526. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  48527. return FreeCameraMouseInput;
  48528. }());
  48529. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  48530. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  48531. })(BABYLON || (BABYLON = {}));
  48532. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  48533. var BABYLON;
  48534. (function (BABYLON) {
  48535. /**
  48536. * Manage the keyboard inputs to control the movement of a free camera.
  48537. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48538. */
  48539. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  48540. function FreeCameraKeyboardMoveInput() {
  48541. /**
  48542. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48543. */
  48544. this.keysUp = [38];
  48545. /**
  48546. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48547. */
  48548. this.keysDown = [40];
  48549. /**
  48550. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48551. */
  48552. this.keysLeft = [37];
  48553. /**
  48554. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48555. */
  48556. this.keysRight = [39];
  48557. this._keys = new Array();
  48558. }
  48559. /**
  48560. * Attach the input controls to a specific dom element to get the input from.
  48561. * @param element Defines the element the controls should be listened from
  48562. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48563. */
  48564. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48565. var _this = this;
  48566. if (this._onCanvasBlurObserver) {
  48567. return;
  48568. }
  48569. this._scene = this.camera.getScene();
  48570. this._engine = this._scene.getEngine();
  48571. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48572. _this._keys = [];
  48573. });
  48574. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48575. var evt = info.event;
  48576. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48577. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48578. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48579. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48580. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48581. var index = _this._keys.indexOf(evt.keyCode);
  48582. if (index === -1) {
  48583. _this._keys.push(evt.keyCode);
  48584. }
  48585. if (!noPreventDefault) {
  48586. evt.preventDefault();
  48587. }
  48588. }
  48589. }
  48590. else {
  48591. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48592. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48593. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48594. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48595. var index = _this._keys.indexOf(evt.keyCode);
  48596. if (index >= 0) {
  48597. _this._keys.splice(index, 1);
  48598. }
  48599. if (!noPreventDefault) {
  48600. evt.preventDefault();
  48601. }
  48602. }
  48603. }
  48604. });
  48605. };
  48606. /**
  48607. * Detach the current controls from the specified dom element.
  48608. * @param element Defines the element to stop listening the inputs from
  48609. */
  48610. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48611. if (this._scene) {
  48612. if (this._onKeyboardObserver) {
  48613. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48614. }
  48615. if (this._onCanvasBlurObserver) {
  48616. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48617. }
  48618. this._onKeyboardObserver = null;
  48619. this._onCanvasBlurObserver = null;
  48620. }
  48621. this._keys = [];
  48622. };
  48623. /**
  48624. * Update the current camera state depending on the inputs that have been used this frame.
  48625. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  48626. */
  48627. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48628. if (this._onKeyboardObserver) {
  48629. var camera = this.camera;
  48630. // Keyboard
  48631. for (var index = 0; index < this._keys.length; index++) {
  48632. var keyCode = this._keys[index];
  48633. var speed = camera._computeLocalCameraSpeed();
  48634. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48635. camera._localDirection.copyFromFloats(-speed, 0, 0);
  48636. }
  48637. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48638. camera._localDirection.copyFromFloats(0, 0, speed);
  48639. }
  48640. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48641. camera._localDirection.copyFromFloats(speed, 0, 0);
  48642. }
  48643. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48644. camera._localDirection.copyFromFloats(0, 0, -speed);
  48645. }
  48646. if (camera.getScene().useRightHandedSystem) {
  48647. camera._localDirection.z *= -1;
  48648. }
  48649. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  48650. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  48651. camera.cameraDirection.addInPlace(camera._transformedDirection);
  48652. }
  48653. }
  48654. };
  48655. /**
  48656. * Gets the class name of the current intput.
  48657. * @returns the class name
  48658. */
  48659. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  48660. return "FreeCameraKeyboardMoveInput";
  48661. };
  48662. /** @hidden */
  48663. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  48664. this._keys = [];
  48665. };
  48666. /**
  48667. * Get the friendly name associated with the input class.
  48668. * @returns the input friendly name
  48669. */
  48670. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48671. return "keyboard";
  48672. };
  48673. __decorate([
  48674. BABYLON.serialize()
  48675. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48676. __decorate([
  48677. BABYLON.serialize()
  48678. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48679. __decorate([
  48680. BABYLON.serialize()
  48681. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48682. __decorate([
  48683. BABYLON.serialize()
  48684. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48685. return FreeCameraKeyboardMoveInput;
  48686. }());
  48687. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  48688. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  48689. })(BABYLON || (BABYLON = {}));
  48690. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  48691. var BABYLON;
  48692. (function (BABYLON) {
  48693. /**
  48694. * Default Inputs manager for the FreeCamera.
  48695. * It groups all the default supported inputs for ease of use.
  48696. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48697. */
  48698. var FreeCameraInputsManager = /** @class */ (function (_super) {
  48699. __extends(FreeCameraInputsManager, _super);
  48700. /**
  48701. * Instantiates a new FreeCameraInputsManager.
  48702. * @param camera Defines the camera the inputs belong to
  48703. */
  48704. function FreeCameraInputsManager(camera) {
  48705. return _super.call(this, camera) || this;
  48706. }
  48707. /**
  48708. * Add keyboard input support to the input manager.
  48709. * @returns the current input manager
  48710. */
  48711. FreeCameraInputsManager.prototype.addKeyboard = function () {
  48712. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  48713. return this;
  48714. };
  48715. /**
  48716. * Add mouse input support to the input manager.
  48717. * @param touchEnabled if the FreeCameraMouseInput should support touch (default: true)
  48718. * @returns the current input manager
  48719. */
  48720. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  48721. if (touchEnabled === void 0) { touchEnabled = true; }
  48722. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  48723. return this;
  48724. };
  48725. /**
  48726. * Add orientation input support to the input manager.
  48727. * @returns the current input manager
  48728. */
  48729. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  48730. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  48731. return this;
  48732. };
  48733. /**
  48734. * Add touch input support to the input manager.
  48735. * @returns the current input manager
  48736. */
  48737. FreeCameraInputsManager.prototype.addTouch = function () {
  48738. this.add(new BABYLON.FreeCameraTouchInput());
  48739. return this;
  48740. };
  48741. /**
  48742. * Add virtual joystick input support to the input manager.
  48743. * @returns the current input manager
  48744. */
  48745. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  48746. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  48747. return this;
  48748. };
  48749. return FreeCameraInputsManager;
  48750. }(BABYLON.CameraInputsManager));
  48751. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  48752. })(BABYLON || (BABYLON = {}));
  48753. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  48754. var BABYLON;
  48755. (function (BABYLON) {
  48756. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  48757. // Forcing to use the Universal camera
  48758. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  48759. });
  48760. /**
  48761. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  48762. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  48763. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  48764. */
  48765. var FreeCamera = /** @class */ (function (_super) {
  48766. __extends(FreeCamera, _super);
  48767. /**
  48768. * Instantiates a Free Camera.
  48769. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  48770. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  48771. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  48772. * @param name Define the name of the camera in the scene
  48773. * @param position Define the start position of the camera in the scene
  48774. * @param scene Define the scene the camera belongs to
  48775. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48776. */
  48777. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  48778. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48779. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  48780. /**
  48781. * Define the collision ellipsoid of the camera.
  48782. * This is helpful to simulate a camera body like the player body around the camera
  48783. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  48784. */
  48785. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  48786. /**
  48787. * Define an offset for the position of the ellipsoid around the camera.
  48788. * This can be helpful to determine the center of the body near the gravity center of the body
  48789. * instead of its head.
  48790. */
  48791. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  48792. /**
  48793. * Enable or disable collisions of the camera with the rest of the scene objects.
  48794. */
  48795. _this.checkCollisions = false;
  48796. /**
  48797. * Enable or disable gravity on the camera.
  48798. */
  48799. _this.applyGravity = false;
  48800. _this._needMoveForGravity = false;
  48801. _this._oldPosition = BABYLON.Vector3.Zero();
  48802. _this._diffPosition = BABYLON.Vector3.Zero();
  48803. _this._newPosition = BABYLON.Vector3.Zero();
  48804. // Collisions
  48805. _this._collisionMask = -1;
  48806. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48807. if (collidedMesh === void 0) { collidedMesh = null; }
  48808. //TODO move this to the collision coordinator!
  48809. if (_this.getScene().workerCollisions) {
  48810. newPosition.multiplyInPlace(_this._collider._radius);
  48811. }
  48812. var updatePosition = function (newPos) {
  48813. _this._newPosition.copyFrom(newPos);
  48814. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  48815. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  48816. _this.position.addInPlace(_this._diffPosition);
  48817. if (_this.onCollide && collidedMesh) {
  48818. _this.onCollide(collidedMesh);
  48819. }
  48820. }
  48821. };
  48822. updatePosition(newPosition);
  48823. };
  48824. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  48825. _this.inputs.addKeyboard().addMouse();
  48826. return _this;
  48827. }
  48828. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  48829. /**
  48830. * Gets the input sensibility for a mouse input. (default is 2000.0)
  48831. * Higher values reduce sensitivity.
  48832. */
  48833. get: function () {
  48834. var mouse = this.inputs.attached["mouse"];
  48835. if (mouse) {
  48836. return mouse.angularSensibility;
  48837. }
  48838. return 0;
  48839. },
  48840. /**
  48841. * Sets the input sensibility for a mouse input. (default is 2000.0)
  48842. * Higher values reduce sensitivity.
  48843. */
  48844. set: function (value) {
  48845. var mouse = this.inputs.attached["mouse"];
  48846. if (mouse) {
  48847. mouse.angularSensibility = value;
  48848. }
  48849. },
  48850. enumerable: true,
  48851. configurable: true
  48852. });
  48853. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  48854. /**
  48855. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48856. */
  48857. get: function () {
  48858. var keyboard = this.inputs.attached["keyboard"];
  48859. if (keyboard) {
  48860. return keyboard.keysUp;
  48861. }
  48862. return [];
  48863. },
  48864. set: function (value) {
  48865. var keyboard = this.inputs.attached["keyboard"];
  48866. if (keyboard) {
  48867. keyboard.keysUp = value;
  48868. }
  48869. },
  48870. enumerable: true,
  48871. configurable: true
  48872. });
  48873. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  48874. /**
  48875. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48876. */
  48877. get: function () {
  48878. var keyboard = this.inputs.attached["keyboard"];
  48879. if (keyboard) {
  48880. return keyboard.keysDown;
  48881. }
  48882. return [];
  48883. },
  48884. set: function (value) {
  48885. var keyboard = this.inputs.attached["keyboard"];
  48886. if (keyboard) {
  48887. keyboard.keysDown = value;
  48888. }
  48889. },
  48890. enumerable: true,
  48891. configurable: true
  48892. });
  48893. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  48894. /**
  48895. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48896. */
  48897. get: function () {
  48898. var keyboard = this.inputs.attached["keyboard"];
  48899. if (keyboard) {
  48900. return keyboard.keysLeft;
  48901. }
  48902. return [];
  48903. },
  48904. set: function (value) {
  48905. var keyboard = this.inputs.attached["keyboard"];
  48906. if (keyboard) {
  48907. keyboard.keysLeft = value;
  48908. }
  48909. },
  48910. enumerable: true,
  48911. configurable: true
  48912. });
  48913. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  48914. /**
  48915. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48916. */
  48917. get: function () {
  48918. var keyboard = this.inputs.attached["keyboard"];
  48919. if (keyboard) {
  48920. return keyboard.keysRight;
  48921. }
  48922. return [];
  48923. },
  48924. set: function (value) {
  48925. var keyboard = this.inputs.attached["keyboard"];
  48926. if (keyboard) {
  48927. keyboard.keysRight = value;
  48928. }
  48929. },
  48930. enumerable: true,
  48931. configurable: true
  48932. });
  48933. /**
  48934. * Attached controls to the current camera.
  48935. * @param element Defines the element the controls should be listened from
  48936. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48937. */
  48938. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  48939. this.inputs.attachElement(element, noPreventDefault);
  48940. };
  48941. /**
  48942. * Detach the current controls from the camera.
  48943. * The camera will stop reacting to inputs.
  48944. * @param element Defines the element to stop listening the inputs from
  48945. */
  48946. FreeCamera.prototype.detachControl = function (element) {
  48947. this.inputs.detachElement(element);
  48948. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48949. this.cameraRotation = new BABYLON.Vector2(0, 0);
  48950. };
  48951. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  48952. /**
  48953. * Define a collision mask to limit the list of object the camera can collide with
  48954. */
  48955. get: function () {
  48956. return this._collisionMask;
  48957. },
  48958. set: function (mask) {
  48959. this._collisionMask = !isNaN(mask) ? mask : -1;
  48960. },
  48961. enumerable: true,
  48962. configurable: true
  48963. });
  48964. /** @hidden */
  48965. FreeCamera.prototype._collideWithWorld = function (displacement) {
  48966. var globalPosition;
  48967. if (this.parent) {
  48968. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  48969. }
  48970. else {
  48971. globalPosition = this.position;
  48972. }
  48973. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  48974. this._oldPosition.addInPlace(this.ellipsoidOffset);
  48975. if (!this._collider) {
  48976. this._collider = new BABYLON.Collider();
  48977. }
  48978. this._collider._radius = this.ellipsoid;
  48979. this._collider.collisionMask = this._collisionMask;
  48980. //no need for clone, as long as gravity is not on.
  48981. var actualDisplacement = displacement;
  48982. //add gravity to the direction to prevent the dual-collision checking
  48983. if (this.applyGravity) {
  48984. //this prevents mending with cameraDirection, a global variable of the free camera class.
  48985. actualDisplacement = displacement.add(this.getScene().gravity);
  48986. }
  48987. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48988. };
  48989. /** @hidden */
  48990. FreeCamera.prototype._checkInputs = function () {
  48991. if (!this._localDirection) {
  48992. this._localDirection = BABYLON.Vector3.Zero();
  48993. this._transformedDirection = BABYLON.Vector3.Zero();
  48994. }
  48995. this.inputs.checkInputs();
  48996. _super.prototype._checkInputs.call(this);
  48997. };
  48998. /** @hidden */
  48999. FreeCamera.prototype._decideIfNeedsToMove = function () {
  49000. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  49001. };
  49002. /** @hidden */
  49003. FreeCamera.prototype._updatePosition = function () {
  49004. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  49005. this._collideWithWorld(this.cameraDirection);
  49006. }
  49007. else {
  49008. _super.prototype._updatePosition.call(this);
  49009. }
  49010. };
  49011. /**
  49012. * Destroy the camera and release the current resources hold by it.
  49013. */
  49014. FreeCamera.prototype.dispose = function () {
  49015. this.inputs.clear();
  49016. _super.prototype.dispose.call(this);
  49017. };
  49018. /**
  49019. * Gets the current object class name.
  49020. * @return the class name
  49021. */
  49022. FreeCamera.prototype.getClassName = function () {
  49023. return "FreeCamera";
  49024. };
  49025. __decorate([
  49026. BABYLON.serializeAsVector3()
  49027. ], FreeCamera.prototype, "ellipsoid", void 0);
  49028. __decorate([
  49029. BABYLON.serializeAsVector3()
  49030. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  49031. __decorate([
  49032. BABYLON.serialize()
  49033. ], FreeCamera.prototype, "checkCollisions", void 0);
  49034. __decorate([
  49035. BABYLON.serialize()
  49036. ], FreeCamera.prototype, "applyGravity", void 0);
  49037. return FreeCamera;
  49038. }(BABYLON.TargetCamera));
  49039. BABYLON.FreeCamera = FreeCamera;
  49040. })(BABYLON || (BABYLON = {}));
  49041. //# sourceMappingURL=babylon.freeCamera.js.map
  49042. var BABYLON;
  49043. (function (BABYLON) {
  49044. /**
  49045. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  49046. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49047. */
  49048. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  49049. function ArcRotateCameraKeyboardMoveInput() {
  49050. /**
  49051. * Defines the list of key codes associated with the up action (increase alpha)
  49052. */
  49053. this.keysUp = [38];
  49054. /**
  49055. * Defines the list of key codes associated with the down action (decrease alpha)
  49056. */
  49057. this.keysDown = [40];
  49058. /**
  49059. * Defines the list of key codes associated with the left action (increase beta)
  49060. */
  49061. this.keysLeft = [37];
  49062. /**
  49063. * Defines the list of key codes associated with the right action (decrease beta)
  49064. */
  49065. this.keysRight = [39];
  49066. /**
  49067. * Defines the list of key codes associated with the reset action.
  49068. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  49069. */
  49070. this.keysReset = [220];
  49071. /**
  49072. * Defines the panning sensibility of the inputs.
  49073. * (How fast is the camera paning)
  49074. */
  49075. this.panningSensibility = 50.0;
  49076. /**
  49077. * Defines the zooming sensibility of the inputs.
  49078. * (How fast is the camera zooming)
  49079. */
  49080. this.zoomingSensibility = 25.0;
  49081. /**
  49082. * Defines wether maintaining the alt key down switch the movement mode from
  49083. * orientation to zoom.
  49084. */
  49085. this.useAltToZoom = true;
  49086. /**
  49087. * Rotation speed of the camera
  49088. */
  49089. this.angularSpeed = 0.01;
  49090. this._keys = new Array();
  49091. }
  49092. /**
  49093. * Attach the input controls to a specific dom element to get the input from.
  49094. * @param element Defines the element the controls should be listened from
  49095. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49096. */
  49097. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  49098. var _this = this;
  49099. if (this._onCanvasBlurObserver) {
  49100. return;
  49101. }
  49102. this._scene = this.camera.getScene();
  49103. this._engine = this._scene.getEngine();
  49104. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  49105. _this._keys = [];
  49106. });
  49107. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  49108. var evt = info.event;
  49109. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  49110. _this._ctrlPressed = evt.ctrlKey;
  49111. _this._altPressed = evt.altKey;
  49112. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  49113. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  49114. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  49115. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  49116. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  49117. var index = _this._keys.indexOf(evt.keyCode);
  49118. if (index === -1) {
  49119. _this._keys.push(evt.keyCode);
  49120. }
  49121. if (evt.preventDefault) {
  49122. if (!noPreventDefault) {
  49123. evt.preventDefault();
  49124. }
  49125. }
  49126. }
  49127. }
  49128. else {
  49129. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  49130. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  49131. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  49132. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  49133. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  49134. var index = _this._keys.indexOf(evt.keyCode);
  49135. if (index >= 0) {
  49136. _this._keys.splice(index, 1);
  49137. }
  49138. if (evt.preventDefault) {
  49139. if (!noPreventDefault) {
  49140. evt.preventDefault();
  49141. }
  49142. }
  49143. }
  49144. }
  49145. });
  49146. };
  49147. /**
  49148. * Detach the current controls from the specified dom element.
  49149. * @param element Defines the element to stop listening the inputs from
  49150. */
  49151. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  49152. if (this._scene) {
  49153. if (this._onKeyboardObserver) {
  49154. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  49155. }
  49156. if (this._onCanvasBlurObserver) {
  49157. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  49158. }
  49159. this._onKeyboardObserver = null;
  49160. this._onCanvasBlurObserver = null;
  49161. }
  49162. this._keys = [];
  49163. };
  49164. /**
  49165. * Update the current camera state depending on the inputs that have been used this frame.
  49166. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  49167. */
  49168. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  49169. if (this._onKeyboardObserver) {
  49170. var camera = this.camera;
  49171. for (var index = 0; index < this._keys.length; index++) {
  49172. var keyCode = this._keys[index];
  49173. if (this.keysLeft.indexOf(keyCode) !== -1) {
  49174. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49175. camera.inertialPanningX -= 1 / this.panningSensibility;
  49176. }
  49177. else {
  49178. camera.inertialAlphaOffset -= this.angularSpeed;
  49179. }
  49180. }
  49181. else if (this.keysUp.indexOf(keyCode) !== -1) {
  49182. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49183. camera.inertialPanningY += 1 / this.panningSensibility;
  49184. }
  49185. else if (this._altPressed && this.useAltToZoom) {
  49186. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  49187. }
  49188. else {
  49189. camera.inertialBetaOffset -= this.angularSpeed;
  49190. }
  49191. }
  49192. else if (this.keysRight.indexOf(keyCode) !== -1) {
  49193. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49194. camera.inertialPanningX += 1 / this.panningSensibility;
  49195. }
  49196. else {
  49197. camera.inertialAlphaOffset += this.angularSpeed;
  49198. }
  49199. }
  49200. else if (this.keysDown.indexOf(keyCode) !== -1) {
  49201. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49202. camera.inertialPanningY -= 1 / this.panningSensibility;
  49203. }
  49204. else if (this._altPressed && this.useAltToZoom) {
  49205. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  49206. }
  49207. else {
  49208. camera.inertialBetaOffset += this.angularSpeed;
  49209. }
  49210. }
  49211. else if (this.keysReset.indexOf(keyCode) !== -1) {
  49212. if (camera.useInputToRestoreState) {
  49213. camera.restoreState();
  49214. }
  49215. }
  49216. }
  49217. }
  49218. };
  49219. /**
  49220. * Gets the class name of the current intput.
  49221. * @returns the class name
  49222. */
  49223. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  49224. return "ArcRotateCameraKeyboardMoveInput";
  49225. };
  49226. /**
  49227. * Get the friendly name associated with the input class.
  49228. * @returns the input friendly name
  49229. */
  49230. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  49231. return "keyboard";
  49232. };
  49233. __decorate([
  49234. BABYLON.serialize()
  49235. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  49236. __decorate([
  49237. BABYLON.serialize()
  49238. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  49239. __decorate([
  49240. BABYLON.serialize()
  49241. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  49242. __decorate([
  49243. BABYLON.serialize()
  49244. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  49245. __decorate([
  49246. BABYLON.serialize()
  49247. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  49248. __decorate([
  49249. BABYLON.serialize()
  49250. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  49251. __decorate([
  49252. BABYLON.serialize()
  49253. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  49254. __decorate([
  49255. BABYLON.serialize()
  49256. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  49257. __decorate([
  49258. BABYLON.serialize()
  49259. ], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", void 0);
  49260. return ArcRotateCameraKeyboardMoveInput;
  49261. }());
  49262. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  49263. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  49264. })(BABYLON || (BABYLON = {}));
  49265. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  49266. var BABYLON;
  49267. (function (BABYLON) {
  49268. /**
  49269. * Manage the mouse wheel inputs to control an arc rotate camera.
  49270. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49271. */
  49272. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  49273. function ArcRotateCameraMouseWheelInput() {
  49274. /**
  49275. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  49276. */
  49277. this.wheelPrecision = 3.0;
  49278. /**
  49279. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  49280. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  49281. */
  49282. this.wheelDeltaPercentage = 0;
  49283. }
  49284. /**
  49285. * Attach the input controls to a specific dom element to get the input from.
  49286. * @param element Defines the element the controls should be listened from
  49287. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49288. */
  49289. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  49290. var _this = this;
  49291. this._wheel = function (p, s) {
  49292. //sanity check - this should be a PointerWheel event.
  49293. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL) {
  49294. return;
  49295. }
  49296. var event = p.event;
  49297. var delta = 0;
  49298. if (event.wheelDelta) {
  49299. if (_this.wheelDeltaPercentage) {
  49300. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  49301. if (event.wheelDelta > 0) {
  49302. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  49303. }
  49304. else {
  49305. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  49306. }
  49307. }
  49308. else {
  49309. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  49310. }
  49311. }
  49312. else if (event.detail) {
  49313. delta = -event.detail / _this.wheelPrecision;
  49314. }
  49315. if (delta) {
  49316. _this.camera.inertialRadiusOffset += delta;
  49317. }
  49318. if (event.preventDefault) {
  49319. if (!noPreventDefault) {
  49320. event.preventDefault();
  49321. }
  49322. }
  49323. };
  49324. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  49325. };
  49326. /**
  49327. * Detach the current controls from the specified dom element.
  49328. * @param element Defines the element to stop listening the inputs from
  49329. */
  49330. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  49331. if (this._observer && element) {
  49332. this.camera.getScene().onPointerObservable.remove(this._observer);
  49333. this._observer = null;
  49334. this._wheel = null;
  49335. }
  49336. };
  49337. /**
  49338. * Gets the class name of the current intput.
  49339. * @returns the class name
  49340. */
  49341. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  49342. return "ArcRotateCameraMouseWheelInput";
  49343. };
  49344. /**
  49345. * Get the friendly name associated with the input class.
  49346. * @returns the input friendly name
  49347. */
  49348. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  49349. return "mousewheel";
  49350. };
  49351. __decorate([
  49352. BABYLON.serialize()
  49353. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  49354. __decorate([
  49355. BABYLON.serialize()
  49356. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  49357. return ArcRotateCameraMouseWheelInput;
  49358. }());
  49359. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  49360. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  49361. })(BABYLON || (BABYLON = {}));
  49362. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  49363. var BABYLON;
  49364. (function (BABYLON) {
  49365. /**
  49366. * Manage the pointers inputs to control an arc rotate camera.
  49367. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49368. */
  49369. var ArcRotateCameraPointersInput = /** @class */ (function () {
  49370. function ArcRotateCameraPointersInput() {
  49371. /**
  49372. * Defines the buttons associated with the input to handle camera move.
  49373. */
  49374. this.buttons = [0, 1, 2];
  49375. /**
  49376. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  49377. */
  49378. this.angularSensibilityX = 1000.0;
  49379. /**
  49380. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  49381. */
  49382. this.angularSensibilityY = 1000.0;
  49383. /**
  49384. * Defines the pointer pinch precision or how fast is the camera zooming.
  49385. */
  49386. this.pinchPrecision = 12.0;
  49387. /**
  49388. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  49389. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  49390. */
  49391. this.pinchDeltaPercentage = 0;
  49392. /**
  49393. * Defines the pointer panning sensibility or how fast is the camera moving.
  49394. */
  49395. this.panningSensibility = 1000.0;
  49396. /**
  49397. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  49398. */
  49399. this.multiTouchPanning = true;
  49400. /**
  49401. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  49402. */
  49403. this.multiTouchPanAndZoom = true;
  49404. /**
  49405. * Revers pinch action direction.
  49406. */
  49407. this.pinchInwards = true;
  49408. this._isPanClick = false;
  49409. }
  49410. /**
  49411. * Attach the input controls to a specific dom element to get the input from.
  49412. * @param element Defines the element the controls should be listened from
  49413. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49414. */
  49415. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  49416. var _this = this;
  49417. var engine = this.camera.getEngine();
  49418. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  49419. var pointA = null;
  49420. var pointB = null;
  49421. var previousPinchSquaredDistance = 0;
  49422. var initialDistance = 0;
  49423. var twoFingerActivityCount = 0;
  49424. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  49425. this._pointerInput = function (p, s) {
  49426. var evt = p.event;
  49427. var isTouch = p.event.pointerType === "touch";
  49428. if (engine.isInVRExclusivePointerMode) {
  49429. return;
  49430. }
  49431. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  49432. return;
  49433. }
  49434. var srcElement = (evt.srcElement || evt.target);
  49435. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  49436. try {
  49437. srcElement.setPointerCapture(evt.pointerId);
  49438. }
  49439. catch (e) {
  49440. //Nothing to do with the error. Execution will continue.
  49441. }
  49442. // Manage panning with pan button click
  49443. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  49444. // manage pointers
  49445. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  49446. if (pointA === null) {
  49447. pointA = cacheSoloPointer;
  49448. }
  49449. else if (pointB === null) {
  49450. pointB = cacheSoloPointer;
  49451. }
  49452. if (!noPreventDefault) {
  49453. evt.preventDefault();
  49454. element.focus();
  49455. }
  49456. }
  49457. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  49458. if (_this.camera.useInputToRestoreState) {
  49459. _this.camera.restoreState();
  49460. }
  49461. }
  49462. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  49463. try {
  49464. srcElement.releasePointerCapture(evt.pointerId);
  49465. }
  49466. catch (e) {
  49467. //Nothing to do with the error.
  49468. }
  49469. cacheSoloPointer = null;
  49470. previousPinchSquaredDistance = 0;
  49471. previousMultiTouchPanPosition.isPaning = false;
  49472. previousMultiTouchPanPosition.isPinching = false;
  49473. twoFingerActivityCount = 0;
  49474. initialDistance = 0;
  49475. if (!isTouch) {
  49476. pointB = null; // Mouse and pen are mono pointer
  49477. }
  49478. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  49479. //but emptying completly pointers collection is required to fix a bug on iPhone :
  49480. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  49481. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  49482. if (engine._badOS) {
  49483. pointA = pointB = null;
  49484. }
  49485. else {
  49486. //only remove the impacted pointer in case of multitouch allowing on most
  49487. //platforms switching from rotate to zoom and pan seamlessly.
  49488. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  49489. pointA = pointB;
  49490. pointB = null;
  49491. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  49492. }
  49493. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  49494. pointB = null;
  49495. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  49496. }
  49497. else {
  49498. pointA = pointB = null;
  49499. }
  49500. }
  49501. if (!noPreventDefault) {
  49502. evt.preventDefault();
  49503. }
  49504. }
  49505. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  49506. if (!noPreventDefault) {
  49507. evt.preventDefault();
  49508. }
  49509. // One button down
  49510. if (pointA && pointB === null && cacheSoloPointer) {
  49511. if (_this.panningSensibility !== 0 &&
  49512. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  49513. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  49514. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  49515. }
  49516. else {
  49517. var offsetX = evt.clientX - cacheSoloPointer.x;
  49518. var offsetY = evt.clientY - cacheSoloPointer.y;
  49519. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  49520. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  49521. }
  49522. cacheSoloPointer.x = evt.clientX;
  49523. cacheSoloPointer.y = evt.clientY;
  49524. }
  49525. // Two buttons down: pinch/pan
  49526. else if (pointA && pointB) {
  49527. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  49528. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  49529. ed.x = evt.clientX;
  49530. ed.y = evt.clientY;
  49531. var direction = _this.pinchInwards ? 1 : -1;
  49532. var distX = pointA.x - pointB.x;
  49533. var distY = pointA.y - pointB.y;
  49534. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  49535. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  49536. if (previousPinchSquaredDistance === 0) {
  49537. initialDistance = pinchDistance;
  49538. previousPinchSquaredDistance = pinchSquaredDistance;
  49539. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  49540. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  49541. return;
  49542. }
  49543. if (_this.multiTouchPanAndZoom) {
  49544. if (_this.pinchDeltaPercentage) {
  49545. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  49546. }
  49547. else {
  49548. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  49549. (_this.pinchPrecision *
  49550. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  49551. direction);
  49552. }
  49553. if (_this.panningSensibility !== 0) {
  49554. var pointersCenterX = (pointA.x + pointB.x) / 2;
  49555. var pointersCenterY = (pointA.y + pointB.y) / 2;
  49556. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  49557. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  49558. previousMultiTouchPanPosition.x = pointersCenterX;
  49559. previousMultiTouchPanPosition.y = pointersCenterY;
  49560. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  49561. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  49562. }
  49563. }
  49564. else {
  49565. twoFingerActivityCount++;
  49566. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  49567. if (_this.pinchDeltaPercentage) {
  49568. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  49569. }
  49570. else {
  49571. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  49572. (_this.pinchPrecision *
  49573. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  49574. direction);
  49575. }
  49576. previousMultiTouchPanPosition.isPaning = false;
  49577. previousMultiTouchPanPosition.isPinching = true;
  49578. }
  49579. else {
  49580. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  49581. if (!previousMultiTouchPanPosition.isPaning) {
  49582. previousMultiTouchPanPosition.isPaning = true;
  49583. previousMultiTouchPanPosition.isPinching = false;
  49584. previousMultiTouchPanPosition.x = ed.x;
  49585. previousMultiTouchPanPosition.y = ed.y;
  49586. return;
  49587. }
  49588. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  49589. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  49590. }
  49591. }
  49592. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  49593. previousMultiTouchPanPosition.x = ed.x;
  49594. previousMultiTouchPanPosition.y = ed.y;
  49595. }
  49596. }
  49597. previousPinchSquaredDistance = pinchSquaredDistance;
  49598. }
  49599. }
  49600. };
  49601. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  49602. this._onContextMenu = function (evt) {
  49603. evt.preventDefault();
  49604. };
  49605. if (!this.camera._useCtrlForPanning) {
  49606. element.addEventListener("contextmenu", this._onContextMenu, false);
  49607. }
  49608. this._onLostFocus = function () {
  49609. //this._keys = [];
  49610. pointA = pointB = null;
  49611. previousPinchSquaredDistance = 0;
  49612. previousMultiTouchPanPosition.isPaning = false;
  49613. previousMultiTouchPanPosition.isPinching = false;
  49614. twoFingerActivityCount = 0;
  49615. cacheSoloPointer = null;
  49616. initialDistance = 0;
  49617. };
  49618. this._onMouseMove = function (evt) {
  49619. if (!engine.isPointerLock) {
  49620. return;
  49621. }
  49622. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  49623. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  49624. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  49625. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  49626. if (!noPreventDefault) {
  49627. evt.preventDefault();
  49628. }
  49629. };
  49630. this._onGestureStart = function (e) {
  49631. if (window.MSGesture === undefined) {
  49632. return;
  49633. }
  49634. if (!_this._MSGestureHandler) {
  49635. _this._MSGestureHandler = new MSGesture();
  49636. _this._MSGestureHandler.target = element;
  49637. }
  49638. _this._MSGestureHandler.addPointer(e.pointerId);
  49639. };
  49640. this._onGesture = function (e) {
  49641. _this.camera.radius *= e.scale;
  49642. if (e.preventDefault) {
  49643. if (!noPreventDefault) {
  49644. e.stopPropagation();
  49645. e.preventDefault();
  49646. }
  49647. }
  49648. };
  49649. element.addEventListener("mousemove", this._onMouseMove, false);
  49650. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  49651. element.addEventListener("MSGestureChange", this._onGesture, false);
  49652. BABYLON.Tools.RegisterTopRootEvents([
  49653. { name: "blur", handler: this._onLostFocus }
  49654. ]);
  49655. };
  49656. /**
  49657. * Detach the current controls from the specified dom element.
  49658. * @param element Defines the element to stop listening the inputs from
  49659. */
  49660. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  49661. if (this._onLostFocus) {
  49662. BABYLON.Tools.UnregisterTopRootEvents([
  49663. { name: "blur", handler: this._onLostFocus }
  49664. ]);
  49665. }
  49666. if (element && this._observer) {
  49667. this.camera.getScene().onPointerObservable.remove(this._observer);
  49668. this._observer = null;
  49669. if (this._onContextMenu) {
  49670. element.removeEventListener("contextmenu", this._onContextMenu);
  49671. }
  49672. if (this._onMouseMove) {
  49673. element.removeEventListener("mousemove", this._onMouseMove);
  49674. }
  49675. if (this._onGestureStart) {
  49676. element.removeEventListener("MSPointerDown", this._onGestureStart);
  49677. }
  49678. if (this._onGesture) {
  49679. element.removeEventListener("MSGestureChange", this._onGesture);
  49680. }
  49681. this._isPanClick = false;
  49682. this.pinchInwards = true;
  49683. this._onMouseMove = null;
  49684. this._onGestureStart = null;
  49685. this._onGesture = null;
  49686. this._MSGestureHandler = null;
  49687. this._onLostFocus = null;
  49688. this._onContextMenu = null;
  49689. }
  49690. };
  49691. /**
  49692. * Gets the class name of the current intput.
  49693. * @returns the class name
  49694. */
  49695. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  49696. return "ArcRotateCameraPointersInput";
  49697. };
  49698. /**
  49699. * Get the friendly name associated with the input class.
  49700. * @returns the input friendly name
  49701. */
  49702. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  49703. return "pointers";
  49704. };
  49705. __decorate([
  49706. BABYLON.serialize()
  49707. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  49708. __decorate([
  49709. BABYLON.serialize()
  49710. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  49711. __decorate([
  49712. BABYLON.serialize()
  49713. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  49714. __decorate([
  49715. BABYLON.serialize()
  49716. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  49717. __decorate([
  49718. BABYLON.serialize()
  49719. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  49720. __decorate([
  49721. BABYLON.serialize()
  49722. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  49723. __decorate([
  49724. BABYLON.serialize()
  49725. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  49726. __decorate([
  49727. BABYLON.serialize()
  49728. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  49729. return ArcRotateCameraPointersInput;
  49730. }());
  49731. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  49732. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  49733. })(BABYLON || (BABYLON = {}));
  49734. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  49735. var BABYLON;
  49736. (function (BABYLON) {
  49737. /**
  49738. * Default Inputs manager for the ArcRotateCamera.
  49739. * It groups all the default supported inputs for ease of use.
  49740. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49741. */
  49742. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  49743. __extends(ArcRotateCameraInputsManager, _super);
  49744. /**
  49745. * Instantiates a new ArcRotateCameraInputsManager.
  49746. * @param camera Defines the camera the inputs belong to
  49747. */
  49748. function ArcRotateCameraInputsManager(camera) {
  49749. return _super.call(this, camera) || this;
  49750. }
  49751. /**
  49752. * Add mouse wheel input support to the input manager.
  49753. * @returns the current input manager
  49754. */
  49755. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  49756. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  49757. return this;
  49758. };
  49759. /**
  49760. * Add pointers input support to the input manager.
  49761. * @returns the current input manager
  49762. */
  49763. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  49764. this.add(new BABYLON.ArcRotateCameraPointersInput());
  49765. return this;
  49766. };
  49767. /**
  49768. * Add keyboard input support to the input manager.
  49769. * @returns the current input manager
  49770. */
  49771. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  49772. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  49773. return this;
  49774. };
  49775. /**
  49776. * Add orientation input support to the input manager.
  49777. * @returns the current input manager
  49778. */
  49779. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  49780. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  49781. return this;
  49782. };
  49783. return ArcRotateCameraInputsManager;
  49784. }(BABYLON.CameraInputsManager));
  49785. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  49786. })(BABYLON || (BABYLON = {}));
  49787. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  49788. var BABYLON;
  49789. (function (BABYLON) {
  49790. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  49791. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  49792. });
  49793. /**
  49794. * This represents an orbital type of camera.
  49795. *
  49796. * This camera always points towards a given target position and can be rotated around that target with the target as the centre of rotation. It can be controlled with cursors and mouse, or with touch events.
  49797. * Think of this camera as one orbiting its target position, or more imaginatively as a spy satellite orbiting the earth. Its position relative to the target (earth) can be set by three parameters, alpha (radians) the longitudinal rotation, beta (radians) the latitudinal rotation and radius the distance from the target position.
  49798. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  49799. */
  49800. var ArcRotateCamera = /** @class */ (function (_super) {
  49801. __extends(ArcRotateCamera, _super);
  49802. /**
  49803. * Instantiates a new ArcRotateCamera in a given scene
  49804. * @param name Defines the name of the camera
  49805. * @param alpha Defines the camera rotation along the logitudinal axis
  49806. * @param beta Defines the camera rotation along the latitudinal axis
  49807. * @param radius Defines the camera distance from its target
  49808. * @param target Defines the camera target
  49809. * @param scene Defines the scene the camera belongs to
  49810. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  49811. */
  49812. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  49813. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  49814. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  49815. /**
  49816. * Current inertia value on the longitudinal axis.
  49817. * The bigger this number the longer it will take for the camera to stop.
  49818. */
  49819. _this.inertialAlphaOffset = 0;
  49820. /**
  49821. * Current inertia value on the latitudinal axis.
  49822. * The bigger this number the longer it will take for the camera to stop.
  49823. */
  49824. _this.inertialBetaOffset = 0;
  49825. /**
  49826. * Current inertia value on the radius axis.
  49827. * The bigger this number the longer it will take for the camera to stop.
  49828. */
  49829. _this.inertialRadiusOffset = 0;
  49830. /**
  49831. * Minimum allowed angle on the longitudinal axis.
  49832. * This can help limiting how the Camera is able to move in the scene.
  49833. */
  49834. _this.lowerAlphaLimit = null;
  49835. /**
  49836. * Maximum allowed angle on the longitudinal axis.
  49837. * This can help limiting how the Camera is able to move in the scene.
  49838. */
  49839. _this.upperAlphaLimit = null;
  49840. /**
  49841. * Minimum allowed angle on the latitudinal axis.
  49842. * This can help limiting how the Camera is able to move in the scene.
  49843. */
  49844. _this.lowerBetaLimit = 0.01;
  49845. /**
  49846. * Maximum allowed angle on the latitudinal axis.
  49847. * This can help limiting how the Camera is able to move in the scene.
  49848. */
  49849. _this.upperBetaLimit = Math.PI;
  49850. /**
  49851. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  49852. * This can help limiting how the Camera is able to move in the scene.
  49853. */
  49854. _this.lowerRadiusLimit = null;
  49855. /**
  49856. * Maximum allowed distance of the camera to the target (The camera can not get further).
  49857. * This can help limiting how the Camera is able to move in the scene.
  49858. */
  49859. _this.upperRadiusLimit = null;
  49860. /**
  49861. * Defines the current inertia value used during panning of the camera along the X axis.
  49862. */
  49863. _this.inertialPanningX = 0;
  49864. /**
  49865. * Defines the current inertia value used during panning of the camera along the Y axis.
  49866. */
  49867. _this.inertialPanningY = 0;
  49868. /**
  49869. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  49870. * Basically if your fingers moves away from more than this distance you will be considered
  49871. * in pinch mode.
  49872. */
  49873. _this.pinchToPanMaxDistance = 20;
  49874. /**
  49875. * Defines the maximum distance the camera can pan.
  49876. * This could help keeping the cammera always in your scene.
  49877. */
  49878. _this.panningDistanceLimit = null;
  49879. /**
  49880. * Defines the target of the camera before paning.
  49881. */
  49882. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  49883. /**
  49884. * Defines the value of the inertia used during panning.
  49885. * 0 would mean stop inertia and one would mean no decelleration at all.
  49886. */
  49887. _this.panningInertia = 0.9;
  49888. //-- end properties for backward compatibility for inputs
  49889. /**
  49890. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  49891. */
  49892. _this.zoomOnFactor = 1;
  49893. /**
  49894. * Defines a screen offset for the camera position.
  49895. */
  49896. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  49897. /**
  49898. * Allows the camera to be completely reversed.
  49899. * If false the camera can not arrive upside down.
  49900. */
  49901. _this.allowUpsideDown = true;
  49902. /**
  49903. * Define if double tap/click is used to restore the previously saved state of the camera.
  49904. */
  49905. _this.useInputToRestoreState = true;
  49906. /** @hidden */
  49907. _this._viewMatrix = new BABYLON.Matrix();
  49908. /**
  49909. * Defines the allowed panning axis.
  49910. */
  49911. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  49912. /**
  49913. * Observable triggered when the mesh target has been changed on the camera.
  49914. */
  49915. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  49916. /**
  49917. * Defines whether the camera should check collision with the objects oh the scene.
  49918. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  49919. */
  49920. _this.checkCollisions = false;
  49921. /**
  49922. * Defines the collision radius of the camera.
  49923. * This simulates a sphere around the camera.
  49924. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  49925. */
  49926. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  49927. _this._previousPosition = BABYLON.Vector3.Zero();
  49928. _this._collisionVelocity = BABYLON.Vector3.Zero();
  49929. _this._newPosition = BABYLON.Vector3.Zero();
  49930. _this._computationVector = BABYLON.Vector3.Zero();
  49931. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  49932. if (collidedMesh === void 0) { collidedMesh = null; }
  49933. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  49934. newPosition.multiplyInPlace(_this._collider._radius);
  49935. }
  49936. if (!collidedMesh) {
  49937. _this._previousPosition.copyFrom(_this.position);
  49938. }
  49939. else {
  49940. _this.setPosition(newPosition);
  49941. if (_this.onCollide) {
  49942. _this.onCollide(collidedMesh);
  49943. }
  49944. }
  49945. // Recompute because of constraints
  49946. var cosa = Math.cos(_this.alpha);
  49947. var sina = Math.sin(_this.alpha);
  49948. var cosb = Math.cos(_this.beta);
  49949. var sinb = Math.sin(_this.beta);
  49950. if (sinb === 0) {
  49951. sinb = 0.0001;
  49952. }
  49953. var target = _this._getTargetPosition();
  49954. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  49955. target.addToRef(_this._computationVector, _this._newPosition);
  49956. _this.position.copyFrom(_this._newPosition);
  49957. var up = _this.upVector;
  49958. if (_this.allowUpsideDown && _this.beta < 0) {
  49959. up = up.clone();
  49960. up = up.negate();
  49961. }
  49962. _this._computeViewMatrix(_this.position, target, up);
  49963. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  49964. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  49965. _this._collisionTriggered = false;
  49966. };
  49967. _this._target = BABYLON.Vector3.Zero();
  49968. if (target) {
  49969. _this.setTarget(target);
  49970. }
  49971. _this.alpha = alpha;
  49972. _this.beta = beta;
  49973. _this.radius = radius;
  49974. _this.getViewMatrix();
  49975. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  49976. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  49977. return _this;
  49978. }
  49979. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  49980. /**
  49981. * Defines the target point of the camera.
  49982. * The camera looks towards it form the radius distance.
  49983. */
  49984. get: function () {
  49985. return this._target;
  49986. },
  49987. set: function (value) {
  49988. this.setTarget(value);
  49989. },
  49990. enumerable: true,
  49991. configurable: true
  49992. });
  49993. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  49994. //-- begin properties for backward compatibility for inputs
  49995. /**
  49996. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  49997. */
  49998. get: function () {
  49999. var pointers = this.inputs.attached["pointers"];
  50000. if (pointers) {
  50001. return pointers.angularSensibilityX;
  50002. }
  50003. return 0;
  50004. },
  50005. set: function (value) {
  50006. var pointers = this.inputs.attached["pointers"];
  50007. if (pointers) {
  50008. pointers.angularSensibilityX = value;
  50009. }
  50010. },
  50011. enumerable: true,
  50012. configurable: true
  50013. });
  50014. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  50015. /**
  50016. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  50017. */
  50018. get: function () {
  50019. var pointers = this.inputs.attached["pointers"];
  50020. if (pointers) {
  50021. return pointers.angularSensibilityY;
  50022. }
  50023. return 0;
  50024. },
  50025. set: function (value) {
  50026. var pointers = this.inputs.attached["pointers"];
  50027. if (pointers) {
  50028. pointers.angularSensibilityY = value;
  50029. }
  50030. },
  50031. enumerable: true,
  50032. configurable: true
  50033. });
  50034. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  50035. /**
  50036. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  50037. */
  50038. get: function () {
  50039. var pointers = this.inputs.attached["pointers"];
  50040. if (pointers) {
  50041. return pointers.pinchPrecision;
  50042. }
  50043. return 0;
  50044. },
  50045. set: function (value) {
  50046. var pointers = this.inputs.attached["pointers"];
  50047. if (pointers) {
  50048. pointers.pinchPrecision = value;
  50049. }
  50050. },
  50051. enumerable: true,
  50052. configurable: true
  50053. });
  50054. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  50055. /**
  50056. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  50057. * It will be used instead of pinchDeltaPrecision if different from 0.
  50058. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  50059. */
  50060. get: function () {
  50061. var pointers = this.inputs.attached["pointers"];
  50062. if (pointers) {
  50063. return pointers.pinchDeltaPercentage;
  50064. }
  50065. return 0;
  50066. },
  50067. set: function (value) {
  50068. var pointers = this.inputs.attached["pointers"];
  50069. if (pointers) {
  50070. pointers.pinchDeltaPercentage = value;
  50071. }
  50072. },
  50073. enumerable: true,
  50074. configurable: true
  50075. });
  50076. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  50077. /**
  50078. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  50079. */
  50080. get: function () {
  50081. var pointers = this.inputs.attached["pointers"];
  50082. if (pointers) {
  50083. return pointers.panningSensibility;
  50084. }
  50085. return 0;
  50086. },
  50087. set: function (value) {
  50088. var pointers = this.inputs.attached["pointers"];
  50089. if (pointers) {
  50090. pointers.panningSensibility = value;
  50091. }
  50092. },
  50093. enumerable: true,
  50094. configurable: true
  50095. });
  50096. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  50097. /**
  50098. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  50099. */
  50100. get: function () {
  50101. var keyboard = this.inputs.attached["keyboard"];
  50102. if (keyboard) {
  50103. return keyboard.keysUp;
  50104. }
  50105. return [];
  50106. },
  50107. set: function (value) {
  50108. var keyboard = this.inputs.attached["keyboard"];
  50109. if (keyboard) {
  50110. keyboard.keysUp = value;
  50111. }
  50112. },
  50113. enumerable: true,
  50114. configurable: true
  50115. });
  50116. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  50117. /**
  50118. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  50119. */
  50120. get: function () {
  50121. var keyboard = this.inputs.attached["keyboard"];
  50122. if (keyboard) {
  50123. return keyboard.keysDown;
  50124. }
  50125. return [];
  50126. },
  50127. set: function (value) {
  50128. var keyboard = this.inputs.attached["keyboard"];
  50129. if (keyboard) {
  50130. keyboard.keysDown = value;
  50131. }
  50132. },
  50133. enumerable: true,
  50134. configurable: true
  50135. });
  50136. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  50137. /**
  50138. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  50139. */
  50140. get: function () {
  50141. var keyboard = this.inputs.attached["keyboard"];
  50142. if (keyboard) {
  50143. return keyboard.keysLeft;
  50144. }
  50145. return [];
  50146. },
  50147. set: function (value) {
  50148. var keyboard = this.inputs.attached["keyboard"];
  50149. if (keyboard) {
  50150. keyboard.keysLeft = value;
  50151. }
  50152. },
  50153. enumerable: true,
  50154. configurable: true
  50155. });
  50156. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  50157. /**
  50158. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  50159. */
  50160. get: function () {
  50161. var keyboard = this.inputs.attached["keyboard"];
  50162. if (keyboard) {
  50163. return keyboard.keysRight;
  50164. }
  50165. return [];
  50166. },
  50167. set: function (value) {
  50168. var keyboard = this.inputs.attached["keyboard"];
  50169. if (keyboard) {
  50170. keyboard.keysRight = value;
  50171. }
  50172. },
  50173. enumerable: true,
  50174. configurable: true
  50175. });
  50176. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  50177. /**
  50178. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  50179. */
  50180. get: function () {
  50181. var mousewheel = this.inputs.attached["mousewheel"];
  50182. if (mousewheel) {
  50183. return mousewheel.wheelPrecision;
  50184. }
  50185. return 0;
  50186. },
  50187. set: function (value) {
  50188. var mousewheel = this.inputs.attached["mousewheel"];
  50189. if (mousewheel) {
  50190. mousewheel.wheelPrecision = value;
  50191. }
  50192. },
  50193. enumerable: true,
  50194. configurable: true
  50195. });
  50196. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  50197. /**
  50198. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  50199. * It will be used instead of pinchDeltaPrecision if different from 0.
  50200. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  50201. */
  50202. get: function () {
  50203. var mousewheel = this.inputs.attached["mousewheel"];
  50204. if (mousewheel) {
  50205. return mousewheel.wheelDeltaPercentage;
  50206. }
  50207. return 0;
  50208. },
  50209. set: function (value) {
  50210. var mousewheel = this.inputs.attached["mousewheel"];
  50211. if (mousewheel) {
  50212. mousewheel.wheelDeltaPercentage = value;
  50213. }
  50214. },
  50215. enumerable: true,
  50216. configurable: true
  50217. });
  50218. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  50219. /**
  50220. * Gets the bouncing behavior of the camera if it has been enabled.
  50221. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  50222. */
  50223. get: function () {
  50224. return this._bouncingBehavior;
  50225. },
  50226. enumerable: true,
  50227. configurable: true
  50228. });
  50229. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  50230. /**
  50231. * Defines if the bouncing behavior of the camera is enabled on the camera.
  50232. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  50233. */
  50234. get: function () {
  50235. return this._bouncingBehavior != null;
  50236. },
  50237. set: function (value) {
  50238. if (value === this.useBouncingBehavior) {
  50239. return;
  50240. }
  50241. if (value) {
  50242. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  50243. this.addBehavior(this._bouncingBehavior);
  50244. }
  50245. else if (this._bouncingBehavior) {
  50246. this.removeBehavior(this._bouncingBehavior);
  50247. this._bouncingBehavior = null;
  50248. }
  50249. },
  50250. enumerable: true,
  50251. configurable: true
  50252. });
  50253. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  50254. /**
  50255. * Gets the framing behavior of the camera if it has been enabled.
  50256. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  50257. */
  50258. get: function () {
  50259. return this._framingBehavior;
  50260. },
  50261. enumerable: true,
  50262. configurable: true
  50263. });
  50264. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  50265. /**
  50266. * Defines if the framing behavior of the camera is enabled on the camera.
  50267. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  50268. */
  50269. get: function () {
  50270. return this._framingBehavior != null;
  50271. },
  50272. set: function (value) {
  50273. if (value === this.useFramingBehavior) {
  50274. return;
  50275. }
  50276. if (value) {
  50277. this._framingBehavior = new BABYLON.FramingBehavior();
  50278. this.addBehavior(this._framingBehavior);
  50279. }
  50280. else if (this._framingBehavior) {
  50281. this.removeBehavior(this._framingBehavior);
  50282. this._framingBehavior = null;
  50283. }
  50284. },
  50285. enumerable: true,
  50286. configurable: true
  50287. });
  50288. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  50289. /**
  50290. * Gets the auto rotation behavior of the camera if it has been enabled.
  50291. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  50292. */
  50293. get: function () {
  50294. return this._autoRotationBehavior;
  50295. },
  50296. enumerable: true,
  50297. configurable: true
  50298. });
  50299. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  50300. /**
  50301. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  50302. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  50303. */
  50304. get: function () {
  50305. return this._autoRotationBehavior != null;
  50306. },
  50307. set: function (value) {
  50308. if (value === this.useAutoRotationBehavior) {
  50309. return;
  50310. }
  50311. if (value) {
  50312. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  50313. this.addBehavior(this._autoRotationBehavior);
  50314. }
  50315. else if (this._autoRotationBehavior) {
  50316. this.removeBehavior(this._autoRotationBehavior);
  50317. this._autoRotationBehavior = null;
  50318. }
  50319. },
  50320. enumerable: true,
  50321. configurable: true
  50322. });
  50323. // Cache
  50324. /** @hidden */
  50325. ArcRotateCamera.prototype._initCache = function () {
  50326. _super.prototype._initCache.call(this);
  50327. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  50328. this._cache.alpha = undefined;
  50329. this._cache.beta = undefined;
  50330. this._cache.radius = undefined;
  50331. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  50332. };
  50333. /** @hidden */
  50334. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  50335. if (!ignoreParentClass) {
  50336. _super.prototype._updateCache.call(this);
  50337. }
  50338. this._cache._target.copyFrom(this._getTargetPosition());
  50339. this._cache.alpha = this.alpha;
  50340. this._cache.beta = this.beta;
  50341. this._cache.radius = this.radius;
  50342. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  50343. };
  50344. ArcRotateCamera.prototype._getTargetPosition = function () {
  50345. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  50346. var pos = this._targetHost.getAbsolutePosition();
  50347. if (this._targetBoundingCenter) {
  50348. pos.addToRef(this._targetBoundingCenter, this._target);
  50349. }
  50350. else {
  50351. this._target.copyFrom(pos);
  50352. }
  50353. }
  50354. var lockedTargetPosition = this._getLockedTargetPosition();
  50355. if (lockedTargetPosition) {
  50356. return lockedTargetPosition;
  50357. }
  50358. return this._target;
  50359. };
  50360. /**
  50361. * Stores the current state of the camera (alpha, beta, radius and target)
  50362. * @returns the camera itself
  50363. */
  50364. ArcRotateCamera.prototype.storeState = function () {
  50365. this._storedAlpha = this.alpha;
  50366. this._storedBeta = this.beta;
  50367. this._storedRadius = this.radius;
  50368. this._storedTarget = this._getTargetPosition().clone();
  50369. return _super.prototype.storeState.call(this);
  50370. };
  50371. /**
  50372. * @hidden
  50373. * Restored camera state. You must call storeState() first
  50374. */
  50375. ArcRotateCamera.prototype._restoreStateValues = function () {
  50376. if (!_super.prototype._restoreStateValues.call(this)) {
  50377. return false;
  50378. }
  50379. this.alpha = this._storedAlpha;
  50380. this.beta = this._storedBeta;
  50381. this.radius = this._storedRadius;
  50382. this.setTarget(this._storedTarget.clone());
  50383. this.inertialAlphaOffset = 0;
  50384. this.inertialBetaOffset = 0;
  50385. this.inertialRadiusOffset = 0;
  50386. this.inertialPanningX = 0;
  50387. this.inertialPanningY = 0;
  50388. return true;
  50389. };
  50390. // Synchronized
  50391. /** @hidden */
  50392. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  50393. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  50394. return false;
  50395. }
  50396. return this._cache._target.equals(this._getTargetPosition())
  50397. && this._cache.alpha === this.alpha
  50398. && this._cache.beta === this.beta
  50399. && this._cache.radius === this.radius
  50400. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  50401. };
  50402. /**
  50403. * Attached controls to the current camera.
  50404. * @param element Defines the element the controls should be listened from
  50405. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50406. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  50407. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  50408. */
  50409. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  50410. var _this = this;
  50411. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  50412. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  50413. this._useCtrlForPanning = useCtrlForPanning;
  50414. this._panningMouseButton = panningMouseButton;
  50415. this.inputs.attachElement(element, noPreventDefault);
  50416. this._reset = function () {
  50417. _this.inertialAlphaOffset = 0;
  50418. _this.inertialBetaOffset = 0;
  50419. _this.inertialRadiusOffset = 0;
  50420. _this.inertialPanningX = 0;
  50421. _this.inertialPanningY = 0;
  50422. };
  50423. };
  50424. /**
  50425. * Detach the current controls from the camera.
  50426. * The camera will stop reacting to inputs.
  50427. * @param element Defines the element to stop listening the inputs from
  50428. */
  50429. ArcRotateCamera.prototype.detachControl = function (element) {
  50430. this.inputs.detachElement(element);
  50431. if (this._reset) {
  50432. this._reset();
  50433. }
  50434. };
  50435. /** @hidden */
  50436. ArcRotateCamera.prototype._checkInputs = function () {
  50437. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  50438. if (this._collisionTriggered) {
  50439. return;
  50440. }
  50441. this.inputs.checkInputs();
  50442. // Inertia
  50443. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  50444. var inertialAlphaOffset = this.inertialAlphaOffset;
  50445. if (this.beta <= 0) {
  50446. inertialAlphaOffset *= -1;
  50447. }
  50448. if (this.getScene().useRightHandedSystem) {
  50449. inertialAlphaOffset *= -1;
  50450. }
  50451. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0) {
  50452. inertialAlphaOffset *= -1;
  50453. }
  50454. this.alpha += inertialAlphaOffset;
  50455. this.beta += this.inertialBetaOffset;
  50456. this.radius -= this.inertialRadiusOffset;
  50457. this.inertialAlphaOffset *= this.inertia;
  50458. this.inertialBetaOffset *= this.inertia;
  50459. this.inertialRadiusOffset *= this.inertia;
  50460. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon) {
  50461. this.inertialAlphaOffset = 0;
  50462. }
  50463. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon) {
  50464. this.inertialBetaOffset = 0;
  50465. }
  50466. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon) {
  50467. this.inertialRadiusOffset = 0;
  50468. }
  50469. }
  50470. // Panning inertia
  50471. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  50472. if (!this._localDirection) {
  50473. this._localDirection = BABYLON.Vector3.Zero();
  50474. this._transformedDirection = BABYLON.Vector3.Zero();
  50475. }
  50476. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  50477. this._localDirection.multiplyInPlace(this.panningAxis);
  50478. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  50479. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  50480. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  50481. if (!this.panningAxis.y) {
  50482. this._transformedDirection.y = 0;
  50483. }
  50484. if (!this._targetHost) {
  50485. if (this.panningDistanceLimit) {
  50486. this._transformedDirection.addInPlace(this._target);
  50487. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  50488. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  50489. this._target.copyFrom(this._transformedDirection);
  50490. }
  50491. }
  50492. else {
  50493. this._target.addInPlace(this._transformedDirection);
  50494. }
  50495. }
  50496. this.inertialPanningX *= this.panningInertia;
  50497. this.inertialPanningY *= this.panningInertia;
  50498. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon) {
  50499. this.inertialPanningX = 0;
  50500. }
  50501. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon) {
  50502. this.inertialPanningY = 0;
  50503. }
  50504. }
  50505. // Limits
  50506. this._checkLimits();
  50507. _super.prototype._checkInputs.call(this);
  50508. };
  50509. ArcRotateCamera.prototype._checkLimits = function () {
  50510. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  50511. if (this.allowUpsideDown && this.beta > Math.PI) {
  50512. this.beta = this.beta - (2 * Math.PI);
  50513. }
  50514. }
  50515. else {
  50516. if (this.beta < this.lowerBetaLimit) {
  50517. this.beta = this.lowerBetaLimit;
  50518. }
  50519. }
  50520. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  50521. if (this.allowUpsideDown && this.beta < -Math.PI) {
  50522. this.beta = this.beta + (2 * Math.PI);
  50523. }
  50524. }
  50525. else {
  50526. if (this.beta > this.upperBetaLimit) {
  50527. this.beta = this.upperBetaLimit;
  50528. }
  50529. }
  50530. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  50531. this.alpha = this.lowerAlphaLimit;
  50532. }
  50533. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  50534. this.alpha = this.upperAlphaLimit;
  50535. }
  50536. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  50537. this.radius = this.lowerRadiusLimit;
  50538. }
  50539. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  50540. this.radius = this.upperRadiusLimit;
  50541. }
  50542. };
  50543. /**
  50544. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  50545. */
  50546. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  50547. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  50548. this.radius = this._computationVector.length();
  50549. if (this.radius === 0) {
  50550. this.radius = 0.0001; // Just to avoid division by zero
  50551. }
  50552. // Alpha
  50553. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  50554. if (this._computationVector.z < 0) {
  50555. this.alpha = 2 * Math.PI - this.alpha;
  50556. }
  50557. // Beta
  50558. this.beta = Math.acos(this._computationVector.y / this.radius);
  50559. this._checkLimits();
  50560. };
  50561. /**
  50562. * Use a position to define the current camera related information like aplha, beta and radius
  50563. * @param position Defines the position to set the camera at
  50564. */
  50565. ArcRotateCamera.prototype.setPosition = function (position) {
  50566. if (this.position.equals(position)) {
  50567. return;
  50568. }
  50569. this.position.copyFrom(position);
  50570. this.rebuildAnglesAndRadius();
  50571. };
  50572. /**
  50573. * Defines the target the camera should look at.
  50574. * This will automatically adapt alpha beta and radius to fit within the new target.
  50575. * @param target Defines the new target as a Vector or a mesh
  50576. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  50577. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  50578. */
  50579. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  50580. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  50581. if (allowSamePosition === void 0) { allowSamePosition = false; }
  50582. if (target.getBoundingInfo) {
  50583. if (toBoundingCenter) {
  50584. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  50585. }
  50586. else {
  50587. this._targetBoundingCenter = null;
  50588. }
  50589. this._targetHost = target;
  50590. this._target = this._getTargetPosition();
  50591. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  50592. }
  50593. else {
  50594. var newTarget = target;
  50595. var currentTarget = this._getTargetPosition();
  50596. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  50597. return;
  50598. }
  50599. this._targetHost = null;
  50600. this._target = newTarget;
  50601. this._targetBoundingCenter = null;
  50602. this.onMeshTargetChangedObservable.notifyObservers(null);
  50603. }
  50604. this.rebuildAnglesAndRadius();
  50605. };
  50606. /** @hidden */
  50607. ArcRotateCamera.prototype._getViewMatrix = function () {
  50608. // Compute
  50609. var cosa = Math.cos(this.alpha);
  50610. var sina = Math.sin(this.alpha);
  50611. var cosb = Math.cos(this.beta);
  50612. var sinb = Math.sin(this.beta);
  50613. if (sinb === 0) {
  50614. sinb = 0.0001;
  50615. }
  50616. var target = this._getTargetPosition();
  50617. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  50618. target.addToRef(this._computationVector, this._newPosition);
  50619. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  50620. if (!this._collider) {
  50621. this._collider = new BABYLON.Collider();
  50622. }
  50623. this._collider._radius = this.collisionRadius;
  50624. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  50625. this._collisionTriggered = true;
  50626. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  50627. }
  50628. else {
  50629. this.position.copyFrom(this._newPosition);
  50630. var up = this.upVector;
  50631. if (this.allowUpsideDown && sinb < 0) {
  50632. up = up.clone();
  50633. up = up.negate();
  50634. }
  50635. this._computeViewMatrix(this.position, target, up);
  50636. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  50637. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  50638. }
  50639. this._currentTarget = target;
  50640. return this._viewMatrix;
  50641. };
  50642. /**
  50643. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  50644. * @param meshes Defines the mesh to zoom on
  50645. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  50646. */
  50647. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  50648. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  50649. meshes = meshes || this.getScene().meshes;
  50650. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  50651. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  50652. this.radius = distance * this.zoomOnFactor;
  50653. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  50654. };
  50655. /**
  50656. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  50657. * The target will be changed but the radius
  50658. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  50659. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  50660. */
  50661. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  50662. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  50663. var meshesOrMinMaxVector;
  50664. var distance;
  50665. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  50666. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  50667. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  50668. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  50669. }
  50670. else { //minMaxVector and distance
  50671. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  50672. meshesOrMinMaxVector = minMaxVectorAndDistance;
  50673. distance = minMaxVectorAndDistance.distance;
  50674. }
  50675. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  50676. if (!doNotUpdateMaxZ) {
  50677. this.maxZ = distance * 2;
  50678. }
  50679. };
  50680. /**
  50681. * @override
  50682. * Override Camera.createRigCamera
  50683. */
  50684. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  50685. var alphaShift = 0;
  50686. switch (this.cameraRigMode) {
  50687. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  50688. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  50689. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  50690. case BABYLON.Camera.RIG_MODE_VR:
  50691. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  50692. break;
  50693. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  50694. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  50695. break;
  50696. }
  50697. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  50698. rigCam._cameraRigParams = {};
  50699. return rigCam;
  50700. };
  50701. /**
  50702. * @hidden
  50703. * @override
  50704. * Override Camera._updateRigCameras
  50705. */
  50706. ArcRotateCamera.prototype._updateRigCameras = function () {
  50707. var camLeft = this._rigCameras[0];
  50708. var camRight = this._rigCameras[1];
  50709. camLeft.beta = camRight.beta = this.beta;
  50710. camLeft.radius = camRight.radius = this.radius;
  50711. switch (this.cameraRigMode) {
  50712. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  50713. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  50714. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  50715. case BABYLON.Camera.RIG_MODE_VR:
  50716. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  50717. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  50718. break;
  50719. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  50720. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  50721. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  50722. break;
  50723. }
  50724. _super.prototype._updateRigCameras.call(this);
  50725. };
  50726. /**
  50727. * Destroy the camera and release the current resources hold by it.
  50728. */
  50729. ArcRotateCamera.prototype.dispose = function () {
  50730. this.inputs.clear();
  50731. _super.prototype.dispose.call(this);
  50732. };
  50733. /**
  50734. * Gets the current object class name.
  50735. * @return the class name
  50736. */
  50737. ArcRotateCamera.prototype.getClassName = function () {
  50738. return "ArcRotateCamera";
  50739. };
  50740. __decorate([
  50741. BABYLON.serialize()
  50742. ], ArcRotateCamera.prototype, "alpha", void 0);
  50743. __decorate([
  50744. BABYLON.serialize()
  50745. ], ArcRotateCamera.prototype, "beta", void 0);
  50746. __decorate([
  50747. BABYLON.serialize()
  50748. ], ArcRotateCamera.prototype, "radius", void 0);
  50749. __decorate([
  50750. BABYLON.serializeAsVector3("target")
  50751. ], ArcRotateCamera.prototype, "_target", void 0);
  50752. __decorate([
  50753. BABYLON.serialize()
  50754. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  50755. __decorate([
  50756. BABYLON.serialize()
  50757. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  50758. __decorate([
  50759. BABYLON.serialize()
  50760. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  50761. __decorate([
  50762. BABYLON.serialize()
  50763. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  50764. __decorate([
  50765. BABYLON.serialize()
  50766. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  50767. __decorate([
  50768. BABYLON.serialize()
  50769. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  50770. __decorate([
  50771. BABYLON.serialize()
  50772. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  50773. __decorate([
  50774. BABYLON.serialize()
  50775. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  50776. __decorate([
  50777. BABYLON.serialize()
  50778. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  50779. __decorate([
  50780. BABYLON.serialize()
  50781. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  50782. __decorate([
  50783. BABYLON.serialize()
  50784. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  50785. __decorate([
  50786. BABYLON.serialize()
  50787. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  50788. __decorate([
  50789. BABYLON.serialize()
  50790. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  50791. __decorate([
  50792. BABYLON.serializeAsVector3()
  50793. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  50794. __decorate([
  50795. BABYLON.serialize()
  50796. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  50797. __decorate([
  50798. BABYLON.serialize()
  50799. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  50800. __decorate([
  50801. BABYLON.serialize()
  50802. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  50803. __decorate([
  50804. BABYLON.serialize()
  50805. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  50806. __decorate([
  50807. BABYLON.serialize()
  50808. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  50809. return ArcRotateCamera;
  50810. }(BABYLON.TargetCamera));
  50811. BABYLON.ArcRotateCamera = ArcRotateCamera;
  50812. })(BABYLON || (BABYLON = {}));
  50813. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  50814. var BABYLON;
  50815. (function (BABYLON) {
  50816. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  50817. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  50818. });
  50819. /**
  50820. * The HemisphericLight simulates the ambient environment light,
  50821. * so the passed direction is the light reflection direction, not the incoming direction.
  50822. */
  50823. var HemisphericLight = /** @class */ (function (_super) {
  50824. __extends(HemisphericLight, _super);
  50825. /**
  50826. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  50827. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  50828. * The HemisphericLight can't cast shadows.
  50829. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50830. * @param name The friendly name of the light
  50831. * @param direction The direction of the light reflection
  50832. * @param scene The scene the light belongs to
  50833. */
  50834. function HemisphericLight(name, direction, scene) {
  50835. var _this = _super.call(this, name, scene) || this;
  50836. /**
  50837. * The groundColor is the light in the opposite direction to the one specified during creation.
  50838. * 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.
  50839. */
  50840. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  50841. _this.direction = direction || BABYLON.Vector3.Up();
  50842. return _this;
  50843. }
  50844. HemisphericLight.prototype._buildUniformLayout = function () {
  50845. this._uniformBuffer.addUniform("vLightData", 4);
  50846. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50847. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50848. this._uniformBuffer.addUniform("vLightGround", 3);
  50849. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50850. this._uniformBuffer.addUniform("depthValues", 2);
  50851. this._uniformBuffer.create();
  50852. };
  50853. /**
  50854. * Returns the string "HemisphericLight".
  50855. * @return The class name
  50856. */
  50857. HemisphericLight.prototype.getClassName = function () {
  50858. return "HemisphericLight";
  50859. };
  50860. /**
  50861. * Sets the HemisphericLight direction towards the passed target (Vector3).
  50862. * Returns the updated direction.
  50863. * @param target The target the direction should point to
  50864. * @return The computed direction
  50865. */
  50866. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  50867. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  50868. return this.direction;
  50869. };
  50870. /**
  50871. * Returns the shadow generator associated to the light.
  50872. * @returns Always null for hemispheric lights because it does not support shadows.
  50873. */
  50874. HemisphericLight.prototype.getShadowGenerator = function () {
  50875. return null;
  50876. };
  50877. /**
  50878. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  50879. * @param effect The effect to update
  50880. * @param lightIndex The index of the light in the effect to update
  50881. * @returns The hemispheric light
  50882. */
  50883. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  50884. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50885. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  50886. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  50887. return this;
  50888. };
  50889. /**
  50890. * Computes the world matrix of the node
  50891. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  50892. * @param useWasUpdatedFlag defines a reserved property
  50893. * @returns the world matrix
  50894. */
  50895. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  50896. if (!this._worldMatrix) {
  50897. this._worldMatrix = BABYLON.Matrix.Identity();
  50898. }
  50899. return this._worldMatrix;
  50900. };
  50901. /**
  50902. * Returns the integer 3.
  50903. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50904. */
  50905. HemisphericLight.prototype.getTypeID = function () {
  50906. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  50907. };
  50908. /**
  50909. * Prepares the list of defines specific to the light type.
  50910. * @param defines the list of defines
  50911. * @param lightIndex defines the index of the light for the effect
  50912. */
  50913. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50914. defines["HEMILIGHT" + lightIndex] = true;
  50915. };
  50916. __decorate([
  50917. BABYLON.serializeAsColor3()
  50918. ], HemisphericLight.prototype, "groundColor", void 0);
  50919. __decorate([
  50920. BABYLON.serializeAsVector3()
  50921. ], HemisphericLight.prototype, "direction", void 0);
  50922. return HemisphericLight;
  50923. }(BABYLON.Light));
  50924. BABYLON.HemisphericLight = HemisphericLight;
  50925. })(BABYLON || (BABYLON = {}));
  50926. //# sourceMappingURL=babylon.hemisphericLight.js.map
  50927. var BABYLON;
  50928. (function (BABYLON) {
  50929. /**
  50930. * Base implementation IShadowLight
  50931. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  50932. */
  50933. var ShadowLight = /** @class */ (function (_super) {
  50934. __extends(ShadowLight, _super);
  50935. function ShadowLight() {
  50936. var _this = _super !== null && _super.apply(this, arguments) || this;
  50937. _this._needProjectionMatrixCompute = true;
  50938. return _this;
  50939. }
  50940. ShadowLight.prototype._setPosition = function (value) {
  50941. this._position = value;
  50942. };
  50943. Object.defineProperty(ShadowLight.prototype, "position", {
  50944. /**
  50945. * Sets the position the shadow will be casted from. Also use as the light position for both
  50946. * point and spot lights.
  50947. */
  50948. get: function () {
  50949. return this._position;
  50950. },
  50951. /**
  50952. * Sets the position the shadow will be casted from. Also use as the light position for both
  50953. * point and spot lights.
  50954. */
  50955. set: function (value) {
  50956. this._setPosition(value);
  50957. },
  50958. enumerable: true,
  50959. configurable: true
  50960. });
  50961. ShadowLight.prototype._setDirection = function (value) {
  50962. this._direction = value;
  50963. };
  50964. Object.defineProperty(ShadowLight.prototype, "direction", {
  50965. /**
  50966. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  50967. * Also use as the light direction on spot and directional lights.
  50968. */
  50969. get: function () {
  50970. return this._direction;
  50971. },
  50972. /**
  50973. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  50974. * Also use as the light direction on spot and directional lights.
  50975. */
  50976. set: function (value) {
  50977. this._setDirection(value);
  50978. },
  50979. enumerable: true,
  50980. configurable: true
  50981. });
  50982. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  50983. /**
  50984. * Gets the shadow projection clipping minimum z value.
  50985. */
  50986. get: function () {
  50987. return this._shadowMinZ;
  50988. },
  50989. /**
  50990. * Sets the shadow projection clipping minimum z value.
  50991. */
  50992. set: function (value) {
  50993. this._shadowMinZ = value;
  50994. this.forceProjectionMatrixCompute();
  50995. },
  50996. enumerable: true,
  50997. configurable: true
  50998. });
  50999. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  51000. /**
  51001. * Sets the shadow projection clipping maximum z value.
  51002. */
  51003. get: function () {
  51004. return this._shadowMaxZ;
  51005. },
  51006. /**
  51007. * Gets the shadow projection clipping maximum z value.
  51008. */
  51009. set: function (value) {
  51010. this._shadowMaxZ = value;
  51011. this.forceProjectionMatrixCompute();
  51012. },
  51013. enumerable: true,
  51014. configurable: true
  51015. });
  51016. /**
  51017. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  51018. * @returns true if the information has been computed, false if it does not need to (no parenting)
  51019. */
  51020. ShadowLight.prototype.computeTransformedInformation = function () {
  51021. if (this.parent && this.parent.getWorldMatrix) {
  51022. if (!this.transformedPosition) {
  51023. this.transformedPosition = BABYLON.Vector3.Zero();
  51024. }
  51025. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  51026. // In case the direction is present.
  51027. if (this.direction) {
  51028. if (!this.transformedDirection) {
  51029. this.transformedDirection = BABYLON.Vector3.Zero();
  51030. }
  51031. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  51032. }
  51033. return true;
  51034. }
  51035. return false;
  51036. };
  51037. /**
  51038. * Return the depth scale used for the shadow map.
  51039. * @returns the depth scale.
  51040. */
  51041. ShadowLight.prototype.getDepthScale = function () {
  51042. return 50.0;
  51043. };
  51044. /**
  51045. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  51046. * @param faceIndex The index of the face we are computed the direction to generate shadow
  51047. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  51048. */
  51049. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  51050. return this.transformedDirection ? this.transformedDirection : this.direction;
  51051. };
  51052. /**
  51053. * Returns the ShadowLight absolute position in the World.
  51054. * @returns the position vector in world space
  51055. */
  51056. ShadowLight.prototype.getAbsolutePosition = function () {
  51057. return this.transformedPosition ? this.transformedPosition : this.position;
  51058. };
  51059. /**
  51060. * Sets the ShadowLight direction toward the passed target.
  51061. * @param target The point tot target in local space
  51062. * @returns the updated ShadowLight direction
  51063. */
  51064. ShadowLight.prototype.setDirectionToTarget = function (target) {
  51065. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  51066. return this.direction;
  51067. };
  51068. /**
  51069. * Returns the light rotation in euler definition.
  51070. * @returns the x y z rotation in local space.
  51071. */
  51072. ShadowLight.prototype.getRotation = function () {
  51073. this.direction.normalize();
  51074. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  51075. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  51076. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  51077. };
  51078. /**
  51079. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  51080. * @returns true if a cube texture needs to be use
  51081. */
  51082. ShadowLight.prototype.needCube = function () {
  51083. return false;
  51084. };
  51085. /**
  51086. * Detects if the projection matrix requires to be recomputed this frame.
  51087. * @returns true if it requires to be recomputed otherwise, false.
  51088. */
  51089. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  51090. return this._needProjectionMatrixCompute;
  51091. };
  51092. /**
  51093. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  51094. */
  51095. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  51096. this._needProjectionMatrixCompute = true;
  51097. };
  51098. /** @hidden */
  51099. ShadowLight.prototype._initCache = function () {
  51100. _super.prototype._initCache.call(this);
  51101. this._cache.position = BABYLON.Vector3.Zero();
  51102. };
  51103. /** @hidden */
  51104. ShadowLight.prototype._isSynchronized = function () {
  51105. if (!this._cache.position.equals(this.position)) {
  51106. return false;
  51107. }
  51108. return true;
  51109. };
  51110. /**
  51111. * Computes the world matrix of the node
  51112. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  51113. * @returns the world matrix
  51114. */
  51115. ShadowLight.prototype.computeWorldMatrix = function (force) {
  51116. if (!force && this.isSynchronized()) {
  51117. this._currentRenderId = this.getScene().getRenderId();
  51118. return this._worldMatrix;
  51119. }
  51120. this._updateCache();
  51121. this._cache.position.copyFrom(this.position);
  51122. if (!this._worldMatrix) {
  51123. this._worldMatrix = BABYLON.Matrix.Identity();
  51124. }
  51125. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  51126. if (this.parent && this.parent.getWorldMatrix) {
  51127. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  51128. this._markSyncedWithParent();
  51129. }
  51130. // Cache the determinant
  51131. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  51132. return this._worldMatrix;
  51133. };
  51134. /**
  51135. * Gets the minZ used for shadow according to both the scene and the light.
  51136. * @param activeCamera The camera we are returning the min for
  51137. * @returns the depth min z
  51138. */
  51139. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  51140. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  51141. };
  51142. /**
  51143. * Gets the maxZ used for shadow according to both the scene and the light.
  51144. * @param activeCamera The camera we are returning the max for
  51145. * @returns the depth max z
  51146. */
  51147. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  51148. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  51149. };
  51150. /**
  51151. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  51152. * @param matrix The materix to updated with the projection information
  51153. * @param viewMatrix The transform matrix of the light
  51154. * @param renderList The list of mesh to render in the map
  51155. * @returns The current light
  51156. */
  51157. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51158. if (this.customProjectionMatrixBuilder) {
  51159. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  51160. }
  51161. else {
  51162. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  51163. }
  51164. return this;
  51165. };
  51166. __decorate([
  51167. BABYLON.serializeAsVector3()
  51168. ], ShadowLight.prototype, "position", null);
  51169. __decorate([
  51170. BABYLON.serializeAsVector3()
  51171. ], ShadowLight.prototype, "direction", null);
  51172. __decorate([
  51173. BABYLON.serialize()
  51174. ], ShadowLight.prototype, "shadowMinZ", null);
  51175. __decorate([
  51176. BABYLON.serialize()
  51177. ], ShadowLight.prototype, "shadowMaxZ", null);
  51178. return ShadowLight;
  51179. }(BABYLON.Light));
  51180. BABYLON.ShadowLight = ShadowLight;
  51181. })(BABYLON || (BABYLON = {}));
  51182. //# sourceMappingURL=babylon.shadowLight.js.map
  51183. var BABYLON;
  51184. (function (BABYLON) {
  51185. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  51186. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  51187. });
  51188. /**
  51189. * A point light is a light defined by an unique point in world space.
  51190. * The light is emitted in every direction from this point.
  51191. * A good example of a point light is a standard light bulb.
  51192. * Documentation: https://doc.babylonjs.com/babylon101/lights
  51193. */
  51194. var PointLight = /** @class */ (function (_super) {
  51195. __extends(PointLight, _super);
  51196. /**
  51197. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  51198. * A PointLight emits the light in every direction.
  51199. * It can cast shadows.
  51200. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  51201. * ```javascript
  51202. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  51203. * ```
  51204. * Documentation : http://doc.babylonjs.com/tutorials/lights
  51205. * @param name The light friendly name
  51206. * @param position The position of the point light in the scene
  51207. * @param scene The scene the lights belongs to
  51208. */
  51209. function PointLight(name, position, scene) {
  51210. var _this = _super.call(this, name, scene) || this;
  51211. _this._shadowAngle = Math.PI / 2;
  51212. _this.position = position;
  51213. return _this;
  51214. }
  51215. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  51216. /**
  51217. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51218. * This specifies what angle the shadow will use to be created.
  51219. *
  51220. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  51221. */
  51222. get: function () {
  51223. return this._shadowAngle;
  51224. },
  51225. /**
  51226. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51227. * This specifies what angle the shadow will use to be created.
  51228. *
  51229. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  51230. */
  51231. set: function (value) {
  51232. this._shadowAngle = value;
  51233. this.forceProjectionMatrixCompute();
  51234. },
  51235. enumerable: true,
  51236. configurable: true
  51237. });
  51238. Object.defineProperty(PointLight.prototype, "direction", {
  51239. /**
  51240. * Gets the direction if it has been set.
  51241. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51242. */
  51243. get: function () {
  51244. return this._direction;
  51245. },
  51246. /**
  51247. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51248. */
  51249. set: function (value) {
  51250. var previousNeedCube = this.needCube();
  51251. this._direction = value;
  51252. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  51253. this._shadowGenerator.recreateShadowMap();
  51254. }
  51255. },
  51256. enumerable: true,
  51257. configurable: true
  51258. });
  51259. /**
  51260. * Returns the string "PointLight"
  51261. * @returns the class name
  51262. */
  51263. PointLight.prototype.getClassName = function () {
  51264. return "PointLight";
  51265. };
  51266. /**
  51267. * Returns the integer 0.
  51268. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  51269. */
  51270. PointLight.prototype.getTypeID = function () {
  51271. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  51272. };
  51273. /**
  51274. * Specifies wether or not the shadowmap should be a cube texture.
  51275. * @returns true if the shadowmap needs to be a cube texture.
  51276. */
  51277. PointLight.prototype.needCube = function () {
  51278. return !this.direction;
  51279. };
  51280. /**
  51281. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  51282. * @param faceIndex The index of the face we are computed the direction to generate shadow
  51283. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  51284. */
  51285. PointLight.prototype.getShadowDirection = function (faceIndex) {
  51286. if (this.direction) {
  51287. return _super.prototype.getShadowDirection.call(this, faceIndex);
  51288. }
  51289. else {
  51290. switch (faceIndex) {
  51291. case 0:
  51292. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  51293. case 1:
  51294. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  51295. case 2:
  51296. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  51297. case 3:
  51298. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  51299. case 4:
  51300. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  51301. case 5:
  51302. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  51303. }
  51304. }
  51305. return BABYLON.Vector3.Zero();
  51306. };
  51307. /**
  51308. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  51309. * - fov = PI / 2
  51310. * - aspect ratio : 1.0
  51311. * - z-near and far equal to the active camera minZ and maxZ.
  51312. * Returns the PointLight.
  51313. */
  51314. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51315. var activeCamera = this.getScene().activeCamera;
  51316. if (!activeCamera) {
  51317. return;
  51318. }
  51319. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  51320. };
  51321. PointLight.prototype._buildUniformLayout = function () {
  51322. this._uniformBuffer.addUniform("vLightData", 4);
  51323. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51324. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51325. this._uniformBuffer.addUniform("vLightFalloff", 4);
  51326. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51327. this._uniformBuffer.addUniform("depthValues", 2);
  51328. this._uniformBuffer.create();
  51329. };
  51330. /**
  51331. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  51332. * @param effect The effect to update
  51333. * @param lightIndex The index of the light in the effect to update
  51334. * @returns The point light
  51335. */
  51336. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  51337. if (this.computeTransformedInformation()) {
  51338. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  51339. }
  51340. else {
  51341. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  51342. }
  51343. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  51344. return this;
  51345. };
  51346. /**
  51347. * Prepares the list of defines specific to the light type.
  51348. * @param defines the list of defines
  51349. * @param lightIndex defines the index of the light for the effect
  51350. */
  51351. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51352. defines["POINTLIGHT" + lightIndex] = true;
  51353. };
  51354. __decorate([
  51355. BABYLON.serialize()
  51356. ], PointLight.prototype, "shadowAngle", null);
  51357. return PointLight;
  51358. }(BABYLON.ShadowLight));
  51359. BABYLON.PointLight = PointLight;
  51360. })(BABYLON || (BABYLON = {}));
  51361. //# sourceMappingURL=babylon.pointLight.js.map
  51362. var BABYLON;
  51363. (function (BABYLON) {
  51364. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  51365. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  51366. });
  51367. /**
  51368. * A directional light is defined by a direction (what a surprise!).
  51369. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  51370. * 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.
  51371. * Documentation: https://doc.babylonjs.com/babylon101/lights
  51372. */
  51373. var DirectionalLight = /** @class */ (function (_super) {
  51374. __extends(DirectionalLight, _super);
  51375. /**
  51376. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  51377. * The directional light is emitted from everywhere in the given direction.
  51378. * It can cast shadows.
  51379. * Documentation : http://doc.babylonjs.com/tutorials/lights
  51380. * @param name The friendly name of the light
  51381. * @param direction The direction of the light
  51382. * @param scene The scene the light belongs to
  51383. */
  51384. function DirectionalLight(name, direction, scene) {
  51385. var _this = _super.call(this, name, scene) || this;
  51386. _this._shadowFrustumSize = 0;
  51387. _this._shadowOrthoScale = 0.1;
  51388. /**
  51389. * Automatically compute the projection matrix to best fit (including all the casters)
  51390. * on each frame.
  51391. */
  51392. _this.autoUpdateExtends = true;
  51393. // Cache
  51394. _this._orthoLeft = Number.MAX_VALUE;
  51395. _this._orthoRight = Number.MIN_VALUE;
  51396. _this._orthoTop = Number.MIN_VALUE;
  51397. _this._orthoBottom = Number.MAX_VALUE;
  51398. _this.position = direction.scale(-1.0);
  51399. _this.direction = direction;
  51400. return _this;
  51401. }
  51402. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  51403. /**
  51404. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  51405. */
  51406. get: function () {
  51407. return this._shadowFrustumSize;
  51408. },
  51409. /**
  51410. * Specifies a fix frustum size for the shadow generation.
  51411. */
  51412. set: function (value) {
  51413. this._shadowFrustumSize = value;
  51414. this.forceProjectionMatrixCompute();
  51415. },
  51416. enumerable: true,
  51417. configurable: true
  51418. });
  51419. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  51420. /**
  51421. * Gets the shadow projection scale against the optimal computed one.
  51422. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  51423. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  51424. */
  51425. get: function () {
  51426. return this._shadowOrthoScale;
  51427. },
  51428. /**
  51429. * Sets the shadow projection scale against the optimal computed one.
  51430. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  51431. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  51432. */
  51433. set: function (value) {
  51434. this._shadowOrthoScale = value;
  51435. this.forceProjectionMatrixCompute();
  51436. },
  51437. enumerable: true,
  51438. configurable: true
  51439. });
  51440. /**
  51441. * Returns the string "DirectionalLight".
  51442. * @return The class name
  51443. */
  51444. DirectionalLight.prototype.getClassName = function () {
  51445. return "DirectionalLight";
  51446. };
  51447. /**
  51448. * Returns the integer 1.
  51449. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  51450. */
  51451. DirectionalLight.prototype.getTypeID = function () {
  51452. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  51453. };
  51454. /**
  51455. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  51456. * Returns the DirectionalLight Shadow projection matrix.
  51457. */
  51458. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51459. if (this.shadowFrustumSize > 0) {
  51460. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  51461. }
  51462. else {
  51463. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  51464. }
  51465. };
  51466. /**
  51467. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  51468. * Returns the DirectionalLight Shadow projection matrix.
  51469. */
  51470. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  51471. var activeCamera = this.getScene().activeCamera;
  51472. if (!activeCamera) {
  51473. return;
  51474. }
  51475. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  51476. };
  51477. /**
  51478. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  51479. * Returns the DirectionalLight Shadow projection matrix.
  51480. */
  51481. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51482. var activeCamera = this.getScene().activeCamera;
  51483. if (!activeCamera) {
  51484. return;
  51485. }
  51486. // Check extends
  51487. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  51488. var tempVector3 = BABYLON.Vector3.Zero();
  51489. this._orthoLeft = Number.MAX_VALUE;
  51490. this._orthoRight = Number.MIN_VALUE;
  51491. this._orthoTop = Number.MIN_VALUE;
  51492. this._orthoBottom = Number.MAX_VALUE;
  51493. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  51494. var mesh = renderList[meshIndex];
  51495. if (!mesh) {
  51496. continue;
  51497. }
  51498. var boundingInfo = mesh.getBoundingInfo();
  51499. var boundingBox = boundingInfo.boundingBox;
  51500. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  51501. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  51502. if (tempVector3.x < this._orthoLeft) {
  51503. this._orthoLeft = tempVector3.x;
  51504. }
  51505. if (tempVector3.y < this._orthoBottom) {
  51506. this._orthoBottom = tempVector3.y;
  51507. }
  51508. if (tempVector3.x > this._orthoRight) {
  51509. this._orthoRight = tempVector3.x;
  51510. }
  51511. if (tempVector3.y > this._orthoTop) {
  51512. this._orthoTop = tempVector3.y;
  51513. }
  51514. }
  51515. }
  51516. }
  51517. var xOffset = this._orthoRight - this._orthoLeft;
  51518. var yOffset = this._orthoTop - this._orthoBottom;
  51519. 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);
  51520. };
  51521. DirectionalLight.prototype._buildUniformLayout = function () {
  51522. this._uniformBuffer.addUniform("vLightData", 4);
  51523. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51524. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51525. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51526. this._uniformBuffer.addUniform("depthValues", 2);
  51527. this._uniformBuffer.create();
  51528. };
  51529. /**
  51530. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  51531. * @param effect The effect to update
  51532. * @param lightIndex The index of the light in the effect to update
  51533. * @returns The directional light
  51534. */
  51535. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  51536. if (this.computeTransformedInformation()) {
  51537. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  51538. return this;
  51539. }
  51540. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  51541. return this;
  51542. };
  51543. /**
  51544. * Gets the minZ used for shadow according to both the scene and the light.
  51545. *
  51546. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  51547. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  51548. * @param activeCamera The camera we are returning the min for
  51549. * @returns the depth min z
  51550. */
  51551. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  51552. return 1;
  51553. };
  51554. /**
  51555. * Gets the maxZ used for shadow according to both the scene and the light.
  51556. *
  51557. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  51558. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  51559. * @param activeCamera The camera we are returning the max for
  51560. * @returns the depth max z
  51561. */
  51562. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  51563. return 1;
  51564. };
  51565. /**
  51566. * Prepares the list of defines specific to the light type.
  51567. * @param defines the list of defines
  51568. * @param lightIndex defines the index of the light for the effect
  51569. */
  51570. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51571. defines["DIRLIGHT" + lightIndex] = true;
  51572. };
  51573. __decorate([
  51574. BABYLON.serialize()
  51575. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  51576. __decorate([
  51577. BABYLON.serialize()
  51578. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  51579. __decorate([
  51580. BABYLON.serialize()
  51581. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  51582. return DirectionalLight;
  51583. }(BABYLON.ShadowLight));
  51584. BABYLON.DirectionalLight = DirectionalLight;
  51585. })(BABYLON || (BABYLON = {}));
  51586. //# sourceMappingURL=babylon.directionalLight.js.map
  51587. var BABYLON;
  51588. (function (BABYLON) {
  51589. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  51590. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  51591. });
  51592. /**
  51593. * A spot light is defined by a position, a direction, an angle, and an exponent.
  51594. * These values define a cone of light starting from the position, emitting toward the direction.
  51595. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  51596. * and the exponent defines the speed of the decay of the light with distance (reach).
  51597. * Documentation: https://doc.babylonjs.com/babylon101/lights
  51598. */
  51599. var SpotLight = /** @class */ (function (_super) {
  51600. __extends(SpotLight, _super);
  51601. /**
  51602. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  51603. * It can cast shadows.
  51604. * Documentation : http://doc.babylonjs.com/tutorials/lights
  51605. * @param name The light friendly name
  51606. * @param position The position of the spot light in the scene
  51607. * @param direction The direction of the light in the scene
  51608. * @param angle The cone angle of the light in Radians
  51609. * @param exponent The light decay speed with the distance from the emission spot
  51610. * @param scene The scene the lights belongs to
  51611. */
  51612. function SpotLight(name, position, direction, angle, exponent, scene) {
  51613. var _this = _super.call(this, name, scene) || this;
  51614. _this._innerAngle = 0;
  51615. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  51616. _this._projectionTextureLightNear = 1e-6;
  51617. _this._projectionTextureLightFar = 1000.0;
  51618. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  51619. _this._projectionTextureViewLightDirty = true;
  51620. _this._projectionTextureProjectionLightDirty = true;
  51621. _this._projectionTextureDirty = true;
  51622. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  51623. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  51624. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  51625. _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);
  51626. _this.position = position;
  51627. _this.direction = direction;
  51628. _this.angle = angle;
  51629. _this.exponent = exponent;
  51630. return _this;
  51631. }
  51632. Object.defineProperty(SpotLight.prototype, "angle", {
  51633. /**
  51634. * Gets the cone angle of the spot light in Radians.
  51635. */
  51636. get: function () {
  51637. return this._angle;
  51638. },
  51639. /**
  51640. * Sets the cone angle of the spot light in Radians.
  51641. */
  51642. set: function (value) {
  51643. this._angle = value;
  51644. this._cosHalfAngle = Math.cos(value * 0.5);
  51645. this._projectionTextureProjectionLightDirty = true;
  51646. this.forceProjectionMatrixCompute();
  51647. this._computeAngleValues();
  51648. },
  51649. enumerable: true,
  51650. configurable: true
  51651. });
  51652. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  51653. /**
  51654. * Only used in gltf falloff mode, this defines the angle where
  51655. * the directional falloff will start before cutting at angle which could be seen
  51656. * as outer angle.
  51657. */
  51658. get: function () {
  51659. return this._innerAngle;
  51660. },
  51661. /**
  51662. * Only used in gltf falloff mode, this defines the angle where
  51663. * the directional falloff will start before cutting at angle which could be seen
  51664. * as outer angle.
  51665. */
  51666. set: function (value) {
  51667. this._innerAngle = value;
  51668. this._computeAngleValues();
  51669. },
  51670. enumerable: true,
  51671. configurable: true
  51672. });
  51673. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  51674. /**
  51675. * Allows scaling the angle of the light for shadow generation only.
  51676. */
  51677. get: function () {
  51678. return this._shadowAngleScale;
  51679. },
  51680. /**
  51681. * Allows scaling the angle of the light for shadow generation only.
  51682. */
  51683. set: function (value) {
  51684. this._shadowAngleScale = value;
  51685. this.forceProjectionMatrixCompute();
  51686. },
  51687. enumerable: true,
  51688. configurable: true
  51689. });
  51690. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  51691. /**
  51692. * Allows reading the projecton texture
  51693. */
  51694. get: function () {
  51695. return this._projectionTextureMatrix;
  51696. },
  51697. enumerable: true,
  51698. configurable: true
  51699. });
  51700. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  51701. /**
  51702. * Gets the near clip of the Spotlight for texture projection.
  51703. */
  51704. get: function () {
  51705. return this._projectionTextureLightNear;
  51706. },
  51707. /**
  51708. * Sets the near clip of the Spotlight for texture projection.
  51709. */
  51710. set: function (value) {
  51711. this._projectionTextureLightNear = value;
  51712. this._projectionTextureProjectionLightDirty = true;
  51713. },
  51714. enumerable: true,
  51715. configurable: true
  51716. });
  51717. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  51718. /**
  51719. * Gets the far clip of the Spotlight for texture projection.
  51720. */
  51721. get: function () {
  51722. return this._projectionTextureLightFar;
  51723. },
  51724. /**
  51725. * Sets the far clip of the Spotlight for texture projection.
  51726. */
  51727. set: function (value) {
  51728. this._projectionTextureLightFar = value;
  51729. this._projectionTextureProjectionLightDirty = true;
  51730. },
  51731. enumerable: true,
  51732. configurable: true
  51733. });
  51734. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  51735. /**
  51736. * Gets the Up vector of the Spotlight for texture projection.
  51737. */
  51738. get: function () {
  51739. return this._projectionTextureUpDirection;
  51740. },
  51741. /**
  51742. * Sets the Up vector of the Spotlight for texture projection.
  51743. */
  51744. set: function (value) {
  51745. this._projectionTextureUpDirection = value;
  51746. this._projectionTextureProjectionLightDirty = true;
  51747. },
  51748. enumerable: true,
  51749. configurable: true
  51750. });
  51751. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  51752. /**
  51753. * Gets the projection texture of the light.
  51754. */
  51755. get: function () {
  51756. return this._projectionTexture;
  51757. },
  51758. /**
  51759. * Sets the projection texture of the light.
  51760. */
  51761. set: function (value) {
  51762. this._projectionTexture = value;
  51763. this._projectionTextureDirty = true;
  51764. },
  51765. enumerable: true,
  51766. configurable: true
  51767. });
  51768. /**
  51769. * Returns the string "SpotLight".
  51770. * @returns the class name
  51771. */
  51772. SpotLight.prototype.getClassName = function () {
  51773. return "SpotLight";
  51774. };
  51775. /**
  51776. * Returns the integer 2.
  51777. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  51778. */
  51779. SpotLight.prototype.getTypeID = function () {
  51780. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  51781. };
  51782. /**
  51783. * Overrides the direction setter to recompute the projection texture view light Matrix.
  51784. */
  51785. SpotLight.prototype._setDirection = function (value) {
  51786. _super.prototype._setDirection.call(this, value);
  51787. this._projectionTextureViewLightDirty = true;
  51788. };
  51789. /**
  51790. * Overrides the position setter to recompute the projection texture view light Matrix.
  51791. */
  51792. SpotLight.prototype._setPosition = function (value) {
  51793. _super.prototype._setPosition.call(this, value);
  51794. this._projectionTextureViewLightDirty = true;
  51795. };
  51796. /**
  51797. * 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.
  51798. * Returns the SpotLight.
  51799. */
  51800. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51801. var activeCamera = this.getScene().activeCamera;
  51802. if (!activeCamera) {
  51803. return;
  51804. }
  51805. this._shadowAngleScale = this._shadowAngleScale || 1;
  51806. var angle = this._shadowAngleScale * this._angle;
  51807. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  51808. };
  51809. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  51810. this._projectionTextureViewLightDirty = false;
  51811. this._projectionTextureDirty = true;
  51812. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  51813. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  51814. };
  51815. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  51816. this._projectionTextureProjectionLightDirty = false;
  51817. this._projectionTextureDirty = true;
  51818. var light_far = this.projectionTextureLightFar;
  51819. var light_near = this.projectionTextureLightNear;
  51820. var P = light_far / (light_far - light_near);
  51821. var Q = -P * light_near;
  51822. var S = 1.0 / Math.tan(this._angle / 2.0);
  51823. var A = 1.0;
  51824. 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);
  51825. };
  51826. /**
  51827. * Main function for light texture projection matrix computing.
  51828. */
  51829. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  51830. this._projectionTextureDirty = false;
  51831. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  51832. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  51833. };
  51834. SpotLight.prototype._buildUniformLayout = function () {
  51835. this._uniformBuffer.addUniform("vLightData", 4);
  51836. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51837. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51838. this._uniformBuffer.addUniform("vLightDirection", 3);
  51839. this._uniformBuffer.addUniform("vLightFalloff", 4);
  51840. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51841. this._uniformBuffer.addUniform("depthValues", 2);
  51842. this._uniformBuffer.create();
  51843. };
  51844. SpotLight.prototype._computeAngleValues = function () {
  51845. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  51846. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  51847. };
  51848. /**
  51849. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  51850. * @param effect The effect to update
  51851. * @param lightIndex The index of the light in the effect to update
  51852. * @returns The spot light
  51853. */
  51854. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  51855. var normalizeDirection;
  51856. if (this.computeTransformedInformation()) {
  51857. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  51858. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  51859. }
  51860. else {
  51861. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  51862. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  51863. }
  51864. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  51865. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  51866. if (this.projectionTexture && this.projectionTexture.isReady()) {
  51867. if (this._projectionTextureViewLightDirty) {
  51868. this._computeProjectionTextureViewLightMatrix();
  51869. }
  51870. if (this._projectionTextureProjectionLightDirty) {
  51871. this._computeProjectionTextureProjectionLightMatrix();
  51872. }
  51873. if (this._projectionTextureDirty) {
  51874. this._computeProjectionTextureMatrix();
  51875. }
  51876. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  51877. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  51878. }
  51879. return this;
  51880. };
  51881. /**
  51882. * Disposes the light and the associated resources.
  51883. */
  51884. SpotLight.prototype.dispose = function () {
  51885. _super.prototype.dispose.call(this);
  51886. if (this._projectionTexture) {
  51887. this._projectionTexture.dispose();
  51888. }
  51889. };
  51890. /**
  51891. * Prepares the list of defines specific to the light type.
  51892. * @param defines the list of defines
  51893. * @param lightIndex defines the index of the light for the effect
  51894. */
  51895. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51896. defines["SPOTLIGHT" + lightIndex] = true;
  51897. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  51898. };
  51899. __decorate([
  51900. BABYLON.serialize()
  51901. ], SpotLight.prototype, "angle", null);
  51902. __decorate([
  51903. BABYLON.serialize()
  51904. ], SpotLight.prototype, "innerAngle", null);
  51905. __decorate([
  51906. BABYLON.serialize()
  51907. ], SpotLight.prototype, "shadowAngleScale", null);
  51908. __decorate([
  51909. BABYLON.serialize()
  51910. ], SpotLight.prototype, "exponent", void 0);
  51911. __decorate([
  51912. BABYLON.serialize()
  51913. ], SpotLight.prototype, "projectionTextureLightNear", null);
  51914. __decorate([
  51915. BABYLON.serialize()
  51916. ], SpotLight.prototype, "projectionTextureLightFar", null);
  51917. __decorate([
  51918. BABYLON.serialize()
  51919. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  51920. __decorate([
  51921. BABYLON.serializeAsTexture("projectedLightTexture")
  51922. ], SpotLight.prototype, "_projectionTexture", void 0);
  51923. return SpotLight;
  51924. }(BABYLON.ShadowLight));
  51925. BABYLON.SpotLight = SpotLight;
  51926. })(BABYLON || (BABYLON = {}));
  51927. //# sourceMappingURL=babylon.spotLight.js.map
  51928. var BABYLON;
  51929. (function (BABYLON) {
  51930. /**
  51931. * Class used to override all child animations of a given target
  51932. */
  51933. var AnimationPropertiesOverride = /** @class */ (function () {
  51934. function AnimationPropertiesOverride() {
  51935. /**
  51936. * Gets or sets a value indicating if animation blending must be used
  51937. */
  51938. this.enableBlending = false;
  51939. /**
  51940. * Gets or sets the blending speed to use when enableBlending is true
  51941. */
  51942. this.blendingSpeed = 0.01;
  51943. /**
  51944. * Gets or sets the default loop mode to use
  51945. */
  51946. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  51947. }
  51948. return AnimationPropertiesOverride;
  51949. }());
  51950. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  51951. })(BABYLON || (BABYLON = {}));
  51952. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  51953. var BABYLON;
  51954. (function (BABYLON) {
  51955. /**
  51956. * Represents the range of an animation
  51957. */
  51958. var AnimationRange = /** @class */ (function () {
  51959. /**
  51960. * Initializes the range of an animation
  51961. * @param name The name of the animation range
  51962. * @param from The starting frame of the animation
  51963. * @param to The ending frame of the animation
  51964. */
  51965. function AnimationRange(
  51966. /**The name of the animation range**/
  51967. name,
  51968. /**The starting frame of the animation */
  51969. from,
  51970. /**The ending frame of the animation*/
  51971. to) {
  51972. this.name = name;
  51973. this.from = from;
  51974. this.to = to;
  51975. }
  51976. /**
  51977. * Makes a copy of the animation range
  51978. * @returns A copy of the animation range
  51979. */
  51980. AnimationRange.prototype.clone = function () {
  51981. return new AnimationRange(this.name, this.from, this.to);
  51982. };
  51983. return AnimationRange;
  51984. }());
  51985. BABYLON.AnimationRange = AnimationRange;
  51986. /**
  51987. * Composed of a frame, and an action function
  51988. */
  51989. var AnimationEvent = /** @class */ (function () {
  51990. /**
  51991. * Initializes the animation event
  51992. * @param frame The frame for which the event is triggered
  51993. * @param action The event to perform when triggered
  51994. * @param onlyOnce Specifies if the event should be triggered only once
  51995. */
  51996. function AnimationEvent(
  51997. /** The frame for which the event is triggered **/
  51998. frame,
  51999. /** The event to perform when triggered **/
  52000. action,
  52001. /** Specifies if the event should be triggered only once**/
  52002. onlyOnce) {
  52003. this.frame = frame;
  52004. this.action = action;
  52005. this.onlyOnce = onlyOnce;
  52006. /**
  52007. * Specifies if the animation event is done
  52008. */
  52009. this.isDone = false;
  52010. }
  52011. /** @hidden */
  52012. AnimationEvent.prototype._clone = function () {
  52013. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  52014. };
  52015. return AnimationEvent;
  52016. }());
  52017. BABYLON.AnimationEvent = AnimationEvent;
  52018. /**
  52019. * A cursor which tracks a point on a path
  52020. */
  52021. var PathCursor = /** @class */ (function () {
  52022. /**
  52023. * Initializes the path cursor
  52024. * @param path The path to track
  52025. */
  52026. function PathCursor(path) {
  52027. this.path = path;
  52028. /**
  52029. * Stores path cursor callbacks for when an onchange event is triggered
  52030. */
  52031. this._onchange = new Array();
  52032. /**
  52033. * The value of the path cursor
  52034. */
  52035. this.value = 0;
  52036. /**
  52037. * The animation array of the path cursor
  52038. */
  52039. this.animations = new Array();
  52040. }
  52041. /**
  52042. * Gets the cursor point on the path
  52043. * @returns A point on the path cursor at the cursor location
  52044. */
  52045. PathCursor.prototype.getPoint = function () {
  52046. var point = this.path.getPointAtLengthPosition(this.value);
  52047. return new BABYLON.Vector3(point.x, 0, point.y);
  52048. };
  52049. /**
  52050. * Moves the cursor ahead by the step amount
  52051. * @param step The amount to move the cursor forward
  52052. * @returns This path cursor
  52053. */
  52054. PathCursor.prototype.moveAhead = function (step) {
  52055. if (step === void 0) { step = 0.002; }
  52056. this.move(step);
  52057. return this;
  52058. };
  52059. /**
  52060. * Moves the cursor behind by the step amount
  52061. * @param step The amount to move the cursor back
  52062. * @returns This path cursor
  52063. */
  52064. PathCursor.prototype.moveBack = function (step) {
  52065. if (step === void 0) { step = 0.002; }
  52066. this.move(-step);
  52067. return this;
  52068. };
  52069. /**
  52070. * Moves the cursor by the step amount
  52071. * If the step amount is greater than one, an exception is thrown
  52072. * @param step The amount to move the cursor
  52073. * @returns This path cursor
  52074. */
  52075. PathCursor.prototype.move = function (step) {
  52076. if (Math.abs(step) > 1) {
  52077. throw "step size should be less than 1.";
  52078. }
  52079. this.value += step;
  52080. this.ensureLimits();
  52081. this.raiseOnChange();
  52082. return this;
  52083. };
  52084. /**
  52085. * Ensures that the value is limited between zero and one
  52086. * @returns This path cursor
  52087. */
  52088. PathCursor.prototype.ensureLimits = function () {
  52089. while (this.value > 1) {
  52090. this.value -= 1;
  52091. }
  52092. while (this.value < 0) {
  52093. this.value += 1;
  52094. }
  52095. return this;
  52096. };
  52097. /**
  52098. * Runs onchange callbacks on change (used by the animation engine)
  52099. * @returns This path cursor
  52100. */
  52101. PathCursor.prototype.raiseOnChange = function () {
  52102. var _this = this;
  52103. this._onchange.forEach(function (f) { return f(_this); });
  52104. return this;
  52105. };
  52106. /**
  52107. * Executes a function on change
  52108. * @param f A path cursor onchange callback
  52109. * @returns This path cursor
  52110. */
  52111. PathCursor.prototype.onchange = function (f) {
  52112. this._onchange.push(f);
  52113. return this;
  52114. };
  52115. return PathCursor;
  52116. }());
  52117. BABYLON.PathCursor = PathCursor;
  52118. /**
  52119. * Enum for the animation key frame interpolation type
  52120. */
  52121. var AnimationKeyInterpolation;
  52122. (function (AnimationKeyInterpolation) {
  52123. /**
  52124. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  52125. */
  52126. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  52127. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  52128. /**
  52129. * Class used to store any kind of animation
  52130. */
  52131. var Animation = /** @class */ (function () {
  52132. /**
  52133. * Initializes the animation
  52134. * @param name Name of the animation
  52135. * @param targetProperty Property to animate
  52136. * @param framePerSecond The frames per second of the animation
  52137. * @param dataType The data type of the animation
  52138. * @param loopMode The loop mode of the animation
  52139. * @param enableBlendings Specifies if blending should be enabled
  52140. */
  52141. function Animation(
  52142. /**Name of the animation */
  52143. name,
  52144. /**Property to animate */
  52145. targetProperty,
  52146. /**The frames per second of the animation */
  52147. framePerSecond,
  52148. /**The data type of the animation */
  52149. dataType,
  52150. /**The loop mode of the animation */
  52151. loopMode,
  52152. /**Specifies if blending should be enabled */
  52153. enableBlending) {
  52154. this.name = name;
  52155. this.targetProperty = targetProperty;
  52156. this.framePerSecond = framePerSecond;
  52157. this.dataType = dataType;
  52158. this.loopMode = loopMode;
  52159. this.enableBlending = enableBlending;
  52160. /**
  52161. * @hidden Internal use only
  52162. */
  52163. this._runtimeAnimations = new Array();
  52164. /**
  52165. * The set of event that will be linked to this animation
  52166. */
  52167. this._events = new Array();
  52168. /**
  52169. * Stores the blending speed of the animation
  52170. */
  52171. this.blendingSpeed = 0.01;
  52172. /**
  52173. * Stores the animation ranges for the animation
  52174. */
  52175. this._ranges = {};
  52176. this.targetPropertyPath = targetProperty.split(".");
  52177. this.dataType = dataType;
  52178. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  52179. }
  52180. /**
  52181. * @hidden Internal use
  52182. */
  52183. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  52184. var dataType = undefined;
  52185. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  52186. dataType = Animation.ANIMATIONTYPE_FLOAT;
  52187. }
  52188. else if (from instanceof BABYLON.Quaternion) {
  52189. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  52190. }
  52191. else if (from instanceof BABYLON.Vector3) {
  52192. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  52193. }
  52194. else if (from instanceof BABYLON.Vector2) {
  52195. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  52196. }
  52197. else if (from instanceof BABYLON.Color3) {
  52198. dataType = Animation.ANIMATIONTYPE_COLOR3;
  52199. }
  52200. else if (from instanceof BABYLON.Size) {
  52201. dataType = Animation.ANIMATIONTYPE_SIZE;
  52202. }
  52203. if (dataType == undefined) {
  52204. return null;
  52205. }
  52206. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  52207. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  52208. animation.setKeys(keys);
  52209. if (easingFunction !== undefined) {
  52210. animation.setEasingFunction(easingFunction);
  52211. }
  52212. return animation;
  52213. };
  52214. /**
  52215. * Sets up an animation
  52216. * @param property The property to animate
  52217. * @param animationType The animation type to apply
  52218. * @param framePerSecond The frames per second of the animation
  52219. * @param easingFunction The easing function used in the animation
  52220. * @returns The created animation
  52221. */
  52222. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  52223. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  52224. animation.setEasingFunction(easingFunction);
  52225. return animation;
  52226. };
  52227. /**
  52228. * Create and start an animation on a node
  52229. * @param name defines the name of the global animation that will be run on all nodes
  52230. * @param node defines the root node where the animation will take place
  52231. * @param targetProperty defines property to animate
  52232. * @param framePerSecond defines the number of frame per second yo use
  52233. * @param totalFrame defines the number of frames in total
  52234. * @param from defines the initial value
  52235. * @param to defines the final value
  52236. * @param loopMode defines which loop mode you want to use (off by default)
  52237. * @param easingFunction defines the easing function to use (linear by default)
  52238. * @param onAnimationEnd defines the callback to call when animation end
  52239. * @returns the animatable created for this animation
  52240. */
  52241. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  52242. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  52243. if (!animation) {
  52244. return null;
  52245. }
  52246. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  52247. };
  52248. /**
  52249. * Create and start an animation on a node and its descendants
  52250. * @param name defines the name of the global animation that will be run on all nodes
  52251. * @param node defines the root node where the animation will take place
  52252. * @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
  52253. * @param targetProperty defines property to animate
  52254. * @param framePerSecond defines the number of frame per second to use
  52255. * @param totalFrame defines the number of frames in total
  52256. * @param from defines the initial value
  52257. * @param to defines the final value
  52258. * @param loopMode defines which loop mode you want to use (off by default)
  52259. * @param easingFunction defines the easing function to use (linear by default)
  52260. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  52261. * @returns the list of animatables created for all nodes
  52262. * @example https://www.babylonjs-playground.com/#MH0VLI
  52263. */
  52264. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  52265. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  52266. if (!animation) {
  52267. return null;
  52268. }
  52269. var scene = node.getScene();
  52270. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  52271. };
  52272. /**
  52273. * Creates a new animation, merges it with the existing animations and starts it
  52274. * @param name Name of the animation
  52275. * @param node Node which contains the scene that begins the animations
  52276. * @param targetProperty Specifies which property to animate
  52277. * @param framePerSecond The frames per second of the animation
  52278. * @param totalFrame The total number of frames
  52279. * @param from The frame at the beginning of the animation
  52280. * @param to The frame at the end of the animation
  52281. * @param loopMode Specifies the loop mode of the animation
  52282. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  52283. * @param onAnimationEnd Callback to run once the animation is complete
  52284. * @returns Nullable animation
  52285. */
  52286. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  52287. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  52288. if (!animation) {
  52289. return null;
  52290. }
  52291. node.animations.push(animation);
  52292. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  52293. };
  52294. /**
  52295. * Transition property of an host to the target Value
  52296. * @param property The property to transition
  52297. * @param targetValue The target Value of the property
  52298. * @param host The object where the property to animate belongs
  52299. * @param scene Scene used to run the animation
  52300. * @param frameRate Framerate (in frame/s) to use
  52301. * @param transition The transition type we want to use
  52302. * @param duration The duration of the animation, in milliseconds
  52303. * @param onAnimationEnd Callback trigger at the end of the animation
  52304. * @returns Nullable animation
  52305. */
  52306. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  52307. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  52308. if (duration <= 0) {
  52309. host[property] = targetValue;
  52310. if (onAnimationEnd) {
  52311. onAnimationEnd();
  52312. }
  52313. return null;
  52314. }
  52315. var endFrame = frameRate * (duration / 1000);
  52316. transition.setKeys([{
  52317. frame: 0,
  52318. value: host[property].clone ? host[property].clone() : host[property]
  52319. },
  52320. {
  52321. frame: endFrame,
  52322. value: targetValue
  52323. }]);
  52324. if (!host.animations) {
  52325. host.animations = [];
  52326. }
  52327. host.animations.push(transition);
  52328. var animation = scene.beginAnimation(host, 0, endFrame, false);
  52329. animation.onAnimationEnd = onAnimationEnd;
  52330. return animation;
  52331. };
  52332. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  52333. /**
  52334. * Return the array of runtime animations currently using this animation
  52335. */
  52336. get: function () {
  52337. return this._runtimeAnimations;
  52338. },
  52339. enumerable: true,
  52340. configurable: true
  52341. });
  52342. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  52343. /**
  52344. * Specifies if any of the runtime animations are currently running
  52345. */
  52346. get: function () {
  52347. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  52348. var runtimeAnimation = _a[_i];
  52349. if (!runtimeAnimation.isStopped) {
  52350. return true;
  52351. }
  52352. }
  52353. return false;
  52354. },
  52355. enumerable: true,
  52356. configurable: true
  52357. });
  52358. // Methods
  52359. /**
  52360. * Converts the animation to a string
  52361. * @param fullDetails support for multiple levels of logging within scene loading
  52362. * @returns String form of the animation
  52363. */
  52364. Animation.prototype.toString = function (fullDetails) {
  52365. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  52366. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  52367. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  52368. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  52369. if (fullDetails) {
  52370. ret += ", Ranges: {";
  52371. var first = true;
  52372. for (var name in this._ranges) {
  52373. if (first) {
  52374. ret += ", ";
  52375. first = false;
  52376. }
  52377. ret += name;
  52378. }
  52379. ret += "}";
  52380. }
  52381. return ret;
  52382. };
  52383. /**
  52384. * Add an event to this animation
  52385. * @param event Event to add
  52386. */
  52387. Animation.prototype.addEvent = function (event) {
  52388. this._events.push(event);
  52389. };
  52390. /**
  52391. * Remove all events found at the given frame
  52392. * @param frame The frame to remove events from
  52393. */
  52394. Animation.prototype.removeEvents = function (frame) {
  52395. for (var index = 0; index < this._events.length; index++) {
  52396. if (this._events[index].frame === frame) {
  52397. this._events.splice(index, 1);
  52398. index--;
  52399. }
  52400. }
  52401. };
  52402. /**
  52403. * Retrieves all the events from the animation
  52404. * @returns Events from the animation
  52405. */
  52406. Animation.prototype.getEvents = function () {
  52407. return this._events;
  52408. };
  52409. /**
  52410. * Creates an animation range
  52411. * @param name Name of the animation range
  52412. * @param from Starting frame of the animation range
  52413. * @param to Ending frame of the animation
  52414. */
  52415. Animation.prototype.createRange = function (name, from, to) {
  52416. // check name not already in use; could happen for bones after serialized
  52417. if (!this._ranges[name]) {
  52418. this._ranges[name] = new AnimationRange(name, from, to);
  52419. }
  52420. };
  52421. /**
  52422. * Deletes an animation range by name
  52423. * @param name Name of the animation range to delete
  52424. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  52425. */
  52426. Animation.prototype.deleteRange = function (name, deleteFrames) {
  52427. if (deleteFrames === void 0) { deleteFrames = true; }
  52428. var range = this._ranges[name];
  52429. if (!range) {
  52430. return;
  52431. }
  52432. if (deleteFrames) {
  52433. var from = range.from;
  52434. var to = range.to;
  52435. // this loop MUST go high to low for multiple splices to work
  52436. for (var key = this._keys.length - 1; key >= 0; key--) {
  52437. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  52438. this._keys.splice(key, 1);
  52439. }
  52440. }
  52441. }
  52442. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  52443. };
  52444. /**
  52445. * Gets the animation range by name, or null if not defined
  52446. * @param name Name of the animation range
  52447. * @returns Nullable animation range
  52448. */
  52449. Animation.prototype.getRange = function (name) {
  52450. return this._ranges[name];
  52451. };
  52452. /**
  52453. * Gets the key frames from the animation
  52454. * @returns The key frames of the animation
  52455. */
  52456. Animation.prototype.getKeys = function () {
  52457. return this._keys;
  52458. };
  52459. /**
  52460. * Gets the highest frame rate of the animation
  52461. * @returns Highest frame rate of the animation
  52462. */
  52463. Animation.prototype.getHighestFrame = function () {
  52464. var ret = 0;
  52465. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  52466. if (ret < this._keys[key].frame) {
  52467. ret = this._keys[key].frame;
  52468. }
  52469. }
  52470. return ret;
  52471. };
  52472. /**
  52473. * Gets the easing function of the animation
  52474. * @returns Easing function of the animation
  52475. */
  52476. Animation.prototype.getEasingFunction = function () {
  52477. return this._easingFunction;
  52478. };
  52479. /**
  52480. * Sets the easing function of the animation
  52481. * @param easingFunction A custom mathematical formula for animation
  52482. */
  52483. Animation.prototype.setEasingFunction = function (easingFunction) {
  52484. this._easingFunction = easingFunction;
  52485. };
  52486. /**
  52487. * Interpolates a scalar linearly
  52488. * @param startValue Start value of the animation curve
  52489. * @param endValue End value of the animation curve
  52490. * @param gradient Scalar amount to interpolate
  52491. * @returns Interpolated scalar value
  52492. */
  52493. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  52494. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  52495. };
  52496. /**
  52497. * Interpolates a scalar cubically
  52498. * @param startValue Start value of the animation curve
  52499. * @param outTangent End tangent of the animation
  52500. * @param endValue End value of the animation curve
  52501. * @param inTangent Start tangent of the animation curve
  52502. * @param gradient Scalar amount to interpolate
  52503. * @returns Interpolated scalar value
  52504. */
  52505. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52506. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  52507. };
  52508. /**
  52509. * Interpolates a quaternion using a spherical linear interpolation
  52510. * @param startValue Start value of the animation curve
  52511. * @param endValue End value of the animation curve
  52512. * @param gradient Scalar amount to interpolate
  52513. * @returns Interpolated quaternion value
  52514. */
  52515. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  52516. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  52517. };
  52518. /**
  52519. * Interpolates a quaternion cubically
  52520. * @param startValue Start value of the animation curve
  52521. * @param outTangent End tangent of the animation curve
  52522. * @param endValue End value of the animation curve
  52523. * @param inTangent Start tangent of the animation curve
  52524. * @param gradient Scalar amount to interpolate
  52525. * @returns Interpolated quaternion value
  52526. */
  52527. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52528. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  52529. };
  52530. /**
  52531. * Interpolates a Vector3 linearl
  52532. * @param startValue Start value of the animation curve
  52533. * @param endValue End value of the animation curve
  52534. * @param gradient Scalar amount to interpolate
  52535. * @returns Interpolated scalar value
  52536. */
  52537. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  52538. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  52539. };
  52540. /**
  52541. * Interpolates a Vector3 cubically
  52542. * @param startValue Start value of the animation curve
  52543. * @param outTangent End tangent of the animation
  52544. * @param endValue End value of the animation curve
  52545. * @param inTangent Start tangent of the animation curve
  52546. * @param gradient Scalar amount to interpolate
  52547. * @returns InterpolatedVector3 value
  52548. */
  52549. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52550. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  52551. };
  52552. /**
  52553. * Interpolates a Vector2 linearly
  52554. * @param startValue Start value of the animation curve
  52555. * @param endValue End value of the animation curve
  52556. * @param gradient Scalar amount to interpolate
  52557. * @returns Interpolated Vector2 value
  52558. */
  52559. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  52560. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  52561. };
  52562. /**
  52563. * Interpolates a Vector2 cubically
  52564. * @param startValue Start value of the animation curve
  52565. * @param outTangent End tangent of the animation
  52566. * @param endValue End value of the animation curve
  52567. * @param inTangent Start tangent of the animation curve
  52568. * @param gradient Scalar amount to interpolate
  52569. * @returns Interpolated Vector2 value
  52570. */
  52571. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52572. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  52573. };
  52574. /**
  52575. * Interpolates a size linearly
  52576. * @param startValue Start value of the animation curve
  52577. * @param endValue End value of the animation curve
  52578. * @param gradient Scalar amount to interpolate
  52579. * @returns Interpolated Size value
  52580. */
  52581. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  52582. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  52583. };
  52584. /**
  52585. * Interpolates a Color3 linearly
  52586. * @param startValue Start value of the animation curve
  52587. * @param endValue End value of the animation curve
  52588. * @param gradient Scalar amount to interpolate
  52589. * @returns Interpolated Color3 value
  52590. */
  52591. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  52592. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  52593. };
  52594. /**
  52595. * @hidden Internal use only
  52596. */
  52597. Animation.prototype._getKeyValue = function (value) {
  52598. if (typeof value === "function") {
  52599. return value();
  52600. }
  52601. return value;
  52602. };
  52603. /**
  52604. * @hidden Internal use only
  52605. */
  52606. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  52607. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  52608. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  52609. }
  52610. var keys = this.getKeys();
  52611. // Try to get a hash to find the right key
  52612. 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));
  52613. if (keys[startKeyIndex].frame >= currentFrame) {
  52614. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  52615. startKeyIndex--;
  52616. }
  52617. }
  52618. for (var key = startKeyIndex; key < keys.length; key++) {
  52619. var endKey = keys[key + 1];
  52620. if (endKey.frame >= currentFrame) {
  52621. var startKey = keys[key];
  52622. var startValue = this._getKeyValue(startKey.value);
  52623. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  52624. return startValue;
  52625. }
  52626. var endValue = this._getKeyValue(endKey.value);
  52627. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  52628. var frameDelta = endKey.frame - startKey.frame;
  52629. // gradient : percent of currentFrame between the frame inf and the frame sup
  52630. var gradient = (currentFrame - startKey.frame) / frameDelta;
  52631. // check for easingFunction and correction of gradient
  52632. var easingFunction = this.getEasingFunction();
  52633. if (easingFunction != null) {
  52634. gradient = easingFunction.ease(gradient);
  52635. }
  52636. switch (this.dataType) {
  52637. // Float
  52638. case Animation.ANIMATIONTYPE_FLOAT:
  52639. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  52640. switch (loopMode) {
  52641. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52642. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52643. return floatValue;
  52644. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52645. return offsetValue * repeatCount + floatValue;
  52646. }
  52647. break;
  52648. // Quaternion
  52649. case Animation.ANIMATIONTYPE_QUATERNION:
  52650. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  52651. switch (loopMode) {
  52652. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52653. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52654. return quatValue;
  52655. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52656. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  52657. }
  52658. return quatValue;
  52659. // Vector3
  52660. case Animation.ANIMATIONTYPE_VECTOR3:
  52661. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  52662. switch (loopMode) {
  52663. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52664. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52665. return vec3Value;
  52666. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52667. return vec3Value.add(offsetValue.scale(repeatCount));
  52668. }
  52669. // Vector2
  52670. case Animation.ANIMATIONTYPE_VECTOR2:
  52671. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  52672. switch (loopMode) {
  52673. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52674. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52675. return vec2Value;
  52676. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52677. return vec2Value.add(offsetValue.scale(repeatCount));
  52678. }
  52679. // Size
  52680. case Animation.ANIMATIONTYPE_SIZE:
  52681. switch (loopMode) {
  52682. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52683. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52684. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  52685. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52686. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  52687. }
  52688. // Color3
  52689. case Animation.ANIMATIONTYPE_COLOR3:
  52690. switch (loopMode) {
  52691. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52692. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52693. return this.color3InterpolateFunction(startValue, endValue, gradient);
  52694. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52695. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  52696. }
  52697. // Matrix
  52698. case Animation.ANIMATIONTYPE_MATRIX:
  52699. switch (loopMode) {
  52700. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52701. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52702. if (Animation.AllowMatricesInterpolation) {
  52703. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  52704. }
  52705. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52706. return startValue;
  52707. }
  52708. default:
  52709. break;
  52710. }
  52711. break;
  52712. }
  52713. }
  52714. return this._getKeyValue(keys[keys.length - 1].value);
  52715. };
  52716. /**
  52717. * Defines the function to use to interpolate matrices
  52718. * @param startValue defines the start matrix
  52719. * @param endValue defines the end matrix
  52720. * @param gradient defines the gradient between both matrices
  52721. * @param result defines an optional target matrix where to store the interpolation
  52722. * @returns the interpolated matrix
  52723. */
  52724. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  52725. if (Animation.AllowMatrixDecomposeForInterpolation) {
  52726. if (result) {
  52727. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  52728. return result;
  52729. }
  52730. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  52731. }
  52732. if (result) {
  52733. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  52734. return result;
  52735. }
  52736. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  52737. };
  52738. /**
  52739. * Makes a copy of the animation
  52740. * @returns Cloned animation
  52741. */
  52742. Animation.prototype.clone = function () {
  52743. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  52744. clone.enableBlending = this.enableBlending;
  52745. clone.blendingSpeed = this.blendingSpeed;
  52746. if (this._keys) {
  52747. clone.setKeys(this._keys);
  52748. }
  52749. if (this._ranges) {
  52750. clone._ranges = {};
  52751. for (var name in this._ranges) {
  52752. var range = this._ranges[name];
  52753. if (!range) {
  52754. continue;
  52755. }
  52756. clone._ranges[name] = range.clone();
  52757. }
  52758. }
  52759. return clone;
  52760. };
  52761. /**
  52762. * Sets the key frames of the animation
  52763. * @param values The animation key frames to set
  52764. */
  52765. Animation.prototype.setKeys = function (values) {
  52766. this._keys = values.slice(0);
  52767. };
  52768. /**
  52769. * Serializes the animation to an object
  52770. * @returns Serialized object
  52771. */
  52772. Animation.prototype.serialize = function () {
  52773. var serializationObject = {};
  52774. serializationObject.name = this.name;
  52775. serializationObject.property = this.targetProperty;
  52776. serializationObject.framePerSecond = this.framePerSecond;
  52777. serializationObject.dataType = this.dataType;
  52778. serializationObject.loopBehavior = this.loopMode;
  52779. serializationObject.enableBlending = this.enableBlending;
  52780. serializationObject.blendingSpeed = this.blendingSpeed;
  52781. var dataType = this.dataType;
  52782. serializationObject.keys = [];
  52783. var keys = this.getKeys();
  52784. for (var index = 0; index < keys.length; index++) {
  52785. var animationKey = keys[index];
  52786. var key = {};
  52787. key.frame = animationKey.frame;
  52788. switch (dataType) {
  52789. case Animation.ANIMATIONTYPE_FLOAT:
  52790. key.values = [animationKey.value];
  52791. break;
  52792. case Animation.ANIMATIONTYPE_QUATERNION:
  52793. case Animation.ANIMATIONTYPE_MATRIX:
  52794. case Animation.ANIMATIONTYPE_VECTOR3:
  52795. case Animation.ANIMATIONTYPE_COLOR3:
  52796. key.values = animationKey.value.asArray();
  52797. break;
  52798. }
  52799. serializationObject.keys.push(key);
  52800. }
  52801. serializationObject.ranges = [];
  52802. for (var name in this._ranges) {
  52803. var source = this._ranges[name];
  52804. if (!source) {
  52805. continue;
  52806. }
  52807. var range = {};
  52808. range.name = name;
  52809. range.from = source.from;
  52810. range.to = source.to;
  52811. serializationObject.ranges.push(range);
  52812. }
  52813. return serializationObject;
  52814. };
  52815. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  52816. /**
  52817. * Get the float animation type
  52818. */
  52819. get: function () {
  52820. return Animation._ANIMATIONTYPE_FLOAT;
  52821. },
  52822. enumerable: true,
  52823. configurable: true
  52824. });
  52825. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  52826. /**
  52827. * Get the Vector3 animation type
  52828. */
  52829. get: function () {
  52830. return Animation._ANIMATIONTYPE_VECTOR3;
  52831. },
  52832. enumerable: true,
  52833. configurable: true
  52834. });
  52835. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  52836. /**
  52837. * Get the Vector2 animation type
  52838. */
  52839. get: function () {
  52840. return Animation._ANIMATIONTYPE_VECTOR2;
  52841. },
  52842. enumerable: true,
  52843. configurable: true
  52844. });
  52845. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  52846. /**
  52847. * Get the Size animation type
  52848. */
  52849. get: function () {
  52850. return Animation._ANIMATIONTYPE_SIZE;
  52851. },
  52852. enumerable: true,
  52853. configurable: true
  52854. });
  52855. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  52856. /**
  52857. * Get the Quaternion animation type
  52858. */
  52859. get: function () {
  52860. return Animation._ANIMATIONTYPE_QUATERNION;
  52861. },
  52862. enumerable: true,
  52863. configurable: true
  52864. });
  52865. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  52866. /**
  52867. * Get the Matrix animation type
  52868. */
  52869. get: function () {
  52870. return Animation._ANIMATIONTYPE_MATRIX;
  52871. },
  52872. enumerable: true,
  52873. configurable: true
  52874. });
  52875. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  52876. /**
  52877. * Get the Color3 animation type
  52878. */
  52879. get: function () {
  52880. return Animation._ANIMATIONTYPE_COLOR3;
  52881. },
  52882. enumerable: true,
  52883. configurable: true
  52884. });
  52885. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  52886. /**
  52887. * Get the Relative Loop Mode
  52888. */
  52889. get: function () {
  52890. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  52891. },
  52892. enumerable: true,
  52893. configurable: true
  52894. });
  52895. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  52896. /**
  52897. * Get the Cycle Loop Mode
  52898. */
  52899. get: function () {
  52900. return Animation._ANIMATIONLOOPMODE_CYCLE;
  52901. },
  52902. enumerable: true,
  52903. configurable: true
  52904. });
  52905. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  52906. /**
  52907. * Get the Constant Loop Mode
  52908. */
  52909. get: function () {
  52910. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  52911. },
  52912. enumerable: true,
  52913. configurable: true
  52914. });
  52915. /** @hidden */
  52916. Animation._UniversalLerp = function (left, right, amount) {
  52917. var constructor = left.constructor;
  52918. if (constructor.Lerp) { // Lerp supported
  52919. return constructor.Lerp(left, right, amount);
  52920. }
  52921. else if (constructor.Slerp) { // Slerp supported
  52922. return constructor.Slerp(left, right, amount);
  52923. }
  52924. else if (left.toFixed) { // Number
  52925. return left * (1.0 - amount) + amount * right;
  52926. }
  52927. else { // Blending not supported
  52928. return right;
  52929. }
  52930. };
  52931. /**
  52932. * Parses an animation object and creates an animation
  52933. * @param parsedAnimation Parsed animation object
  52934. * @returns Animation object
  52935. */
  52936. Animation.Parse = function (parsedAnimation) {
  52937. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  52938. var dataType = parsedAnimation.dataType;
  52939. var keys = [];
  52940. var data;
  52941. var index;
  52942. if (parsedAnimation.enableBlending) {
  52943. animation.enableBlending = parsedAnimation.enableBlending;
  52944. }
  52945. if (parsedAnimation.blendingSpeed) {
  52946. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  52947. }
  52948. for (index = 0; index < parsedAnimation.keys.length; index++) {
  52949. var key = parsedAnimation.keys[index];
  52950. var inTangent;
  52951. var outTangent;
  52952. switch (dataType) {
  52953. case Animation.ANIMATIONTYPE_FLOAT:
  52954. data = key.values[0];
  52955. if (key.values.length >= 1) {
  52956. inTangent = key.values[1];
  52957. }
  52958. if (key.values.length >= 2) {
  52959. outTangent = key.values[2];
  52960. }
  52961. break;
  52962. case Animation.ANIMATIONTYPE_QUATERNION:
  52963. data = BABYLON.Quaternion.FromArray(key.values);
  52964. if (key.values.length >= 8) {
  52965. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  52966. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  52967. inTangent = _inTangent;
  52968. }
  52969. }
  52970. if (key.values.length >= 12) {
  52971. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  52972. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  52973. outTangent = _outTangent;
  52974. }
  52975. }
  52976. break;
  52977. case Animation.ANIMATIONTYPE_MATRIX:
  52978. data = BABYLON.Matrix.FromArray(key.values);
  52979. break;
  52980. case Animation.ANIMATIONTYPE_COLOR3:
  52981. data = BABYLON.Color3.FromArray(key.values);
  52982. break;
  52983. case Animation.ANIMATIONTYPE_VECTOR3:
  52984. default:
  52985. data = BABYLON.Vector3.FromArray(key.values);
  52986. break;
  52987. }
  52988. var keyData = {};
  52989. keyData.frame = key.frame;
  52990. keyData.value = data;
  52991. if (inTangent != undefined) {
  52992. keyData.inTangent = inTangent;
  52993. }
  52994. if (outTangent != undefined) {
  52995. keyData.outTangent = outTangent;
  52996. }
  52997. keys.push(keyData);
  52998. }
  52999. animation.setKeys(keys);
  53000. if (parsedAnimation.ranges) {
  53001. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  53002. data = parsedAnimation.ranges[index];
  53003. animation.createRange(data.name, data.from, data.to);
  53004. }
  53005. }
  53006. return animation;
  53007. };
  53008. /**
  53009. * Appends the serialized animations from the source animations
  53010. * @param source Source containing the animations
  53011. * @param destination Target to store the animations
  53012. */
  53013. Animation.AppendSerializedAnimations = function (source, destination) {
  53014. if (source.animations) {
  53015. destination.animations = [];
  53016. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  53017. var animation = source.animations[animationIndex];
  53018. destination.animations.push(animation.serialize());
  53019. }
  53020. }
  53021. };
  53022. /**
  53023. * Use matrix interpolation instead of using direct key value when animating matrices
  53024. */
  53025. Animation.AllowMatricesInterpolation = false;
  53026. /**
  53027. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  53028. */
  53029. Animation.AllowMatrixDecomposeForInterpolation = true;
  53030. // Statics
  53031. /**
  53032. * Float animation type
  53033. */
  53034. Animation._ANIMATIONTYPE_FLOAT = 0;
  53035. /**
  53036. * Vector3 animation type
  53037. */
  53038. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  53039. /**
  53040. * Quaternion animation type
  53041. */
  53042. Animation._ANIMATIONTYPE_QUATERNION = 2;
  53043. /**
  53044. * Matrix animation type
  53045. */
  53046. Animation._ANIMATIONTYPE_MATRIX = 3;
  53047. /**
  53048. * Color3 animation type
  53049. */
  53050. Animation._ANIMATIONTYPE_COLOR3 = 4;
  53051. /**
  53052. * Vector2 animation type
  53053. */
  53054. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  53055. /**
  53056. * Size animation type
  53057. */
  53058. Animation._ANIMATIONTYPE_SIZE = 6;
  53059. /**
  53060. * Relative Loop Mode
  53061. */
  53062. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  53063. /**
  53064. * Cycle Loop Mode
  53065. */
  53066. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  53067. /**
  53068. * Constant Loop Mode
  53069. */
  53070. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  53071. return Animation;
  53072. }());
  53073. BABYLON.Animation = Animation;
  53074. })(BABYLON || (BABYLON = {}));
  53075. //# sourceMappingURL=babylon.animation.js.map
  53076. var BABYLON;
  53077. (function (BABYLON) {
  53078. /**
  53079. * This class defines the direct association between an animation and a target
  53080. */
  53081. var TargetedAnimation = /** @class */ (function () {
  53082. function TargetedAnimation() {
  53083. }
  53084. return TargetedAnimation;
  53085. }());
  53086. BABYLON.TargetedAnimation = TargetedAnimation;
  53087. /**
  53088. * Use this class to create coordinated animations on multiple targets
  53089. */
  53090. var AnimationGroup = /** @class */ (function () {
  53091. /**
  53092. * Instantiates a new Animation Group.
  53093. * This helps managing several animations at once.
  53094. * @see http://doc.babylonjs.com/how_to/group
  53095. * @param name Defines the name of the group
  53096. * @param scene Defines the scene the group belongs to
  53097. */
  53098. function AnimationGroup(
  53099. /** The name of the animation group */
  53100. name, scene) {
  53101. if (scene === void 0) { scene = null; }
  53102. this.name = name;
  53103. this._targetedAnimations = new Array();
  53104. this._animatables = new Array();
  53105. this._from = Number.MAX_VALUE;
  53106. this._to = -Number.MAX_VALUE;
  53107. this._speedRatio = 1;
  53108. /**
  53109. * This observable will notify when one animation have ended.
  53110. */
  53111. this.onAnimationEndObservable = new BABYLON.Observable();
  53112. /**
  53113. * This observable will notify when all animations have ended.
  53114. */
  53115. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  53116. /**
  53117. * This observable will notify when all animations have paused.
  53118. */
  53119. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  53120. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53121. this._scene.animationGroups.push(this);
  53122. }
  53123. Object.defineProperty(AnimationGroup.prototype, "from", {
  53124. /**
  53125. * Gets the first frame
  53126. */
  53127. get: function () {
  53128. return this._from;
  53129. },
  53130. enumerable: true,
  53131. configurable: true
  53132. });
  53133. Object.defineProperty(AnimationGroup.prototype, "to", {
  53134. /**
  53135. * Gets the last frame
  53136. */
  53137. get: function () {
  53138. return this._to;
  53139. },
  53140. enumerable: true,
  53141. configurable: true
  53142. });
  53143. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  53144. /**
  53145. * Define if the animations are started
  53146. */
  53147. get: function () {
  53148. return this._isStarted;
  53149. },
  53150. enumerable: true,
  53151. configurable: true
  53152. });
  53153. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  53154. /**
  53155. * Gets or sets the speed ratio to use for all animations
  53156. */
  53157. get: function () {
  53158. return this._speedRatio;
  53159. },
  53160. /**
  53161. * Gets or sets the speed ratio to use for all animations
  53162. */
  53163. set: function (value) {
  53164. if (this._speedRatio === value) {
  53165. return;
  53166. }
  53167. this._speedRatio = value;
  53168. for (var index = 0; index < this._animatables.length; index++) {
  53169. var animatable = this._animatables[index];
  53170. animatable.speedRatio = this._speedRatio;
  53171. }
  53172. },
  53173. enumerable: true,
  53174. configurable: true
  53175. });
  53176. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  53177. /**
  53178. * Gets the targeted animations for this animation group
  53179. */
  53180. get: function () {
  53181. return this._targetedAnimations;
  53182. },
  53183. enumerable: true,
  53184. configurable: true
  53185. });
  53186. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  53187. /**
  53188. * returning the list of animatables controlled by this animation group.
  53189. */
  53190. get: function () {
  53191. return this._animatables;
  53192. },
  53193. enumerable: true,
  53194. configurable: true
  53195. });
  53196. /**
  53197. * Add an animation (with its target) in the group
  53198. * @param animation defines the animation we want to add
  53199. * @param target defines the target of the animation
  53200. * @returns the TargetedAnimation object
  53201. */
  53202. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  53203. var targetedAnimation = {
  53204. animation: animation,
  53205. target: target
  53206. };
  53207. var keys = animation.getKeys();
  53208. if (this._from > keys[0].frame) {
  53209. this._from = keys[0].frame;
  53210. }
  53211. if (this._to < keys[keys.length - 1].frame) {
  53212. this._to = keys[keys.length - 1].frame;
  53213. }
  53214. this._targetedAnimations.push(targetedAnimation);
  53215. return targetedAnimation;
  53216. };
  53217. /**
  53218. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  53219. * It can add constant keys at begin or end
  53220. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  53221. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  53222. * @returns the animation group
  53223. */
  53224. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  53225. if (beginFrame === void 0) { beginFrame = null; }
  53226. if (endFrame === void 0) { endFrame = null; }
  53227. if (beginFrame == null) {
  53228. beginFrame = this._from;
  53229. }
  53230. if (endFrame == null) {
  53231. endFrame = this._to;
  53232. }
  53233. for (var index = 0; index < this._targetedAnimations.length; index++) {
  53234. var targetedAnimation = this._targetedAnimations[index];
  53235. var keys = targetedAnimation.animation.getKeys();
  53236. var startKey = keys[0];
  53237. var endKey = keys[keys.length - 1];
  53238. if (startKey.frame > beginFrame) {
  53239. var newKey = {
  53240. frame: beginFrame,
  53241. value: startKey.value,
  53242. inTangent: startKey.inTangent,
  53243. outTangent: startKey.outTangent,
  53244. interpolation: startKey.interpolation
  53245. };
  53246. keys.splice(0, 0, newKey);
  53247. }
  53248. if (endKey.frame < endFrame) {
  53249. var newKey = {
  53250. frame: endFrame,
  53251. value: endKey.value,
  53252. inTangent: endKey.outTangent,
  53253. outTangent: endKey.outTangent,
  53254. interpolation: endKey.interpolation
  53255. };
  53256. keys.push(newKey);
  53257. }
  53258. }
  53259. this._from = beginFrame;
  53260. this._to = endFrame;
  53261. return this;
  53262. };
  53263. /**
  53264. * Start all animations on given targets
  53265. * @param loop defines if animations must loop
  53266. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  53267. * @param from defines the from key (optional)
  53268. * @param to defines the to key (optional)
  53269. * @returns the current animation group
  53270. */
  53271. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  53272. var _this = this;
  53273. if (loop === void 0) { loop = false; }
  53274. if (speedRatio === void 0) { speedRatio = 1; }
  53275. if (this._isStarted || this._targetedAnimations.length === 0) {
  53276. return this;
  53277. }
  53278. var _loop_1 = function (targetedAnimation) {
  53279. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  53280. animatable.onAnimationEnd = function () {
  53281. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  53282. _this._checkAnimationGroupEnded(animatable);
  53283. };
  53284. this_1._animatables.push(animatable);
  53285. };
  53286. var this_1 = this;
  53287. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  53288. var targetedAnimation = _a[_i];
  53289. _loop_1(targetedAnimation);
  53290. }
  53291. this._speedRatio = speedRatio;
  53292. this._isStarted = true;
  53293. return this;
  53294. };
  53295. /**
  53296. * Pause all animations
  53297. * @returns the animation group
  53298. */
  53299. AnimationGroup.prototype.pause = function () {
  53300. if (!this._isStarted) {
  53301. return this;
  53302. }
  53303. for (var index = 0; index < this._animatables.length; index++) {
  53304. var animatable = this._animatables[index];
  53305. animatable.pause();
  53306. }
  53307. this.onAnimationGroupPauseObservable.notifyObservers(this);
  53308. return this;
  53309. };
  53310. /**
  53311. * Play all animations to initial state
  53312. * This function will start() the animations if they were not started or will restart() them if they were paused
  53313. * @param loop defines if animations must loop
  53314. * @returns the animation group
  53315. */
  53316. AnimationGroup.prototype.play = function (loop) {
  53317. // only if all animatables are ready and exist
  53318. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  53319. if (loop !== undefined) {
  53320. for (var index = 0; index < this._animatables.length; index++) {
  53321. var animatable = this._animatables[index];
  53322. animatable.loopAnimation = loop;
  53323. }
  53324. }
  53325. this.restart();
  53326. }
  53327. else {
  53328. this.stop();
  53329. this.start(loop, this._speedRatio);
  53330. }
  53331. return this;
  53332. };
  53333. /**
  53334. * Reset all animations to initial state
  53335. * @returns the animation group
  53336. */
  53337. AnimationGroup.prototype.reset = function () {
  53338. if (!this._isStarted) {
  53339. return this;
  53340. }
  53341. for (var index = 0; index < this._animatables.length; index++) {
  53342. var animatable = this._animatables[index];
  53343. animatable.reset();
  53344. }
  53345. return this;
  53346. };
  53347. /**
  53348. * Restart animations from key 0
  53349. * @returns the animation group
  53350. */
  53351. AnimationGroup.prototype.restart = function () {
  53352. if (!this._isStarted) {
  53353. return this;
  53354. }
  53355. for (var index = 0; index < this._animatables.length; index++) {
  53356. var animatable = this._animatables[index];
  53357. animatable.restart();
  53358. }
  53359. return this;
  53360. };
  53361. /**
  53362. * Stop all animations
  53363. * @returns the animation group
  53364. */
  53365. AnimationGroup.prototype.stop = function () {
  53366. if (!this._isStarted) {
  53367. return this;
  53368. }
  53369. var list = this._animatables.slice();
  53370. for (var index = 0; index < list.length; index++) {
  53371. list[index].stop();
  53372. }
  53373. this._isStarted = false;
  53374. return this;
  53375. };
  53376. /**
  53377. * Set animation weight for all animatables
  53378. * @param weight defines the weight to use
  53379. * @return the animationGroup
  53380. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  53381. */
  53382. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  53383. for (var index = 0; index < this._animatables.length; index++) {
  53384. var animatable = this._animatables[index];
  53385. animatable.weight = weight;
  53386. }
  53387. return this;
  53388. };
  53389. /**
  53390. * Synchronize and normalize all animatables with a source animatable
  53391. * @param root defines the root animatable to synchronize with
  53392. * @return the animationGroup
  53393. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  53394. */
  53395. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  53396. for (var index = 0; index < this._animatables.length; index++) {
  53397. var animatable = this._animatables[index];
  53398. animatable.syncWith(root);
  53399. }
  53400. return this;
  53401. };
  53402. /**
  53403. * Goes to a specific frame in this animation group
  53404. * @param frame the frame number to go to
  53405. * @return the animationGroup
  53406. */
  53407. AnimationGroup.prototype.goToFrame = function (frame) {
  53408. if (!this._isStarted) {
  53409. return this;
  53410. }
  53411. for (var index = 0; index < this._animatables.length; index++) {
  53412. var animatable = this._animatables[index];
  53413. animatable.goToFrame(frame);
  53414. }
  53415. return this;
  53416. };
  53417. /**
  53418. * Dispose all associated resources
  53419. */
  53420. AnimationGroup.prototype.dispose = function () {
  53421. this._targetedAnimations = [];
  53422. this._animatables = [];
  53423. var index = this._scene.animationGroups.indexOf(this);
  53424. if (index > -1) {
  53425. this._scene.animationGroups.splice(index, 1);
  53426. }
  53427. };
  53428. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  53429. // animatable should be taken out of the array
  53430. var idx = this._animatables.indexOf(animatable);
  53431. if (idx > -1) {
  53432. this._animatables.splice(idx, 1);
  53433. }
  53434. // all animatables were removed? animation group ended!
  53435. if (this._animatables.length === 0) {
  53436. this._isStarted = false;
  53437. this.onAnimationGroupEndObservable.notifyObservers(this);
  53438. }
  53439. };
  53440. // Statics
  53441. /**
  53442. * Returns a new AnimationGroup object parsed from the source provided.
  53443. * @param parsedAnimationGroup defines the source
  53444. * @param scene defines the scene that will receive the animationGroup
  53445. * @returns a new AnimationGroup
  53446. */
  53447. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  53448. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  53449. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  53450. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  53451. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  53452. var id = targetedAnimation.targetId;
  53453. var targetNode = scene.getNodeByID(id);
  53454. if (targetNode != null) {
  53455. animationGroup.addTargetedAnimation(animation, targetNode);
  53456. }
  53457. }
  53458. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null) {
  53459. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  53460. }
  53461. return animationGroup;
  53462. };
  53463. /**
  53464. * Returns the string "AnimationGroup"
  53465. * @returns "AnimationGroup"
  53466. */
  53467. AnimationGroup.prototype.getClassName = function () {
  53468. return "AnimationGroup";
  53469. };
  53470. /**
  53471. * Creates a detailled string about the object
  53472. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  53473. * @returns a string representing the object
  53474. */
  53475. AnimationGroup.prototype.toString = function (fullDetails) {
  53476. var ret = "Name: " + this.name;
  53477. ret += ", type: " + this.getClassName();
  53478. if (fullDetails) {
  53479. ret += ", from: " + this._from;
  53480. ret += ", to: " + this._to;
  53481. ret += ", isStarted: " + this._isStarted;
  53482. ret += ", speedRatio: " + this._speedRatio;
  53483. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  53484. ret += ", animatables length: " + this._animatables;
  53485. }
  53486. return ret;
  53487. };
  53488. return AnimationGroup;
  53489. }());
  53490. BABYLON.AnimationGroup = AnimationGroup;
  53491. })(BABYLON || (BABYLON = {}));
  53492. //# sourceMappingURL=babylon.animationGroup.js.map
  53493. var BABYLON;
  53494. (function (BABYLON) {
  53495. // Static values to help the garbage collector
  53496. // Quaternion
  53497. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  53498. // Vector3
  53499. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  53500. // Vector2
  53501. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  53502. // Size
  53503. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  53504. // Color3
  53505. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  53506. /**
  53507. * Defines a runtime animation
  53508. */
  53509. var RuntimeAnimation = /** @class */ (function () {
  53510. /**
  53511. * Create a new RuntimeAnimation object
  53512. * @param target defines the target of the animation
  53513. * @param animation defines the source animation object
  53514. * @param scene defines the hosting scene
  53515. * @param host defines the initiating Animatable
  53516. */
  53517. function RuntimeAnimation(target, animation, scene, host) {
  53518. var _this = this;
  53519. this._events = new Array();
  53520. /**
  53521. * The current frame of the runtime animation
  53522. */
  53523. this._currentFrame = 0;
  53524. /**
  53525. * The original value of the runtime animation
  53526. */
  53527. this._originalValue = new Array();
  53528. /**
  53529. * The offsets cache of the runtime animation
  53530. */
  53531. this._offsetsCache = {};
  53532. /**
  53533. * The high limits cache of the runtime animation
  53534. */
  53535. this._highLimitsCache = {};
  53536. /**
  53537. * Specifies if the runtime animation has been stopped
  53538. */
  53539. this._stopped = false;
  53540. /**
  53541. * The blending factor of the runtime animation
  53542. */
  53543. this._blendingFactor = 0;
  53544. /**
  53545. * The target path of the runtime animation
  53546. */
  53547. this._targetPath = "";
  53548. /**
  53549. * The weight of the runtime animation
  53550. */
  53551. this._weight = 1.0;
  53552. /**
  53553. * The ratio offset of the runtime animation
  53554. */
  53555. this._ratioOffset = 0;
  53556. /**
  53557. * The previous delay of the runtime animation
  53558. */
  53559. this._previousDelay = 0;
  53560. /**
  53561. * The previous ratio of the runtime animation
  53562. */
  53563. this._previousRatio = 0;
  53564. this._animation = animation;
  53565. this._target = target;
  53566. this._scene = scene;
  53567. this._host = host;
  53568. animation._runtimeAnimations.push(this);
  53569. // Cloning events locally
  53570. var events = animation.getEvents();
  53571. if (events && events.length > 0) {
  53572. events.forEach(function (e) {
  53573. _this._events.push(e._clone());
  53574. });
  53575. }
  53576. }
  53577. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  53578. /**
  53579. * Gets the current frame of the runtime animation
  53580. */
  53581. get: function () {
  53582. return this._currentFrame;
  53583. },
  53584. enumerable: true,
  53585. configurable: true
  53586. });
  53587. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  53588. /**
  53589. * Gets the weight of the runtime animation
  53590. */
  53591. get: function () {
  53592. return this._weight;
  53593. },
  53594. enumerable: true,
  53595. configurable: true
  53596. });
  53597. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  53598. /**
  53599. * Gets the current value of the runtime animation
  53600. */
  53601. get: function () {
  53602. return this._currentValue;
  53603. },
  53604. enumerable: true,
  53605. configurable: true
  53606. });
  53607. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  53608. /**
  53609. * Gets the target path of the runtime animation
  53610. */
  53611. get: function () {
  53612. return this._targetPath;
  53613. },
  53614. enumerable: true,
  53615. configurable: true
  53616. });
  53617. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  53618. /**
  53619. * Gets the actual target of the runtime animation
  53620. */
  53621. get: function () {
  53622. return this._activeTarget;
  53623. },
  53624. enumerable: true,
  53625. configurable: true
  53626. });
  53627. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  53628. /**
  53629. * Gets the animation from the runtime animation
  53630. */
  53631. get: function () {
  53632. return this._animation;
  53633. },
  53634. enumerable: true,
  53635. configurable: true
  53636. });
  53637. /**
  53638. * Resets the runtime animation to the beginning
  53639. * @param restoreOriginal defines whether to restore the target property to the original value
  53640. */
  53641. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  53642. if (restoreOriginal === void 0) { restoreOriginal = false; }
  53643. if (restoreOriginal) {
  53644. if (this._target instanceof Array) {
  53645. var index = 0;
  53646. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  53647. var target = _a[_i];
  53648. if (this._originalValue[index] !== undefined) {
  53649. this._setValue(target, this._originalValue[index], -1);
  53650. }
  53651. index++;
  53652. }
  53653. }
  53654. else {
  53655. if (this._originalValue[0] !== undefined) {
  53656. this._setValue(this._target, this._originalValue[0], -1);
  53657. }
  53658. }
  53659. }
  53660. this._offsetsCache = {};
  53661. this._highLimitsCache = {};
  53662. this._currentFrame = 0;
  53663. this._blendingFactor = 0;
  53664. this._originalValue = new Array();
  53665. // Events
  53666. for (var index = 0; index < this._events.length; index++) {
  53667. this._events[index].isDone = false;
  53668. }
  53669. };
  53670. /**
  53671. * Specifies if the runtime animation is stopped
  53672. * @returns Boolean specifying if the runtime animation is stopped
  53673. */
  53674. RuntimeAnimation.prototype.isStopped = function () {
  53675. return this._stopped;
  53676. };
  53677. /**
  53678. * Disposes of the runtime animation
  53679. */
  53680. RuntimeAnimation.prototype.dispose = function () {
  53681. var index = this._animation.runtimeAnimations.indexOf(this);
  53682. if (index > -1) {
  53683. this._animation.runtimeAnimations.splice(index, 1);
  53684. }
  53685. };
  53686. /**
  53687. * Interpolates the animation from the current frame
  53688. * @param currentFrame The frame to interpolate the animation to
  53689. * @param repeatCount The number of times that the animation should loop
  53690. * @param loopMode The type of looping mode to use
  53691. * @param offsetValue Animation offset value
  53692. * @param highLimitValue The high limit value
  53693. * @returns The interpolated value
  53694. */
  53695. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  53696. this._currentFrame = currentFrame;
  53697. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  53698. this._workValue = BABYLON.Matrix.Zero();
  53699. }
  53700. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  53701. };
  53702. /**
  53703. * Apply the interpolated value to the target
  53704. * @param currentValue defines the value computed by the animation
  53705. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  53706. */
  53707. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  53708. if (weight === void 0) { weight = 1.0; }
  53709. if (this._target instanceof Array) {
  53710. var index = 0;
  53711. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  53712. var target = _a[_i];
  53713. this._setValue(target, currentValue, weight, index);
  53714. index++;
  53715. }
  53716. }
  53717. else {
  53718. this._setValue(this._target, currentValue, weight);
  53719. }
  53720. };
  53721. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  53722. if (targetIndex === void 0) { targetIndex = 0; }
  53723. // Set value
  53724. var path;
  53725. var destination;
  53726. var targetPropertyPath = this._animation.targetPropertyPath;
  53727. if (targetPropertyPath.length > 1) {
  53728. var property = target[targetPropertyPath[0]];
  53729. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  53730. property = property[targetPropertyPath[index]];
  53731. }
  53732. path = targetPropertyPath[targetPropertyPath.length - 1];
  53733. destination = property;
  53734. }
  53735. else {
  53736. path = targetPropertyPath[0];
  53737. destination = target;
  53738. }
  53739. this._targetPath = path;
  53740. this._activeTarget = destination;
  53741. this._weight = weight;
  53742. if (this._originalValue[targetIndex] === undefined) {
  53743. var originalValue = void 0;
  53744. if (destination.getRestPose && path === "_matrix") { // For bones
  53745. originalValue = destination.getRestPose();
  53746. }
  53747. else {
  53748. originalValue = destination[path];
  53749. }
  53750. if (originalValue && originalValue.clone) {
  53751. this._originalValue[targetIndex] = originalValue.clone();
  53752. }
  53753. else {
  53754. this._originalValue[targetIndex] = originalValue;
  53755. }
  53756. }
  53757. // Blending
  53758. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  53759. if (enableBlending && this._blendingFactor <= 1.0) {
  53760. if (!this._originalBlendValue) {
  53761. var originalValue = destination[path];
  53762. if (originalValue.clone) {
  53763. this._originalBlendValue = originalValue.clone();
  53764. }
  53765. else {
  53766. this._originalBlendValue = originalValue;
  53767. }
  53768. }
  53769. if (this._originalBlendValue.m) { // Matrix
  53770. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  53771. if (this._currentValue) {
  53772. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  53773. }
  53774. else {
  53775. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53776. }
  53777. }
  53778. else {
  53779. if (this._currentValue) {
  53780. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  53781. }
  53782. else {
  53783. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53784. }
  53785. }
  53786. }
  53787. else {
  53788. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53789. }
  53790. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  53791. this._blendingFactor += blendingSpeed;
  53792. }
  53793. else {
  53794. this._currentValue = currentValue;
  53795. }
  53796. if (weight !== -1.0) {
  53797. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  53798. }
  53799. else {
  53800. destination[path] = this._currentValue;
  53801. }
  53802. if (target.markAsDirty) {
  53803. target.markAsDirty(this._animation.targetProperty);
  53804. }
  53805. };
  53806. /**
  53807. * Gets the loop pmode of the runtime animation
  53808. * @returns Loop Mode
  53809. */
  53810. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  53811. if (this._target && this._target.animationPropertiesOverride) {
  53812. return this._target.animationPropertiesOverride.loopMode;
  53813. }
  53814. return this._animation.loopMode;
  53815. };
  53816. /**
  53817. * Move the current animation to a given frame
  53818. * @param frame defines the frame to move to
  53819. */
  53820. RuntimeAnimation.prototype.goToFrame = function (frame) {
  53821. var keys = this._animation.getKeys();
  53822. if (frame < keys[0].frame) {
  53823. frame = keys[0].frame;
  53824. }
  53825. else if (frame > keys[keys.length - 1].frame) {
  53826. frame = keys[keys.length - 1].frame;
  53827. }
  53828. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  53829. this.setValue(currentValue, -1);
  53830. };
  53831. /**
  53832. * @hidden Internal use only
  53833. */
  53834. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  53835. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  53836. this._ratioOffset = this._previousRatio - newRatio;
  53837. };
  53838. /**
  53839. * Execute the current animation
  53840. * @param delay defines the delay to add to the current frame
  53841. * @param from defines the lower bound of the animation range
  53842. * @param to defines the upper bound of the animation range
  53843. * @param loop defines if the current animation must loop
  53844. * @param speedRatio defines the current speed ratio
  53845. * @param weight defines the weight of the animation (default is -1 so no weight)
  53846. * @returns a boolean indicating if the animation is running
  53847. */
  53848. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  53849. if (weight === void 0) { weight = -1.0; }
  53850. var targetPropertyPath = this._animation.targetPropertyPath;
  53851. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  53852. this._stopped = true;
  53853. return false;
  53854. }
  53855. var returnValue = true;
  53856. var keys = this._animation.getKeys();
  53857. // Adding a start key at frame 0 if missing
  53858. if (keys[0].frame !== 0) {
  53859. var newKey = { frame: 0, value: keys[0].value };
  53860. keys.splice(0, 0, newKey);
  53861. }
  53862. // Adding a duplicate key when there is only one key at frame zero
  53863. else if (keys.length === 1) {
  53864. var newKey = { frame: 0.001, value: keys[0].value };
  53865. keys.push(newKey);
  53866. }
  53867. // Check limits
  53868. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  53869. from = keys[0].frame;
  53870. }
  53871. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  53872. to = keys[keys.length - 1].frame;
  53873. }
  53874. //to and from cannot be the same key
  53875. if (from === to) {
  53876. if (from > keys[0].frame) {
  53877. from--;
  53878. }
  53879. else if (to < keys[keys.length - 1].frame) {
  53880. to++;
  53881. }
  53882. }
  53883. // Compute ratio
  53884. var range = to - from;
  53885. var offsetValue;
  53886. // ratio represents the frame delta between from and to
  53887. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  53888. var highLimitValue = 0;
  53889. this._previousDelay = delay;
  53890. this._previousRatio = ratio;
  53891. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  53892. returnValue = false;
  53893. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  53894. }
  53895. else {
  53896. // Get max value if required
  53897. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  53898. var keyOffset = to.toString() + from.toString();
  53899. if (!this._offsetsCache[keyOffset]) {
  53900. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53901. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53902. switch (this._animation.dataType) {
  53903. // Float
  53904. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53905. this._offsetsCache[keyOffset] = toValue - fromValue;
  53906. break;
  53907. // Quaternion
  53908. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53909. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53910. break;
  53911. // Vector3
  53912. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53913. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53914. // Vector2
  53915. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53916. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53917. // Size
  53918. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53919. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53920. // Color3
  53921. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53922. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53923. default:
  53924. break;
  53925. }
  53926. this._highLimitsCache[keyOffset] = toValue;
  53927. }
  53928. highLimitValue = this._highLimitsCache[keyOffset];
  53929. offsetValue = this._offsetsCache[keyOffset];
  53930. }
  53931. }
  53932. if (offsetValue === undefined) {
  53933. switch (this._animation.dataType) {
  53934. // Float
  53935. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53936. offsetValue = 0;
  53937. break;
  53938. // Quaternion
  53939. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53940. offsetValue = _staticOffsetValueQuaternion;
  53941. break;
  53942. // Vector3
  53943. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53944. offsetValue = _staticOffsetValueVector3;
  53945. break;
  53946. // Vector2
  53947. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53948. offsetValue = _staticOffsetValueVector2;
  53949. break;
  53950. // Size
  53951. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53952. offsetValue = _staticOffsetValueSize;
  53953. break;
  53954. // Color3
  53955. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53956. offsetValue = _staticOffsetValueColor3;
  53957. }
  53958. }
  53959. // Compute value
  53960. var repeatCount = (ratio / range) >> 0;
  53961. var currentFrame = returnValue ? from + ratio % range : to;
  53962. // Need to normalize?
  53963. if (this._host && this._host.syncRoot) {
  53964. var syncRoot = this._host.syncRoot;
  53965. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  53966. currentFrame = from + (to - from) * hostNormalizedFrame;
  53967. }
  53968. // Reset events if looping
  53969. var events = this._events;
  53970. if (range > 0 && this.currentFrame > currentFrame ||
  53971. range < 0 && this.currentFrame < currentFrame) {
  53972. // Need to reset animation events
  53973. for (var index = 0; index < events.length; index++) {
  53974. if (!events[index].onlyOnce) {
  53975. // reset event, the animation is looping
  53976. events[index].isDone = false;
  53977. }
  53978. }
  53979. }
  53980. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  53981. // Set value
  53982. this.setValue(currentValue, weight);
  53983. // Check events
  53984. for (var index = 0; index < events.length; index++) {
  53985. // Make sure current frame has passed event frame and that event frame is within the current range
  53986. // Also, handle both forward and reverse animations
  53987. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  53988. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  53989. var event = events[index];
  53990. if (!event.isDone) {
  53991. // If event should be done only once, remove it.
  53992. if (event.onlyOnce) {
  53993. events.splice(index, 1);
  53994. index--;
  53995. }
  53996. event.isDone = true;
  53997. event.action(currentFrame);
  53998. } // Don't do anything if the event has already be done.
  53999. }
  54000. }
  54001. if (!returnValue) {
  54002. this._stopped = true;
  54003. }
  54004. return returnValue;
  54005. };
  54006. return RuntimeAnimation;
  54007. }());
  54008. BABYLON.RuntimeAnimation = RuntimeAnimation;
  54009. })(BABYLON || (BABYLON = {}));
  54010. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  54011. var BABYLON;
  54012. (function (BABYLON) {
  54013. /**
  54014. * Class used to store an actual running animation
  54015. */
  54016. var Animatable = /** @class */ (function () {
  54017. /**
  54018. * Creates a new Animatable
  54019. * @param scene defines the hosting scene
  54020. * @param target defines the target object
  54021. * @param fromFrame defines the starting frame number (default is 0)
  54022. * @param toFrame defines the ending frame number (default is 100)
  54023. * @param loopAnimation defines if the animation must loop (default is false)
  54024. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  54025. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  54026. * @param animations defines a group of animation to add to the new Animatable
  54027. */
  54028. function Animatable(scene,
  54029. /** defines the target object */
  54030. target,
  54031. /** defines the starting frame number (default is 0) */
  54032. fromFrame,
  54033. /** defines the ending frame number (default is 100) */
  54034. toFrame,
  54035. /** defines if the animation must loop (default is false) */
  54036. loopAnimation, speedRatio,
  54037. /** defines a callback to call when animation ends if it is not looping */
  54038. onAnimationEnd, animations) {
  54039. if (fromFrame === void 0) { fromFrame = 0; }
  54040. if (toFrame === void 0) { toFrame = 100; }
  54041. if (loopAnimation === void 0) { loopAnimation = false; }
  54042. if (speedRatio === void 0) { speedRatio = 1.0; }
  54043. this.target = target;
  54044. this.fromFrame = fromFrame;
  54045. this.toFrame = toFrame;
  54046. this.loopAnimation = loopAnimation;
  54047. this.onAnimationEnd = onAnimationEnd;
  54048. this._localDelayOffset = null;
  54049. this._pausedDelay = null;
  54050. this._runtimeAnimations = new Array();
  54051. this._paused = false;
  54052. this._speedRatio = 1;
  54053. this._weight = -1.0;
  54054. /**
  54055. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  54056. * This will only apply for non looping animation (default is true)
  54057. */
  54058. this.disposeOnEnd = true;
  54059. /**
  54060. * Gets a boolean indicating if the animation has started
  54061. */
  54062. this.animationStarted = false;
  54063. /**
  54064. * Observer raised when the animation ends
  54065. */
  54066. this.onAnimationEndObservable = new BABYLON.Observable();
  54067. this._scene = scene;
  54068. if (animations) {
  54069. this.appendAnimations(target, animations);
  54070. }
  54071. this._speedRatio = speedRatio;
  54072. scene._activeAnimatables.push(this);
  54073. }
  54074. Object.defineProperty(Animatable.prototype, "syncRoot", {
  54075. /**
  54076. * Gets the root Animatable used to synchronize and normalize animations
  54077. */
  54078. get: function () {
  54079. return this._syncRoot;
  54080. },
  54081. enumerable: true,
  54082. configurable: true
  54083. });
  54084. Object.defineProperty(Animatable.prototype, "masterFrame", {
  54085. /**
  54086. * Gets the current frame of the first RuntimeAnimation
  54087. * Used to synchronize Animatables
  54088. */
  54089. get: function () {
  54090. if (this._runtimeAnimations.length === 0) {
  54091. return 0;
  54092. }
  54093. return this._runtimeAnimations[0].currentFrame;
  54094. },
  54095. enumerable: true,
  54096. configurable: true
  54097. });
  54098. Object.defineProperty(Animatable.prototype, "weight", {
  54099. /**
  54100. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  54101. */
  54102. get: function () {
  54103. return this._weight;
  54104. },
  54105. set: function (value) {
  54106. if (value === -1) { // -1 is ok and means no weight
  54107. this._weight = -1;
  54108. return;
  54109. }
  54110. // Else weight must be in [0, 1] range
  54111. this._weight = Math.min(Math.max(value, 0), 1.0);
  54112. },
  54113. enumerable: true,
  54114. configurable: true
  54115. });
  54116. Object.defineProperty(Animatable.prototype, "speedRatio", {
  54117. /**
  54118. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  54119. */
  54120. get: function () {
  54121. return this._speedRatio;
  54122. },
  54123. set: function (value) {
  54124. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  54125. var animation = this._runtimeAnimations[index];
  54126. animation._prepareForSpeedRatioChange(value);
  54127. }
  54128. this._speedRatio = value;
  54129. },
  54130. enumerable: true,
  54131. configurable: true
  54132. });
  54133. // Methods
  54134. /**
  54135. * Synchronize and normalize current Animatable with a source Animatable
  54136. * This is useful when using animation weights and when animations are not of the same length
  54137. * @param root defines the root Animatable to synchronize with
  54138. * @returns the current Animatable
  54139. */
  54140. Animatable.prototype.syncWith = function (root) {
  54141. this._syncRoot = root;
  54142. if (root) {
  54143. // Make sure this animatable will animate after the root
  54144. var index = this._scene._activeAnimatables.indexOf(this);
  54145. if (index > -1) {
  54146. this._scene._activeAnimatables.splice(index, 1);
  54147. this._scene._activeAnimatables.push(this);
  54148. }
  54149. }
  54150. return this;
  54151. };
  54152. /**
  54153. * Gets the list of runtime animations
  54154. * @returns an array of RuntimeAnimation
  54155. */
  54156. Animatable.prototype.getAnimations = function () {
  54157. return this._runtimeAnimations;
  54158. };
  54159. /**
  54160. * Adds more animations to the current animatable
  54161. * @param target defines the target of the animations
  54162. * @param animations defines the new animations to add
  54163. */
  54164. Animatable.prototype.appendAnimations = function (target, animations) {
  54165. for (var index = 0; index < animations.length; index++) {
  54166. var animation = animations[index];
  54167. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  54168. }
  54169. };
  54170. /**
  54171. * Gets the source animation for a specific property
  54172. * @param property defines the propertyu to look for
  54173. * @returns null or the source animation for the given property
  54174. */
  54175. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  54176. var runtimeAnimations = this._runtimeAnimations;
  54177. for (var index = 0; index < runtimeAnimations.length; index++) {
  54178. if (runtimeAnimations[index].animation.targetProperty === property) {
  54179. return runtimeAnimations[index].animation;
  54180. }
  54181. }
  54182. return null;
  54183. };
  54184. /**
  54185. * Gets the runtime animation for a specific property
  54186. * @param property defines the propertyu to look for
  54187. * @returns null or the runtime animation for the given property
  54188. */
  54189. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  54190. var runtimeAnimations = this._runtimeAnimations;
  54191. for (var index = 0; index < runtimeAnimations.length; index++) {
  54192. if (runtimeAnimations[index].animation.targetProperty === property) {
  54193. return runtimeAnimations[index];
  54194. }
  54195. }
  54196. return null;
  54197. };
  54198. /**
  54199. * Resets the animatable to its original state
  54200. */
  54201. Animatable.prototype.reset = function () {
  54202. var runtimeAnimations = this._runtimeAnimations;
  54203. for (var index = 0; index < runtimeAnimations.length; index++) {
  54204. runtimeAnimations[index].reset(true);
  54205. }
  54206. this._localDelayOffset = null;
  54207. this._pausedDelay = null;
  54208. };
  54209. /**
  54210. * Allows the animatable to blend with current running animations
  54211. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  54212. * @param blendingSpeed defines the blending speed to use
  54213. */
  54214. Animatable.prototype.enableBlending = function (blendingSpeed) {
  54215. var runtimeAnimations = this._runtimeAnimations;
  54216. for (var index = 0; index < runtimeAnimations.length; index++) {
  54217. runtimeAnimations[index].animation.enableBlending = true;
  54218. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  54219. }
  54220. };
  54221. /**
  54222. * Disable animation blending
  54223. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  54224. */
  54225. Animatable.prototype.disableBlending = function () {
  54226. var runtimeAnimations = this._runtimeAnimations;
  54227. for (var index = 0; index < runtimeAnimations.length; index++) {
  54228. runtimeAnimations[index].animation.enableBlending = false;
  54229. }
  54230. };
  54231. /**
  54232. * Jump directly to a given frame
  54233. * @param frame defines the frame to jump to
  54234. */
  54235. Animatable.prototype.goToFrame = function (frame) {
  54236. var runtimeAnimations = this._runtimeAnimations;
  54237. if (runtimeAnimations[0]) {
  54238. var fps = runtimeAnimations[0].animation.framePerSecond;
  54239. var currentFrame = runtimeAnimations[0].currentFrame;
  54240. var adjustTime = frame - currentFrame;
  54241. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  54242. if (this._localDelayOffset === null) {
  54243. this._localDelayOffset = 0;
  54244. }
  54245. this._localDelayOffset -= delay;
  54246. }
  54247. for (var index = 0; index < runtimeAnimations.length; index++) {
  54248. runtimeAnimations[index].goToFrame(frame);
  54249. }
  54250. };
  54251. /**
  54252. * Pause the animation
  54253. */
  54254. Animatable.prototype.pause = function () {
  54255. if (this._paused) {
  54256. return;
  54257. }
  54258. this._paused = true;
  54259. };
  54260. /**
  54261. * Restart the animation
  54262. */
  54263. Animatable.prototype.restart = function () {
  54264. this._paused = false;
  54265. };
  54266. Animatable.prototype._raiseOnAnimationEnd = function () {
  54267. if (this.onAnimationEnd) {
  54268. this.onAnimationEnd();
  54269. }
  54270. this.onAnimationEndObservable.notifyObservers(this);
  54271. };
  54272. /**
  54273. * Stop and delete the current animation
  54274. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  54275. * @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)
  54276. */
  54277. Animatable.prototype.stop = function (animationName, targetMask) {
  54278. if (animationName || targetMask) {
  54279. var idx = this._scene._activeAnimatables.indexOf(this);
  54280. if (idx > -1) {
  54281. var runtimeAnimations = this._runtimeAnimations;
  54282. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  54283. var runtimeAnimation = runtimeAnimations[index];
  54284. if (animationName && runtimeAnimation.animation.name != animationName) {
  54285. continue;
  54286. }
  54287. if (targetMask && !targetMask(runtimeAnimation.target)) {
  54288. continue;
  54289. }
  54290. runtimeAnimation.dispose();
  54291. runtimeAnimations.splice(index, 1);
  54292. }
  54293. if (runtimeAnimations.length == 0) {
  54294. this._scene._activeAnimatables.splice(idx, 1);
  54295. this._raiseOnAnimationEnd();
  54296. }
  54297. }
  54298. }
  54299. else {
  54300. var index = this._scene._activeAnimatables.indexOf(this);
  54301. if (index > -1) {
  54302. this._scene._activeAnimatables.splice(index, 1);
  54303. var runtimeAnimations = this._runtimeAnimations;
  54304. for (var index = 0; index < runtimeAnimations.length; index++) {
  54305. runtimeAnimations[index].dispose();
  54306. }
  54307. this._raiseOnAnimationEnd();
  54308. }
  54309. }
  54310. };
  54311. /**
  54312. * Wait asynchronously for the animation to end
  54313. * @returns a promise which will be fullfilled when the animation ends
  54314. */
  54315. Animatable.prototype.waitAsync = function () {
  54316. var _this = this;
  54317. return new Promise(function (resolve, reject) {
  54318. _this.onAnimationEndObservable.add(function () {
  54319. resolve(_this);
  54320. }, undefined, undefined, _this, true);
  54321. });
  54322. };
  54323. /** @hidden */
  54324. Animatable.prototype._animate = function (delay) {
  54325. if (this._paused) {
  54326. this.animationStarted = false;
  54327. if (this._pausedDelay === null) {
  54328. this._pausedDelay = delay;
  54329. }
  54330. return true;
  54331. }
  54332. if (this._localDelayOffset === null) {
  54333. this._localDelayOffset = delay;
  54334. this._pausedDelay = null;
  54335. }
  54336. else if (this._pausedDelay !== null) {
  54337. this._localDelayOffset += delay - this._pausedDelay;
  54338. this._pausedDelay = null;
  54339. }
  54340. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  54341. return true;
  54342. }
  54343. // Animating
  54344. var running = false;
  54345. var runtimeAnimations = this._runtimeAnimations;
  54346. var index;
  54347. for (index = 0; index < runtimeAnimations.length; index++) {
  54348. var animation = runtimeAnimations[index];
  54349. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  54350. running = running || isRunning;
  54351. }
  54352. this.animationStarted = running;
  54353. if (!running) {
  54354. if (this.disposeOnEnd) {
  54355. // Remove from active animatables
  54356. index = this._scene._activeAnimatables.indexOf(this);
  54357. this._scene._activeAnimatables.splice(index, 1);
  54358. // Dispose all runtime animations
  54359. for (index = 0; index < runtimeAnimations.length; index++) {
  54360. runtimeAnimations[index].dispose();
  54361. }
  54362. }
  54363. this._raiseOnAnimationEnd();
  54364. if (this.disposeOnEnd) {
  54365. this.onAnimationEnd = null;
  54366. this.onAnimationEndObservable.clear();
  54367. }
  54368. }
  54369. return running;
  54370. };
  54371. return Animatable;
  54372. }());
  54373. BABYLON.Animatable = Animatable;
  54374. })(BABYLON || (BABYLON = {}));
  54375. //# sourceMappingURL=babylon.animatable.js.map
  54376. var BABYLON;
  54377. (function (BABYLON) {
  54378. /**
  54379. * Base class used for every default easing function.
  54380. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54381. */
  54382. var EasingFunction = /** @class */ (function () {
  54383. function EasingFunction() {
  54384. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  54385. }
  54386. /**
  54387. * Sets the easing mode of the current function.
  54388. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  54389. */
  54390. EasingFunction.prototype.setEasingMode = function (easingMode) {
  54391. var n = Math.min(Math.max(easingMode, 0), 2);
  54392. this._easingMode = n;
  54393. };
  54394. /**
  54395. * Gets the current easing mode.
  54396. * @returns the easing mode
  54397. */
  54398. EasingFunction.prototype.getEasingMode = function () {
  54399. return this._easingMode;
  54400. };
  54401. /**
  54402. * @hidden
  54403. */
  54404. EasingFunction.prototype.easeInCore = function (gradient) {
  54405. throw new Error('You must implement this method');
  54406. };
  54407. /**
  54408. * Given an input gradient between 0 and 1, this returns the corrseponding value
  54409. * of the easing function.
  54410. * @param gradient Defines the value between 0 and 1 we want the easing value for
  54411. * @returns the corresponding value on the curve defined by the easing function
  54412. */
  54413. EasingFunction.prototype.ease = function (gradient) {
  54414. switch (this._easingMode) {
  54415. case EasingFunction.EASINGMODE_EASEIN:
  54416. return this.easeInCore(gradient);
  54417. case EasingFunction.EASINGMODE_EASEOUT:
  54418. return (1 - this.easeInCore(1 - gradient));
  54419. }
  54420. if (gradient >= 0.5) {
  54421. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  54422. }
  54423. return (this.easeInCore(gradient * 2) * 0.5);
  54424. };
  54425. /**
  54426. * Interpolation follows the mathematical formula associated with the easing function.
  54427. */
  54428. EasingFunction.EASINGMODE_EASEIN = 0;
  54429. /**
  54430. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  54431. */
  54432. EasingFunction.EASINGMODE_EASEOUT = 1;
  54433. /**
  54434. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  54435. */
  54436. EasingFunction.EASINGMODE_EASEINOUT = 2;
  54437. return EasingFunction;
  54438. }());
  54439. BABYLON.EasingFunction = EasingFunction;
  54440. /**
  54441. * Easing function with a circle shape (see link below).
  54442. * @see https://easings.net/#easeInCirc
  54443. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54444. */
  54445. var CircleEase = /** @class */ (function (_super) {
  54446. __extends(CircleEase, _super);
  54447. function CircleEase() {
  54448. return _super !== null && _super.apply(this, arguments) || this;
  54449. }
  54450. /** @hidden */
  54451. CircleEase.prototype.easeInCore = function (gradient) {
  54452. gradient = Math.max(0, Math.min(1, gradient));
  54453. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  54454. };
  54455. return CircleEase;
  54456. }(EasingFunction));
  54457. BABYLON.CircleEase = CircleEase;
  54458. /**
  54459. * Easing function with a ease back shape (see link below).
  54460. * @see https://easings.net/#easeInBack
  54461. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54462. */
  54463. var BackEase = /** @class */ (function (_super) {
  54464. __extends(BackEase, _super);
  54465. /**
  54466. * Instantiates a back ease easing
  54467. * @see https://easings.net/#easeInBack
  54468. * @param amplitude Defines the amplitude of the function
  54469. */
  54470. function BackEase(
  54471. /** Defines the amplitude of the function */
  54472. amplitude) {
  54473. if (amplitude === void 0) { amplitude = 1; }
  54474. var _this = _super.call(this) || this;
  54475. _this.amplitude = amplitude;
  54476. return _this;
  54477. }
  54478. /** @hidden */
  54479. BackEase.prototype.easeInCore = function (gradient) {
  54480. var num = Math.max(0, this.amplitude);
  54481. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  54482. };
  54483. return BackEase;
  54484. }(EasingFunction));
  54485. BABYLON.BackEase = BackEase;
  54486. /**
  54487. * Easing function with a bouncing shape (see link below).
  54488. * @see https://easings.net/#easeInBounce
  54489. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54490. */
  54491. var BounceEase = /** @class */ (function (_super) {
  54492. __extends(BounceEase, _super);
  54493. /**
  54494. * Instantiates a bounce easing
  54495. * @see https://easings.net/#easeInBounce
  54496. * @param bounces Defines the number of bounces
  54497. * @param bounciness Defines the amplitude of the bounce
  54498. */
  54499. function BounceEase(
  54500. /** Defines the number of bounces */
  54501. bounces,
  54502. /** Defines the amplitude of the bounce */
  54503. bounciness) {
  54504. if (bounces === void 0) { bounces = 3; }
  54505. if (bounciness === void 0) { bounciness = 2; }
  54506. var _this = _super.call(this) || this;
  54507. _this.bounces = bounces;
  54508. _this.bounciness = bounciness;
  54509. return _this;
  54510. }
  54511. /** @hidden */
  54512. BounceEase.prototype.easeInCore = function (gradient) {
  54513. var y = Math.max(0.0, this.bounces);
  54514. var bounciness = this.bounciness;
  54515. if (bounciness <= 1.0) {
  54516. bounciness = 1.001;
  54517. }
  54518. var num9 = Math.pow(bounciness, y);
  54519. var num5 = 1.0 - bounciness;
  54520. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  54521. var num15 = gradient * num4;
  54522. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  54523. var num3 = Math.floor(num65);
  54524. var num13 = num3 + 1.0;
  54525. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  54526. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  54527. var num7 = (num8 + num12) * 0.5;
  54528. var num6 = gradient - num7;
  54529. var num2 = num7 - num8;
  54530. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  54531. };
  54532. return BounceEase;
  54533. }(EasingFunction));
  54534. BABYLON.BounceEase = BounceEase;
  54535. /**
  54536. * Easing function with a power of 3 shape (see link below).
  54537. * @see https://easings.net/#easeInCubic
  54538. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54539. */
  54540. var CubicEase = /** @class */ (function (_super) {
  54541. __extends(CubicEase, _super);
  54542. function CubicEase() {
  54543. return _super !== null && _super.apply(this, arguments) || this;
  54544. }
  54545. /** @hidden */
  54546. CubicEase.prototype.easeInCore = function (gradient) {
  54547. return (gradient * gradient * gradient);
  54548. };
  54549. return CubicEase;
  54550. }(EasingFunction));
  54551. BABYLON.CubicEase = CubicEase;
  54552. /**
  54553. * Easing function with an elastic shape (see link below).
  54554. * @see https://easings.net/#easeInElastic
  54555. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54556. */
  54557. var ElasticEase = /** @class */ (function (_super) {
  54558. __extends(ElasticEase, _super);
  54559. /**
  54560. * Instantiates an elastic easing function
  54561. * @see https://easings.net/#easeInElastic
  54562. * @param oscillations Defines the number of oscillations
  54563. * @param springiness Defines the amplitude of the oscillations
  54564. */
  54565. function ElasticEase(
  54566. /** Defines the number of oscillations*/
  54567. oscillations,
  54568. /** Defines the amplitude of the oscillations*/
  54569. springiness) {
  54570. if (oscillations === void 0) { oscillations = 3; }
  54571. if (springiness === void 0) { springiness = 3; }
  54572. var _this = _super.call(this) || this;
  54573. _this.oscillations = oscillations;
  54574. _this.springiness = springiness;
  54575. return _this;
  54576. }
  54577. /** @hidden */
  54578. ElasticEase.prototype.easeInCore = function (gradient) {
  54579. var num2;
  54580. var num3 = Math.max(0.0, this.oscillations);
  54581. var num = Math.max(0.0, this.springiness);
  54582. if (num == 0) {
  54583. num2 = gradient;
  54584. }
  54585. else {
  54586. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  54587. }
  54588. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  54589. };
  54590. return ElasticEase;
  54591. }(EasingFunction));
  54592. BABYLON.ElasticEase = ElasticEase;
  54593. /**
  54594. * Easing function with an exponential shape (see link below).
  54595. * @see https://easings.net/#easeInExpo
  54596. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54597. */
  54598. var ExponentialEase = /** @class */ (function (_super) {
  54599. __extends(ExponentialEase, _super);
  54600. /**
  54601. * Instantiates an exponential easing function
  54602. * @see https://easings.net/#easeInExpo
  54603. * @param exponent Defines the exponent of the function
  54604. */
  54605. function ExponentialEase(
  54606. /** Defines the exponent of the function */
  54607. exponent) {
  54608. if (exponent === void 0) { exponent = 2; }
  54609. var _this = _super.call(this) || this;
  54610. _this.exponent = exponent;
  54611. return _this;
  54612. }
  54613. /** @hidden */
  54614. ExponentialEase.prototype.easeInCore = function (gradient) {
  54615. if (this.exponent <= 0) {
  54616. return gradient;
  54617. }
  54618. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  54619. };
  54620. return ExponentialEase;
  54621. }(EasingFunction));
  54622. BABYLON.ExponentialEase = ExponentialEase;
  54623. /**
  54624. * Easing function with a power shape (see link below).
  54625. * @see https://easings.net/#easeInQuad
  54626. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54627. */
  54628. var PowerEase = /** @class */ (function (_super) {
  54629. __extends(PowerEase, _super);
  54630. /**
  54631. * Instantiates an power base easing function
  54632. * @see https://easings.net/#easeInQuad
  54633. * @param power Defines the power of the function
  54634. */
  54635. function PowerEase(
  54636. /** Defines the power of the function */
  54637. power) {
  54638. if (power === void 0) { power = 2; }
  54639. var _this = _super.call(this) || this;
  54640. _this.power = power;
  54641. return _this;
  54642. }
  54643. /** @hidden */
  54644. PowerEase.prototype.easeInCore = function (gradient) {
  54645. var y = Math.max(0.0, this.power);
  54646. return Math.pow(gradient, y);
  54647. };
  54648. return PowerEase;
  54649. }(EasingFunction));
  54650. BABYLON.PowerEase = PowerEase;
  54651. /**
  54652. * Easing function with a power of 2 shape (see link below).
  54653. * @see https://easings.net/#easeInQuad
  54654. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54655. */
  54656. var QuadraticEase = /** @class */ (function (_super) {
  54657. __extends(QuadraticEase, _super);
  54658. function QuadraticEase() {
  54659. return _super !== null && _super.apply(this, arguments) || this;
  54660. }
  54661. /** @hidden */
  54662. QuadraticEase.prototype.easeInCore = function (gradient) {
  54663. return (gradient * gradient);
  54664. };
  54665. return QuadraticEase;
  54666. }(EasingFunction));
  54667. BABYLON.QuadraticEase = QuadraticEase;
  54668. /**
  54669. * Easing function with a power of 4 shape (see link below).
  54670. * @see https://easings.net/#easeInQuart
  54671. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54672. */
  54673. var QuarticEase = /** @class */ (function (_super) {
  54674. __extends(QuarticEase, _super);
  54675. function QuarticEase() {
  54676. return _super !== null && _super.apply(this, arguments) || this;
  54677. }
  54678. /** @hidden */
  54679. QuarticEase.prototype.easeInCore = function (gradient) {
  54680. return (gradient * gradient * gradient * gradient);
  54681. };
  54682. return QuarticEase;
  54683. }(EasingFunction));
  54684. BABYLON.QuarticEase = QuarticEase;
  54685. /**
  54686. * Easing function with a power of 5 shape (see link below).
  54687. * @see https://easings.net/#easeInQuint
  54688. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54689. */
  54690. var QuinticEase = /** @class */ (function (_super) {
  54691. __extends(QuinticEase, _super);
  54692. function QuinticEase() {
  54693. return _super !== null && _super.apply(this, arguments) || this;
  54694. }
  54695. /** @hidden */
  54696. QuinticEase.prototype.easeInCore = function (gradient) {
  54697. return (gradient * gradient * gradient * gradient * gradient);
  54698. };
  54699. return QuinticEase;
  54700. }(EasingFunction));
  54701. BABYLON.QuinticEase = QuinticEase;
  54702. /**
  54703. * Easing function with a sin shape (see link below).
  54704. * @see https://easings.net/#easeInSine
  54705. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54706. */
  54707. var SineEase = /** @class */ (function (_super) {
  54708. __extends(SineEase, _super);
  54709. function SineEase() {
  54710. return _super !== null && _super.apply(this, arguments) || this;
  54711. }
  54712. /** @hidden */
  54713. SineEase.prototype.easeInCore = function (gradient) {
  54714. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  54715. };
  54716. return SineEase;
  54717. }(EasingFunction));
  54718. BABYLON.SineEase = SineEase;
  54719. /**
  54720. * Easing function with a bezier shape (see link below).
  54721. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  54722. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54723. */
  54724. var BezierCurveEase = /** @class */ (function (_super) {
  54725. __extends(BezierCurveEase, _super);
  54726. /**
  54727. * Instantiates a bezier function
  54728. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  54729. * @param x1 Defines the x component of the start tangent in the bezier curve
  54730. * @param y1 Defines the y component of the start tangent in the bezier curve
  54731. * @param x2 Defines the x component of the end tangent in the bezier curve
  54732. * @param y2 Defines the y component of the end tangent in the bezier curve
  54733. */
  54734. function BezierCurveEase(
  54735. /** Defines the x component of the start tangent in the bezier curve */
  54736. x1,
  54737. /** Defines the y component of the start tangent in the bezier curve */
  54738. y1,
  54739. /** Defines the x component of the end tangent in the bezier curve */
  54740. x2,
  54741. /** Defines the y component of the end tangent in the bezier curve */
  54742. y2) {
  54743. if (x1 === void 0) { x1 = 0; }
  54744. if (y1 === void 0) { y1 = 0; }
  54745. if (x2 === void 0) { x2 = 1; }
  54746. if (y2 === void 0) { y2 = 1; }
  54747. var _this = _super.call(this) || this;
  54748. _this.x1 = x1;
  54749. _this.y1 = y1;
  54750. _this.x2 = x2;
  54751. _this.y2 = y2;
  54752. return _this;
  54753. }
  54754. /** @hidden */
  54755. BezierCurveEase.prototype.easeInCore = function (gradient) {
  54756. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  54757. };
  54758. return BezierCurveEase;
  54759. }(EasingFunction));
  54760. BABYLON.BezierCurveEase = BezierCurveEase;
  54761. })(BABYLON || (BABYLON = {}));
  54762. //# sourceMappingURL=babylon.easing.js.map
  54763. var BABYLON;
  54764. (function (BABYLON) {
  54765. /**
  54766. * A Condition applied to an Action
  54767. */
  54768. var Condition = /** @class */ (function () {
  54769. /**
  54770. * Creates a new Condition
  54771. * @param actionManager the manager of the action the condition is applied to
  54772. */
  54773. function Condition(actionManager) {
  54774. this._actionManager = actionManager;
  54775. }
  54776. /**
  54777. * Check if the current condition is valid
  54778. * @returns a boolean
  54779. */
  54780. Condition.prototype.isValid = function () {
  54781. return true;
  54782. };
  54783. /**
  54784. * Internal only
  54785. * @hidden
  54786. */
  54787. Condition.prototype._getProperty = function (propertyPath) {
  54788. return this._actionManager._getProperty(propertyPath);
  54789. };
  54790. /**
  54791. * Internal only
  54792. * @hidden
  54793. */
  54794. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  54795. return this._actionManager._getEffectiveTarget(target, propertyPath);
  54796. };
  54797. /**
  54798. * Serialize placeholder for child classes
  54799. * @returns the serialized object
  54800. */
  54801. Condition.prototype.serialize = function () {
  54802. };
  54803. /**
  54804. * Internal only
  54805. * @hidden
  54806. */
  54807. Condition.prototype._serialize = function (serializedCondition) {
  54808. return {
  54809. type: 2,
  54810. children: [],
  54811. name: serializedCondition.name,
  54812. properties: serializedCondition.properties
  54813. };
  54814. };
  54815. return Condition;
  54816. }());
  54817. BABYLON.Condition = Condition;
  54818. /**
  54819. * Defines specific conditional operators as extensions of Condition
  54820. */
  54821. var ValueCondition = /** @class */ (function (_super) {
  54822. __extends(ValueCondition, _super);
  54823. /**
  54824. * Creates a new ValueCondition
  54825. * @param actionManager manager for the action the condition applies to
  54826. * @param target for the action
  54827. * @param propertyPath path to specify the property of the target the conditional operator uses
  54828. * @param value the value compared by the conditional operator against the current value of the property
  54829. * @param operator the conditional operator, default ValueCondition.IsEqual
  54830. */
  54831. function ValueCondition(actionManager, target,
  54832. /** path to specify the property of the target the conditional operator uses */
  54833. propertyPath,
  54834. /** the value compared by the conditional operator against the current value of the property */
  54835. value,
  54836. /** the conditional operator, default ValueCondition.IsEqual */
  54837. operator) {
  54838. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  54839. var _this = _super.call(this, actionManager) || this;
  54840. _this.propertyPath = propertyPath;
  54841. _this.value = value;
  54842. _this.operator = operator;
  54843. _this._target = target;
  54844. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  54845. _this._property = _this._getProperty(_this.propertyPath);
  54846. return _this;
  54847. }
  54848. Object.defineProperty(ValueCondition, "IsEqual", {
  54849. /**
  54850. * returns the number for IsEqual
  54851. */
  54852. get: function () {
  54853. return ValueCondition._IsEqual;
  54854. },
  54855. enumerable: true,
  54856. configurable: true
  54857. });
  54858. Object.defineProperty(ValueCondition, "IsDifferent", {
  54859. /**
  54860. * Returns the number for IsDifferent
  54861. */
  54862. get: function () {
  54863. return ValueCondition._IsDifferent;
  54864. },
  54865. enumerable: true,
  54866. configurable: true
  54867. });
  54868. Object.defineProperty(ValueCondition, "IsGreater", {
  54869. /**
  54870. * Returns the number for IsGreater
  54871. */
  54872. get: function () {
  54873. return ValueCondition._IsGreater;
  54874. },
  54875. enumerable: true,
  54876. configurable: true
  54877. });
  54878. Object.defineProperty(ValueCondition, "IsLesser", {
  54879. /**
  54880. * Returns the number for IsLesser
  54881. */
  54882. get: function () {
  54883. return ValueCondition._IsLesser;
  54884. },
  54885. enumerable: true,
  54886. configurable: true
  54887. });
  54888. /**
  54889. * Compares the given value with the property value for the specified conditional operator
  54890. * @returns the result of the comparison
  54891. */
  54892. ValueCondition.prototype.isValid = function () {
  54893. switch (this.operator) {
  54894. case ValueCondition.IsGreater:
  54895. return this._effectiveTarget[this._property] > this.value;
  54896. case ValueCondition.IsLesser:
  54897. return this._effectiveTarget[this._property] < this.value;
  54898. case ValueCondition.IsEqual:
  54899. case ValueCondition.IsDifferent:
  54900. var check;
  54901. if (this.value.equals) {
  54902. check = this.value.equals(this._effectiveTarget[this._property]);
  54903. }
  54904. else {
  54905. check = this.value === this._effectiveTarget[this._property];
  54906. }
  54907. return this.operator === ValueCondition.IsEqual ? check : !check;
  54908. }
  54909. return false;
  54910. };
  54911. /**
  54912. * Serialize the ValueCondition into a JSON compatible object
  54913. * @returns serialization object
  54914. */
  54915. ValueCondition.prototype.serialize = function () {
  54916. return this._serialize({
  54917. name: "ValueCondition",
  54918. properties: [
  54919. BABYLON.Action._GetTargetProperty(this._target),
  54920. { name: "propertyPath", value: this.propertyPath },
  54921. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54922. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  54923. ]
  54924. });
  54925. };
  54926. /**
  54927. * Gets the name of the conditional operator for the ValueCondition
  54928. * @param operator the conditional operator
  54929. * @returns the name
  54930. */
  54931. ValueCondition.GetOperatorName = function (operator) {
  54932. switch (operator) {
  54933. case ValueCondition._IsEqual: return "IsEqual";
  54934. case ValueCondition._IsDifferent: return "IsDifferent";
  54935. case ValueCondition._IsGreater: return "IsGreater";
  54936. case ValueCondition._IsLesser: return "IsLesser";
  54937. default: return "";
  54938. }
  54939. };
  54940. /**
  54941. * Internal only
  54942. * @hidden
  54943. */
  54944. ValueCondition._IsEqual = 0;
  54945. /**
  54946. * Internal only
  54947. * @hidden
  54948. */
  54949. ValueCondition._IsDifferent = 1;
  54950. /**
  54951. * Internal only
  54952. * @hidden
  54953. */
  54954. ValueCondition._IsGreater = 2;
  54955. /**
  54956. * Internal only
  54957. * @hidden
  54958. */
  54959. ValueCondition._IsLesser = 3;
  54960. return ValueCondition;
  54961. }(Condition));
  54962. BABYLON.ValueCondition = ValueCondition;
  54963. /**
  54964. * Defines a predicate condition as an extension of Condition
  54965. */
  54966. var PredicateCondition = /** @class */ (function (_super) {
  54967. __extends(PredicateCondition, _super);
  54968. /**
  54969. * Creates a new PredicateCondition
  54970. * @param actionManager manager for the action the condition applies to
  54971. * @param predicate defines the predicate function used to validate the condition
  54972. */
  54973. function PredicateCondition(actionManager,
  54974. /** defines the predicate function used to validate the condition */
  54975. predicate) {
  54976. var _this = _super.call(this, actionManager) || this;
  54977. _this.predicate = predicate;
  54978. return _this;
  54979. }
  54980. /**
  54981. * @returns the validity of the predicate condition
  54982. */
  54983. PredicateCondition.prototype.isValid = function () {
  54984. return this.predicate();
  54985. };
  54986. return PredicateCondition;
  54987. }(Condition));
  54988. BABYLON.PredicateCondition = PredicateCondition;
  54989. /**
  54990. * Defines a state condition as an extension of Condition
  54991. */
  54992. var StateCondition = /** @class */ (function (_super) {
  54993. __extends(StateCondition, _super);
  54994. /**
  54995. * Creates a new StateCondition
  54996. * @param actionManager manager for the action the condition applies to
  54997. * @param target of the condition
  54998. * @param value to compare with target state
  54999. */
  55000. function StateCondition(actionManager, target,
  55001. /** Value to compare with target state */
  55002. value) {
  55003. var _this = _super.call(this, actionManager) || this;
  55004. _this.value = value;
  55005. _this._target = target;
  55006. return _this;
  55007. }
  55008. /**
  55009. * Gets a boolean indicating if the current condition is met
  55010. * @returns the validity of the state
  55011. */
  55012. StateCondition.prototype.isValid = function () {
  55013. return this._target.state === this.value;
  55014. };
  55015. /**
  55016. * Serialize the StateCondition into a JSON compatible object
  55017. * @returns serialization object
  55018. */
  55019. StateCondition.prototype.serialize = function () {
  55020. return this._serialize({
  55021. name: "StateCondition",
  55022. properties: [
  55023. BABYLON.Action._GetTargetProperty(this._target),
  55024. { name: "value", value: this.value }
  55025. ]
  55026. });
  55027. };
  55028. return StateCondition;
  55029. }(Condition));
  55030. BABYLON.StateCondition = StateCondition;
  55031. })(BABYLON || (BABYLON = {}));
  55032. //# sourceMappingURL=babylon.condition.js.map
  55033. var BABYLON;
  55034. (function (BABYLON) {
  55035. /**
  55036. * The action to be carried out following a trigger
  55037. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  55038. */
  55039. var Action = /** @class */ (function () {
  55040. /**
  55041. * Creates a new Action
  55042. * @param triggerOptions the trigger, with or without parameters, for the action
  55043. * @param condition an optional determinant of action
  55044. */
  55045. function Action(
  55046. /** the trigger, with or without parameters, for the action */
  55047. triggerOptions, condition) {
  55048. this.triggerOptions = triggerOptions;
  55049. /**
  55050. * An event triggered prior to action being executed.
  55051. */
  55052. this.onBeforeExecuteObservable = new BABYLON.Observable();
  55053. if (triggerOptions.parameter) {
  55054. this.trigger = triggerOptions.trigger;
  55055. this._triggerParameter = triggerOptions.parameter;
  55056. }
  55057. else if (triggerOptions.trigger) {
  55058. this.trigger = triggerOptions.trigger;
  55059. }
  55060. else {
  55061. this.trigger = triggerOptions;
  55062. }
  55063. this._nextActiveAction = this;
  55064. this._condition = condition;
  55065. }
  55066. /**
  55067. * Internal only
  55068. * @hidden
  55069. */
  55070. Action.prototype._prepare = function () {
  55071. };
  55072. /**
  55073. * Gets the trigger parameters
  55074. * @returns the trigger parameters
  55075. */
  55076. Action.prototype.getTriggerParameter = function () {
  55077. return this._triggerParameter;
  55078. };
  55079. /**
  55080. * Internal only - executes current action event
  55081. * @hidden
  55082. */
  55083. Action.prototype._executeCurrent = function (evt) {
  55084. if (this._nextActiveAction._condition) {
  55085. var condition = this._nextActiveAction._condition;
  55086. var currentRenderId = this._actionManager.getScene().getRenderId();
  55087. // We cache the current evaluation for the current frame
  55088. if (condition._evaluationId === currentRenderId) {
  55089. if (!condition._currentResult) {
  55090. return;
  55091. }
  55092. }
  55093. else {
  55094. condition._evaluationId = currentRenderId;
  55095. if (!condition.isValid()) {
  55096. condition._currentResult = false;
  55097. return;
  55098. }
  55099. condition._currentResult = true;
  55100. }
  55101. }
  55102. this.onBeforeExecuteObservable.notifyObservers(this);
  55103. this._nextActiveAction.execute(evt);
  55104. this.skipToNextActiveAction();
  55105. };
  55106. /**
  55107. * Execute placeholder for child classes
  55108. * @param evt optional action event
  55109. */
  55110. Action.prototype.execute = function (evt) {
  55111. };
  55112. /**
  55113. * Skips to next active action
  55114. */
  55115. Action.prototype.skipToNextActiveAction = function () {
  55116. if (this._nextActiveAction._child) {
  55117. if (!this._nextActiveAction._child._actionManager) {
  55118. this._nextActiveAction._child._actionManager = this._actionManager;
  55119. }
  55120. this._nextActiveAction = this._nextActiveAction._child;
  55121. }
  55122. else {
  55123. this._nextActiveAction = this;
  55124. }
  55125. };
  55126. /**
  55127. * Adds action to chain of actions, may be a DoNothingAction
  55128. * @param action defines the next action to execute
  55129. * @returns The action passed in
  55130. * @see https://www.babylonjs-playground.com/#1T30HR#0
  55131. */
  55132. Action.prototype.then = function (action) {
  55133. this._child = action;
  55134. action._actionManager = this._actionManager;
  55135. action._prepare();
  55136. return action;
  55137. };
  55138. /**
  55139. * Internal only
  55140. * @hidden
  55141. */
  55142. Action.prototype._getProperty = function (propertyPath) {
  55143. return this._actionManager._getProperty(propertyPath);
  55144. };
  55145. /**
  55146. * Internal only
  55147. * @hidden
  55148. */
  55149. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  55150. return this._actionManager._getEffectiveTarget(target, propertyPath);
  55151. };
  55152. /**
  55153. * Serialize placeholder for child classes
  55154. * @param parent of child
  55155. * @returns the serialized object
  55156. */
  55157. Action.prototype.serialize = function (parent) {
  55158. };
  55159. /**
  55160. * Internal only called by serialize
  55161. * @hidden
  55162. */
  55163. Action.prototype._serialize = function (serializedAction, parent) {
  55164. var serializationObject = {
  55165. type: 1,
  55166. children: [],
  55167. name: serializedAction.name,
  55168. properties: serializedAction.properties || []
  55169. };
  55170. // Serialize child
  55171. if (this._child) {
  55172. this._child.serialize(serializationObject);
  55173. }
  55174. // Check if "this" has a condition
  55175. if (this._condition) {
  55176. var serializedCondition = this._condition.serialize();
  55177. serializedCondition.children.push(serializationObject);
  55178. if (parent) {
  55179. parent.children.push(serializedCondition);
  55180. }
  55181. return serializedCondition;
  55182. }
  55183. if (parent) {
  55184. parent.children.push(serializationObject);
  55185. }
  55186. return serializationObject;
  55187. };
  55188. /**
  55189. * Internal only
  55190. * @hidden
  55191. */
  55192. Action._SerializeValueAsString = function (value) {
  55193. if (typeof value === "number") {
  55194. return value.toString();
  55195. }
  55196. if (typeof value === "boolean") {
  55197. return value ? "true" : "false";
  55198. }
  55199. if (value instanceof BABYLON.Vector2) {
  55200. return value.x + ", " + value.y;
  55201. }
  55202. if (value instanceof BABYLON.Vector3) {
  55203. return value.x + ", " + value.y + ", " + value.z;
  55204. }
  55205. if (value instanceof BABYLON.Color3) {
  55206. return value.r + ", " + value.g + ", " + value.b;
  55207. }
  55208. if (value instanceof BABYLON.Color4) {
  55209. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  55210. }
  55211. return value; // string
  55212. };
  55213. /**
  55214. * Internal only
  55215. * @hidden
  55216. */
  55217. Action._GetTargetProperty = function (target) {
  55218. return {
  55219. name: "target",
  55220. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  55221. : target instanceof BABYLON.Light ? "LightProperties"
  55222. : target instanceof BABYLON.Camera ? "CameraProperties"
  55223. : "SceneProperties",
  55224. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  55225. };
  55226. };
  55227. return Action;
  55228. }());
  55229. BABYLON.Action = Action;
  55230. })(BABYLON || (BABYLON = {}));
  55231. //# sourceMappingURL=babylon.action.js.map
  55232. var BABYLON;
  55233. (function (BABYLON) {
  55234. /**
  55235. * ActionEvent is the event being sent when an action is triggered.
  55236. */
  55237. var ActionEvent = /** @class */ (function () {
  55238. /**
  55239. * Creates a new ActionEvent
  55240. * @param source The mesh or sprite that triggered the action
  55241. * @param pointerX The X mouse cursor position at the time of the event
  55242. * @param pointerY The Y mouse cursor position at the time of the event
  55243. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  55244. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  55245. * @param additionalData additional data for the event
  55246. */
  55247. function ActionEvent(
  55248. /** The mesh or sprite that triggered the action */
  55249. source,
  55250. /** The X mouse cursor position at the time of the event */
  55251. pointerX,
  55252. /** The Y mouse cursor position at the time of the event */
  55253. pointerY,
  55254. /** The mesh that is currently pointed at (can be null) */
  55255. meshUnderPointer,
  55256. /** the original (browser) event that triggered the ActionEvent */
  55257. sourceEvent,
  55258. /** additional data for the event */
  55259. additionalData) {
  55260. this.source = source;
  55261. this.pointerX = pointerX;
  55262. this.pointerY = pointerY;
  55263. this.meshUnderPointer = meshUnderPointer;
  55264. this.sourceEvent = sourceEvent;
  55265. this.additionalData = additionalData;
  55266. }
  55267. /**
  55268. * Helper function to auto-create an ActionEvent from a source mesh.
  55269. * @param source The source mesh that triggered the event
  55270. * @param evt The original (browser) event
  55271. * @param additionalData additional data for the event
  55272. * @returns the new ActionEvent
  55273. */
  55274. ActionEvent.CreateNew = function (source, evt, additionalData) {
  55275. var scene = source.getScene();
  55276. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  55277. };
  55278. /**
  55279. * Helper function to auto-create an ActionEvent from a source sprite
  55280. * @param source The source sprite that triggered the event
  55281. * @param scene Scene associated with the sprite
  55282. * @param evt The original (browser) event
  55283. * @param additionalData additional data for the event
  55284. * @returns the new ActionEvent
  55285. */
  55286. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  55287. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  55288. };
  55289. /**
  55290. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  55291. * @param scene the scene where the event occurred
  55292. * @param evt The original (browser) event
  55293. * @returns the new ActionEvent
  55294. */
  55295. ActionEvent.CreateNewFromScene = function (scene, evt) {
  55296. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  55297. };
  55298. /**
  55299. * Helper function to auto-create an ActionEvent from a primitive
  55300. * @param prim defines the target primitive
  55301. * @param pointerPos defines the pointer position
  55302. * @param evt The original (browser) event
  55303. * @param additionalData additional data for the event
  55304. * @returns the new ActionEvent
  55305. */
  55306. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  55307. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  55308. };
  55309. return ActionEvent;
  55310. }());
  55311. BABYLON.ActionEvent = ActionEvent;
  55312. /**
  55313. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  55314. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  55315. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55316. */
  55317. var ActionManager = /** @class */ (function () {
  55318. /**
  55319. * Creates a new action manager
  55320. * @param scene defines the hosting scene
  55321. */
  55322. function ActionManager(scene) {
  55323. // Members
  55324. /** Gets the list of actions */
  55325. this.actions = new Array();
  55326. /** Gets the cursor to use when hovering items */
  55327. this.hoverCursor = '';
  55328. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55329. scene.actionManagers.push(this);
  55330. }
  55331. // Methods
  55332. /**
  55333. * Releases all associated resources
  55334. */
  55335. ActionManager.prototype.dispose = function () {
  55336. var index = this._scene.actionManagers.indexOf(this);
  55337. for (var i = 0; i < this.actions.length; i++) {
  55338. var action = this.actions[i];
  55339. ActionManager.Triggers[action.trigger]--;
  55340. if (ActionManager.Triggers[action.trigger] === 0) {
  55341. delete ActionManager.Triggers[action.trigger];
  55342. }
  55343. }
  55344. if (index > -1) {
  55345. this._scene.actionManagers.splice(index, 1);
  55346. }
  55347. };
  55348. /**
  55349. * Gets hosting scene
  55350. * @returns the hosting scene
  55351. */
  55352. ActionManager.prototype.getScene = function () {
  55353. return this._scene;
  55354. };
  55355. /**
  55356. * Does this action manager handles actions of any of the given triggers
  55357. * @param triggers defines the triggers to be tested
  55358. * @return a boolean indicating whether one (or more) of the triggers is handled
  55359. */
  55360. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  55361. for (var index = 0; index < this.actions.length; index++) {
  55362. var action = this.actions[index];
  55363. if (triggers.indexOf(action.trigger) > -1) {
  55364. return true;
  55365. }
  55366. }
  55367. return false;
  55368. };
  55369. /**
  55370. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  55371. * speed.
  55372. * @param triggerA defines the trigger to be tested
  55373. * @param triggerB defines the trigger to be tested
  55374. * @return a boolean indicating whether one (or more) of the triggers is handled
  55375. */
  55376. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  55377. for (var index = 0; index < this.actions.length; index++) {
  55378. var action = this.actions[index];
  55379. if (triggerA == action.trigger || triggerB == action.trigger) {
  55380. return true;
  55381. }
  55382. }
  55383. return false;
  55384. };
  55385. /**
  55386. * Does this action manager handles actions of a given trigger
  55387. * @param trigger defines the trigger to be tested
  55388. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  55389. * @return whether the trigger is handled
  55390. */
  55391. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  55392. for (var index = 0; index < this.actions.length; index++) {
  55393. var action = this.actions[index];
  55394. if (action.trigger === trigger) {
  55395. if (parameterPredicate) {
  55396. if (parameterPredicate(action.getTriggerParameter())) {
  55397. return true;
  55398. }
  55399. }
  55400. else {
  55401. return true;
  55402. }
  55403. }
  55404. }
  55405. return false;
  55406. };
  55407. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  55408. /**
  55409. * Does this action manager has pointer triggers
  55410. */
  55411. get: function () {
  55412. for (var index = 0; index < this.actions.length; index++) {
  55413. var action = this.actions[index];
  55414. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  55415. return true;
  55416. }
  55417. }
  55418. return false;
  55419. },
  55420. enumerable: true,
  55421. configurable: true
  55422. });
  55423. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  55424. /**
  55425. * Does this action manager has pick triggers
  55426. */
  55427. get: function () {
  55428. for (var index = 0; index < this.actions.length; index++) {
  55429. var action = this.actions[index];
  55430. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  55431. return true;
  55432. }
  55433. }
  55434. return false;
  55435. },
  55436. enumerable: true,
  55437. configurable: true
  55438. });
  55439. Object.defineProperty(ActionManager, "HasTriggers", {
  55440. /**
  55441. * Does exist one action manager with at least one trigger
  55442. **/
  55443. get: function () {
  55444. for (var t in ActionManager.Triggers) {
  55445. if (ActionManager.Triggers.hasOwnProperty(t)) {
  55446. return true;
  55447. }
  55448. }
  55449. return false;
  55450. },
  55451. enumerable: true,
  55452. configurable: true
  55453. });
  55454. Object.defineProperty(ActionManager, "HasPickTriggers", {
  55455. /**
  55456. * Does exist one action manager with at least one pick trigger
  55457. **/
  55458. get: function () {
  55459. for (var t in ActionManager.Triggers) {
  55460. if (ActionManager.Triggers.hasOwnProperty(t)) {
  55461. var t_int = parseInt(t);
  55462. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  55463. return true;
  55464. }
  55465. }
  55466. }
  55467. return false;
  55468. },
  55469. enumerable: true,
  55470. configurable: true
  55471. });
  55472. /**
  55473. * Does exist one action manager that handles actions of a given trigger
  55474. * @param trigger defines the trigger to be tested
  55475. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  55476. **/
  55477. ActionManager.HasSpecificTrigger = function (trigger) {
  55478. for (var t in ActionManager.Triggers) {
  55479. if (ActionManager.Triggers.hasOwnProperty(t)) {
  55480. var t_int = parseInt(t);
  55481. if (t_int === trigger) {
  55482. return true;
  55483. }
  55484. }
  55485. }
  55486. return false;
  55487. };
  55488. /**
  55489. * Registers an action to this action manager
  55490. * @param action defines the action to be registered
  55491. * @return the action amended (prepared) after registration
  55492. */
  55493. ActionManager.prototype.registerAction = function (action) {
  55494. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  55495. if (this.getScene().actionManager !== this) {
  55496. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  55497. return null;
  55498. }
  55499. }
  55500. this.actions.push(action);
  55501. if (ActionManager.Triggers[action.trigger]) {
  55502. ActionManager.Triggers[action.trigger]++;
  55503. }
  55504. else {
  55505. ActionManager.Triggers[action.trigger] = 1;
  55506. }
  55507. action._actionManager = this;
  55508. action._prepare();
  55509. return action;
  55510. };
  55511. /**
  55512. * Unregisters an action to this action manager
  55513. * @param action defines the action to be unregistered
  55514. * @return a boolean indicating whether the action has been unregistered
  55515. */
  55516. ActionManager.prototype.unregisterAction = function (action) {
  55517. var index = this.actions.indexOf(action);
  55518. if (index !== -1) {
  55519. this.actions.splice(index, 1);
  55520. ActionManager.Triggers[action.trigger] -= 1;
  55521. if (ActionManager.Triggers[action.trigger] === 0) {
  55522. delete ActionManager.Triggers[action.trigger];
  55523. }
  55524. delete action._actionManager;
  55525. return true;
  55526. }
  55527. return false;
  55528. };
  55529. /**
  55530. * Process a specific trigger
  55531. * @param trigger defines the trigger to process
  55532. * @param evt defines the event details to be processed
  55533. */
  55534. ActionManager.prototype.processTrigger = function (trigger, evt) {
  55535. for (var index = 0; index < this.actions.length; index++) {
  55536. var action = this.actions[index];
  55537. if (action.trigger === trigger) {
  55538. if (evt) {
  55539. if (trigger === ActionManager.OnKeyUpTrigger
  55540. || trigger === ActionManager.OnKeyDownTrigger) {
  55541. var parameter = action.getTriggerParameter();
  55542. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  55543. if (!parameter.toLowerCase) {
  55544. continue;
  55545. }
  55546. var lowerCase = parameter.toLowerCase();
  55547. if (lowerCase !== evt.sourceEvent.key) {
  55548. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  55549. var actualkey = String.fromCharCode(unicode).toLowerCase();
  55550. if (actualkey !== lowerCase) {
  55551. continue;
  55552. }
  55553. }
  55554. }
  55555. }
  55556. }
  55557. action._executeCurrent(evt);
  55558. }
  55559. }
  55560. };
  55561. /** @hidden */
  55562. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  55563. var properties = propertyPath.split(".");
  55564. for (var index = 0; index < properties.length - 1; index++) {
  55565. target = target[properties[index]];
  55566. }
  55567. return target;
  55568. };
  55569. /** @hidden */
  55570. ActionManager.prototype._getProperty = function (propertyPath) {
  55571. var properties = propertyPath.split(".");
  55572. return properties[properties.length - 1];
  55573. };
  55574. /**
  55575. * Serialize this manager to a JSON object
  55576. * @param name defines the property name to store this manager
  55577. * @returns a JSON representation of this manager
  55578. */
  55579. ActionManager.prototype.serialize = function (name) {
  55580. var root = {
  55581. children: new Array(),
  55582. name: name,
  55583. type: 3,
  55584. properties: new Array() // Empty for root but required
  55585. };
  55586. for (var i = 0; i < this.actions.length; i++) {
  55587. var triggerObject = {
  55588. type: 0,
  55589. children: new Array(),
  55590. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  55591. properties: new Array()
  55592. };
  55593. var triggerOptions = this.actions[i].triggerOptions;
  55594. if (triggerOptions && typeof triggerOptions !== "number") {
  55595. if (triggerOptions.parameter instanceof BABYLON.Node) {
  55596. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  55597. }
  55598. else {
  55599. var parameter = {};
  55600. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  55601. if (triggerOptions.parameter && triggerOptions.parameter.mesh) {
  55602. parameter._meshId = triggerOptions.parameter.mesh.id;
  55603. }
  55604. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  55605. }
  55606. }
  55607. // Serialize child action, recursively
  55608. this.actions[i].serialize(triggerObject);
  55609. // Add serialized trigger
  55610. root.children.push(triggerObject);
  55611. }
  55612. return root;
  55613. };
  55614. /**
  55615. * Creates a new ActionManager from a JSON data
  55616. * @param parsedActions defines the JSON data to read from
  55617. * @param object defines the hosting mesh
  55618. * @param scene defines the hosting scene
  55619. */
  55620. ActionManager.Parse = function (parsedActions, object, scene) {
  55621. var actionManager = new ActionManager(scene);
  55622. if (object === null) {
  55623. scene.actionManager = actionManager;
  55624. }
  55625. else {
  55626. object.actionManager = actionManager;
  55627. }
  55628. // instanciate a new object
  55629. var instanciate = function (name, params) {
  55630. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  55631. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  55632. newInstance.constructor.apply(newInstance, params);
  55633. return newInstance;
  55634. };
  55635. var parseParameter = function (name, value, target, propertyPath) {
  55636. if (propertyPath === null) {
  55637. // String, boolean or float
  55638. var floatValue = parseFloat(value);
  55639. if (value === "true" || value === "false") {
  55640. return value === "true";
  55641. }
  55642. else {
  55643. return isNaN(floatValue) ? value : floatValue;
  55644. }
  55645. }
  55646. var effectiveTarget = propertyPath.split(".");
  55647. var values = value.split(",");
  55648. // Get effective Target
  55649. for (var i = 0; i < effectiveTarget.length; i++) {
  55650. target = target[effectiveTarget[i]];
  55651. }
  55652. // Return appropriate value with its type
  55653. if (typeof (target) === "boolean") {
  55654. return values[0] === "true";
  55655. }
  55656. if (typeof (target) === "string") {
  55657. return values[0];
  55658. }
  55659. // Parameters with multiple values such as Vector3 etc.
  55660. var split = new Array();
  55661. for (var i = 0; i < values.length; i++) {
  55662. split.push(parseFloat(values[i]));
  55663. }
  55664. if (target instanceof BABYLON.Vector3) {
  55665. return BABYLON.Vector3.FromArray(split);
  55666. }
  55667. if (target instanceof BABYLON.Vector4) {
  55668. return BABYLON.Vector4.FromArray(split);
  55669. }
  55670. if (target instanceof BABYLON.Color3) {
  55671. return BABYLON.Color3.FromArray(split);
  55672. }
  55673. if (target instanceof BABYLON.Color4) {
  55674. return BABYLON.Color4.FromArray(split);
  55675. }
  55676. return parseFloat(values[0]);
  55677. };
  55678. // traverse graph per trigger
  55679. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  55680. if (combineArray === void 0) { combineArray = null; }
  55681. if (parsedAction.detached) {
  55682. return;
  55683. }
  55684. var parameters = new Array();
  55685. var target = null;
  55686. var propertyPath = null;
  55687. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  55688. // Parameters
  55689. if (parsedAction.type === 2) {
  55690. parameters.push(actionManager);
  55691. }
  55692. else {
  55693. parameters.push(trigger);
  55694. }
  55695. if (combine) {
  55696. var actions = new Array();
  55697. for (var j = 0; j < parsedAction.combine.length; j++) {
  55698. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  55699. }
  55700. parameters.push(actions);
  55701. }
  55702. else {
  55703. for (var i = 0; i < parsedAction.properties.length; i++) {
  55704. var value = parsedAction.properties[i].value;
  55705. var name = parsedAction.properties[i].name;
  55706. var targetType = parsedAction.properties[i].targetType;
  55707. if (name === "target") {
  55708. if (targetType !== null && targetType === "SceneProperties") {
  55709. value = target = scene;
  55710. }
  55711. else {
  55712. value = target = scene.getNodeByName(value);
  55713. }
  55714. }
  55715. else if (name === "parent") {
  55716. value = scene.getNodeByName(value);
  55717. }
  55718. else if (name === "sound") {
  55719. // Can not externalize to component, so only checks for the presence off the API.
  55720. if (scene.getSoundByName) {
  55721. value = scene.getSoundByName(value);
  55722. }
  55723. }
  55724. else if (name !== "propertyPath") {
  55725. if (parsedAction.type === 2 && name === "operator") {
  55726. value = BABYLON.ValueCondition[value];
  55727. }
  55728. else {
  55729. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  55730. }
  55731. }
  55732. else {
  55733. propertyPath = value;
  55734. }
  55735. parameters.push(value);
  55736. }
  55737. }
  55738. if (combineArray === null) {
  55739. parameters.push(condition);
  55740. }
  55741. else {
  55742. parameters.push(null);
  55743. }
  55744. // If interpolate value action
  55745. if (parsedAction.name === "InterpolateValueAction") {
  55746. var param = parameters[parameters.length - 2];
  55747. parameters[parameters.length - 1] = param;
  55748. parameters[parameters.length - 2] = condition;
  55749. }
  55750. // Action or condition(s) and not CombineAction
  55751. var newAction = instanciate(parsedAction.name, parameters);
  55752. if (newAction instanceof BABYLON.Condition && condition !== null) {
  55753. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  55754. if (action) {
  55755. action.then(nothing);
  55756. }
  55757. else {
  55758. actionManager.registerAction(nothing);
  55759. }
  55760. action = nothing;
  55761. }
  55762. if (combineArray === null) {
  55763. if (newAction instanceof BABYLON.Condition) {
  55764. condition = newAction;
  55765. newAction = action;
  55766. }
  55767. else {
  55768. condition = null;
  55769. if (action) {
  55770. action.then(newAction);
  55771. }
  55772. else {
  55773. actionManager.registerAction(newAction);
  55774. }
  55775. }
  55776. }
  55777. else {
  55778. combineArray.push(newAction);
  55779. }
  55780. for (var i = 0; i < parsedAction.children.length; i++) {
  55781. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  55782. }
  55783. };
  55784. // triggers
  55785. for (var i = 0; i < parsedActions.children.length; i++) {
  55786. var triggerParams;
  55787. var trigger = parsedActions.children[i];
  55788. if (trigger.properties.length > 0) {
  55789. var param = trigger.properties[0].value;
  55790. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  55791. if (value._meshId) {
  55792. value.mesh = scene.getMeshByID(value._meshId);
  55793. }
  55794. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  55795. }
  55796. else {
  55797. triggerParams = ActionManager[trigger.name];
  55798. }
  55799. for (var j = 0; j < trigger.children.length; j++) {
  55800. if (!trigger.detached) {
  55801. traverse(trigger.children[j], triggerParams, null, null);
  55802. }
  55803. }
  55804. }
  55805. };
  55806. /**
  55807. * Get a trigger name by index
  55808. * @param trigger defines the trigger index
  55809. * @returns a trigger name
  55810. */
  55811. ActionManager.GetTriggerName = function (trigger) {
  55812. switch (trigger) {
  55813. case 0: return "NothingTrigger";
  55814. case 1: return "OnPickTrigger";
  55815. case 2: return "OnLeftPickTrigger";
  55816. case 3: return "OnRightPickTrigger";
  55817. case 4: return "OnCenterPickTrigger";
  55818. case 5: return "OnPickDownTrigger";
  55819. case 6: return "OnPickUpTrigger";
  55820. case 7: return "OnLongPressTrigger";
  55821. case 8: return "OnPointerOverTrigger";
  55822. case 9: return "OnPointerOutTrigger";
  55823. case 10: return "OnEveryFrameTrigger";
  55824. case 11: return "OnIntersectionEnterTrigger";
  55825. case 12: return "OnIntersectionExitTrigger";
  55826. case 13: return "OnKeyDownTrigger";
  55827. case 14: return "OnKeyUpTrigger";
  55828. case 15: return "OnPickOutTrigger";
  55829. default: return "";
  55830. }
  55831. };
  55832. /**
  55833. * Nothing
  55834. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55835. */
  55836. ActionManager.NothingTrigger = 0;
  55837. /**
  55838. * On pick
  55839. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55840. */
  55841. ActionManager.OnPickTrigger = 1;
  55842. /**
  55843. * On left pick
  55844. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55845. */
  55846. ActionManager.OnLeftPickTrigger = 2;
  55847. /**
  55848. * On right pick
  55849. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55850. */
  55851. ActionManager.OnRightPickTrigger = 3;
  55852. /**
  55853. * On center pick
  55854. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55855. */
  55856. ActionManager.OnCenterPickTrigger = 4;
  55857. /**
  55858. * On pick down
  55859. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55860. */
  55861. ActionManager.OnPickDownTrigger = 5;
  55862. /**
  55863. * On double pick
  55864. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55865. */
  55866. ActionManager.OnDoublePickTrigger = 6;
  55867. /**
  55868. * On pick up
  55869. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55870. */
  55871. ActionManager.OnPickUpTrigger = 7;
  55872. /**
  55873. * On pick out.
  55874. * This trigger will only be raised if you also declared a OnPickDown
  55875. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55876. */
  55877. ActionManager.OnPickOutTrigger = 16;
  55878. /**
  55879. * On long press
  55880. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55881. */
  55882. ActionManager.OnLongPressTrigger = 8;
  55883. /**
  55884. * On pointer over
  55885. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55886. */
  55887. ActionManager.OnPointerOverTrigger = 9;
  55888. /**
  55889. * On pointer out
  55890. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55891. */
  55892. ActionManager.OnPointerOutTrigger = 10;
  55893. /**
  55894. * On every frame
  55895. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55896. */
  55897. ActionManager.OnEveryFrameTrigger = 11;
  55898. /**
  55899. * On intersection enter
  55900. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55901. */
  55902. ActionManager.OnIntersectionEnterTrigger = 12;
  55903. /**
  55904. * On intersection exit
  55905. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55906. */
  55907. ActionManager.OnIntersectionExitTrigger = 13;
  55908. /**
  55909. * On key down
  55910. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55911. */
  55912. ActionManager.OnKeyDownTrigger = 14;
  55913. /**
  55914. * On key up
  55915. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55916. */
  55917. ActionManager.OnKeyUpTrigger = 15;
  55918. /** Gets the list of active triggers */
  55919. ActionManager.Triggers = {};
  55920. return ActionManager;
  55921. }());
  55922. BABYLON.ActionManager = ActionManager;
  55923. })(BABYLON || (BABYLON = {}));
  55924. //# sourceMappingURL=babylon.actionManager.js.map
  55925. var BABYLON;
  55926. (function (BABYLON) {
  55927. /**
  55928. * This defines an action responsible to change the value of a property
  55929. * by interpolating between its current value and the newly set one once triggered.
  55930. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55931. */
  55932. var InterpolateValueAction = /** @class */ (function (_super) {
  55933. __extends(InterpolateValueAction, _super);
  55934. /**
  55935. * Instantiate the action
  55936. * @param triggerOptions defines the trigger options
  55937. * @param target defines the object containing the value to interpolate
  55938. * @param propertyPath defines the path to the property in the target object
  55939. * @param value defines the target value at the end of the interpolation
  55940. * @param duration deines the time it will take for the property to interpolate to the value.
  55941. * @param condition defines the trigger related conditions
  55942. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  55943. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  55944. */
  55945. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  55946. if (duration === void 0) { duration = 1000; }
  55947. var _this = _super.call(this, triggerOptions, condition) || this;
  55948. /**
  55949. * Defines the time it will take for the property to interpolate to the value.
  55950. */
  55951. _this.duration = 1000;
  55952. /**
  55953. * Observable triggered once the interpolation animation has been done.
  55954. */
  55955. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  55956. _this.propertyPath = propertyPath;
  55957. _this.value = value;
  55958. _this.duration = duration;
  55959. _this.stopOtherAnimations = stopOtherAnimations;
  55960. _this.onInterpolationDone = onInterpolationDone;
  55961. _this._target = _this._effectiveTarget = target;
  55962. return _this;
  55963. }
  55964. /** @hidden */
  55965. InterpolateValueAction.prototype._prepare = function () {
  55966. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55967. this._property = this._getProperty(this.propertyPath);
  55968. };
  55969. /**
  55970. * Execute the action starts the value interpolation.
  55971. */
  55972. InterpolateValueAction.prototype.execute = function () {
  55973. var _this = this;
  55974. var scene = this._actionManager.getScene();
  55975. var keys = [
  55976. {
  55977. frame: 0,
  55978. value: this._effectiveTarget[this._property]
  55979. }, {
  55980. frame: 100,
  55981. value: this.value
  55982. }
  55983. ];
  55984. var dataType;
  55985. if (typeof this.value === "number") {
  55986. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  55987. }
  55988. else if (this.value instanceof BABYLON.Color3) {
  55989. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  55990. }
  55991. else if (this.value instanceof BABYLON.Vector3) {
  55992. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  55993. }
  55994. else if (this.value instanceof BABYLON.Matrix) {
  55995. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  55996. }
  55997. else if (this.value instanceof BABYLON.Quaternion) {
  55998. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  55999. }
  56000. else {
  56001. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  56002. return;
  56003. }
  56004. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  56005. animation.setKeys(keys);
  56006. if (this.stopOtherAnimations) {
  56007. scene.stopAnimation(this._effectiveTarget);
  56008. }
  56009. var wrapper = function () {
  56010. _this.onInterpolationDoneObservable.notifyObservers(_this);
  56011. if (_this.onInterpolationDone) {
  56012. _this.onInterpolationDone();
  56013. }
  56014. };
  56015. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  56016. };
  56017. /**
  56018. * Serializes the actions and its related information.
  56019. * @param parent defines the object to serialize in
  56020. * @returns the serialized object
  56021. */
  56022. InterpolateValueAction.prototype.serialize = function (parent) {
  56023. return _super.prototype._serialize.call(this, {
  56024. name: "InterpolateValueAction",
  56025. properties: [
  56026. BABYLON.Action._GetTargetProperty(this._target),
  56027. { name: "propertyPath", value: this.propertyPath },
  56028. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  56029. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  56030. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  56031. ]
  56032. }, parent);
  56033. };
  56034. return InterpolateValueAction;
  56035. }(BABYLON.Action));
  56036. BABYLON.InterpolateValueAction = InterpolateValueAction;
  56037. })(BABYLON || (BABYLON = {}));
  56038. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  56039. var BABYLON;
  56040. (function (BABYLON) {
  56041. /**
  56042. * This defines an action responsible to toggle a boolean once triggered.
  56043. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56044. */
  56045. var SwitchBooleanAction = /** @class */ (function (_super) {
  56046. __extends(SwitchBooleanAction, _super);
  56047. /**
  56048. * Instantiate the action
  56049. * @param triggerOptions defines the trigger options
  56050. * @param target defines the object containing the boolean
  56051. * @param propertyPath defines the path to the boolean property in the target object
  56052. * @param condition defines the trigger related conditions
  56053. */
  56054. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  56055. var _this = _super.call(this, triggerOptions, condition) || this;
  56056. _this.propertyPath = propertyPath;
  56057. _this._target = _this._effectiveTarget = target;
  56058. return _this;
  56059. }
  56060. /** @hidden */
  56061. SwitchBooleanAction.prototype._prepare = function () {
  56062. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  56063. this._property = this._getProperty(this.propertyPath);
  56064. };
  56065. /**
  56066. * Execute the action toggle the boolean value.
  56067. */
  56068. SwitchBooleanAction.prototype.execute = function () {
  56069. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  56070. };
  56071. /**
  56072. * Serializes the actions and its related information.
  56073. * @param parent defines the object to serialize in
  56074. * @returns the serialized object
  56075. */
  56076. SwitchBooleanAction.prototype.serialize = function (parent) {
  56077. return _super.prototype._serialize.call(this, {
  56078. name: "SwitchBooleanAction",
  56079. properties: [
  56080. BABYLON.Action._GetTargetProperty(this._target),
  56081. { name: "propertyPath", value: this.propertyPath }
  56082. ]
  56083. }, parent);
  56084. };
  56085. return SwitchBooleanAction;
  56086. }(BABYLON.Action));
  56087. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  56088. /**
  56089. * This defines an action responsible to set a the state field of the target
  56090. * to a desired value once triggered.
  56091. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56092. */
  56093. var SetStateAction = /** @class */ (function (_super) {
  56094. __extends(SetStateAction, _super);
  56095. /**
  56096. * Instantiate the action
  56097. * @param triggerOptions defines the trigger options
  56098. * @param target defines the object containing the state property
  56099. * @param value defines the value to store in the state field
  56100. * @param condition defines the trigger related conditions
  56101. */
  56102. function SetStateAction(triggerOptions, target, value, condition) {
  56103. var _this = _super.call(this, triggerOptions, condition) || this;
  56104. _this.value = value;
  56105. _this._target = target;
  56106. return _this;
  56107. }
  56108. /**
  56109. * Execute the action and store the value on the target state property.
  56110. */
  56111. SetStateAction.prototype.execute = function () {
  56112. this._target.state = this.value;
  56113. };
  56114. /**
  56115. * Serializes the actions and its related information.
  56116. * @param parent defines the object to serialize in
  56117. * @returns the serialized object
  56118. */
  56119. SetStateAction.prototype.serialize = function (parent) {
  56120. return _super.prototype._serialize.call(this, {
  56121. name: "SetStateAction",
  56122. properties: [
  56123. BABYLON.Action._GetTargetProperty(this._target),
  56124. { name: "value", value: this.value }
  56125. ]
  56126. }, parent);
  56127. };
  56128. return SetStateAction;
  56129. }(BABYLON.Action));
  56130. BABYLON.SetStateAction = SetStateAction;
  56131. /**
  56132. * This defines an action responsible to set a property of the target
  56133. * to a desired value once triggered.
  56134. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56135. */
  56136. var SetValueAction = /** @class */ (function (_super) {
  56137. __extends(SetValueAction, _super);
  56138. /**
  56139. * Instantiate the action
  56140. * @param triggerOptions defines the trigger options
  56141. * @param target defines the object containing the property
  56142. * @param propertyPath defines the path of the property to set in the target
  56143. * @param value defines the value to set in the property
  56144. * @param condition defines the trigger related conditions
  56145. */
  56146. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  56147. var _this = _super.call(this, triggerOptions, condition) || this;
  56148. _this.propertyPath = propertyPath;
  56149. _this.value = value;
  56150. _this._target = _this._effectiveTarget = target;
  56151. return _this;
  56152. }
  56153. /** @hidden */
  56154. SetValueAction.prototype._prepare = function () {
  56155. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  56156. this._property = this._getProperty(this.propertyPath);
  56157. };
  56158. /**
  56159. * Execute the action and set the targetted property to the desired value.
  56160. */
  56161. SetValueAction.prototype.execute = function () {
  56162. this._effectiveTarget[this._property] = this.value;
  56163. if (this._target.markAsDirty) {
  56164. this._target.markAsDirty(this._property);
  56165. }
  56166. };
  56167. /**
  56168. * Serializes the actions and its related information.
  56169. * @param parent defines the object to serialize in
  56170. * @returns the serialized object
  56171. */
  56172. SetValueAction.prototype.serialize = function (parent) {
  56173. return _super.prototype._serialize.call(this, {
  56174. name: "SetValueAction",
  56175. properties: [
  56176. BABYLON.Action._GetTargetProperty(this._target),
  56177. { name: "propertyPath", value: this.propertyPath },
  56178. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  56179. ]
  56180. }, parent);
  56181. };
  56182. return SetValueAction;
  56183. }(BABYLON.Action));
  56184. BABYLON.SetValueAction = SetValueAction;
  56185. /**
  56186. * This defines an action responsible to increment the target value
  56187. * to a desired value once triggered.
  56188. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56189. */
  56190. var IncrementValueAction = /** @class */ (function (_super) {
  56191. __extends(IncrementValueAction, _super);
  56192. /**
  56193. * Instantiate the action
  56194. * @param triggerOptions defines the trigger options
  56195. * @param target defines the object containing the property
  56196. * @param propertyPath defines the path of the property to increment in the target
  56197. * @param value defines the value value we should increment the property by
  56198. * @param condition defines the trigger related conditions
  56199. */
  56200. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  56201. var _this = _super.call(this, triggerOptions, condition) || this;
  56202. _this.propertyPath = propertyPath;
  56203. _this.value = value;
  56204. _this._target = _this._effectiveTarget = target;
  56205. return _this;
  56206. }
  56207. /** @hidden */
  56208. IncrementValueAction.prototype._prepare = function () {
  56209. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  56210. this._property = this._getProperty(this.propertyPath);
  56211. if (typeof this._effectiveTarget[this._property] !== "number") {
  56212. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  56213. }
  56214. };
  56215. /**
  56216. * Execute the action and increment the target of the value amount.
  56217. */
  56218. IncrementValueAction.prototype.execute = function () {
  56219. this._effectiveTarget[this._property] += this.value;
  56220. if (this._target.markAsDirty) {
  56221. this._target.markAsDirty(this._property);
  56222. }
  56223. };
  56224. /**
  56225. * Serializes the actions and its related information.
  56226. * @param parent defines the object to serialize in
  56227. * @returns the serialized object
  56228. */
  56229. IncrementValueAction.prototype.serialize = function (parent) {
  56230. return _super.prototype._serialize.call(this, {
  56231. name: "IncrementValueAction",
  56232. properties: [
  56233. BABYLON.Action._GetTargetProperty(this._target),
  56234. { name: "propertyPath", value: this.propertyPath },
  56235. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  56236. ]
  56237. }, parent);
  56238. };
  56239. return IncrementValueAction;
  56240. }(BABYLON.Action));
  56241. BABYLON.IncrementValueAction = IncrementValueAction;
  56242. /**
  56243. * This defines an action responsible to start an animation once triggered.
  56244. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56245. */
  56246. var PlayAnimationAction = /** @class */ (function (_super) {
  56247. __extends(PlayAnimationAction, _super);
  56248. /**
  56249. * Instantiate the action
  56250. * @param triggerOptions defines the trigger options
  56251. * @param target defines the target animation or animation name
  56252. * @param from defines from where the animation should start (animation frame)
  56253. * @param end defines where the animation should stop (animation frame)
  56254. * @param loop defines if the animation should loop or stop after the first play
  56255. * @param condition defines the trigger related conditions
  56256. */
  56257. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  56258. var _this = _super.call(this, triggerOptions, condition) || this;
  56259. _this.from = from;
  56260. _this.to = to;
  56261. _this.loop = loop;
  56262. _this._target = target;
  56263. return _this;
  56264. }
  56265. /** @hidden */
  56266. PlayAnimationAction.prototype._prepare = function () {
  56267. };
  56268. /**
  56269. * Execute the action and play the animation.
  56270. */
  56271. PlayAnimationAction.prototype.execute = function () {
  56272. var scene = this._actionManager.getScene();
  56273. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  56274. };
  56275. /**
  56276. * Serializes the actions and its related information.
  56277. * @param parent defines the object to serialize in
  56278. * @returns the serialized object
  56279. */
  56280. PlayAnimationAction.prototype.serialize = function (parent) {
  56281. return _super.prototype._serialize.call(this, {
  56282. name: "PlayAnimationAction",
  56283. properties: [
  56284. BABYLON.Action._GetTargetProperty(this._target),
  56285. { name: "from", value: String(this.from) },
  56286. { name: "to", value: String(this.to) },
  56287. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  56288. ]
  56289. }, parent);
  56290. };
  56291. return PlayAnimationAction;
  56292. }(BABYLON.Action));
  56293. BABYLON.PlayAnimationAction = PlayAnimationAction;
  56294. /**
  56295. * This defines an action responsible to stop an animation once triggered.
  56296. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56297. */
  56298. var StopAnimationAction = /** @class */ (function (_super) {
  56299. __extends(StopAnimationAction, _super);
  56300. /**
  56301. * Instantiate the action
  56302. * @param triggerOptions defines the trigger options
  56303. * @param target defines the target animation or animation name
  56304. * @param condition defines the trigger related conditions
  56305. */
  56306. function StopAnimationAction(triggerOptions, target, condition) {
  56307. var _this = _super.call(this, triggerOptions, condition) || this;
  56308. _this._target = target;
  56309. return _this;
  56310. }
  56311. /** @hidden */
  56312. StopAnimationAction.prototype._prepare = function () {
  56313. };
  56314. /**
  56315. * Execute the action and stop the animation.
  56316. */
  56317. StopAnimationAction.prototype.execute = function () {
  56318. var scene = this._actionManager.getScene();
  56319. scene.stopAnimation(this._target);
  56320. };
  56321. /**
  56322. * Serializes the actions and its related information.
  56323. * @param parent defines the object to serialize in
  56324. * @returns the serialized object
  56325. */
  56326. StopAnimationAction.prototype.serialize = function (parent) {
  56327. return _super.prototype._serialize.call(this, {
  56328. name: "StopAnimationAction",
  56329. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  56330. }, parent);
  56331. };
  56332. return StopAnimationAction;
  56333. }(BABYLON.Action));
  56334. BABYLON.StopAnimationAction = StopAnimationAction;
  56335. /**
  56336. * This defines an action responsible that does nothing once triggered.
  56337. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56338. */
  56339. var DoNothingAction = /** @class */ (function (_super) {
  56340. __extends(DoNothingAction, _super);
  56341. /**
  56342. * Instantiate the action
  56343. * @param triggerOptions defines the trigger options
  56344. * @param condition defines the trigger related conditions
  56345. */
  56346. function DoNothingAction(triggerOptions, condition) {
  56347. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  56348. return _super.call(this, triggerOptions, condition) || this;
  56349. }
  56350. /**
  56351. * Execute the action and do nothing.
  56352. */
  56353. DoNothingAction.prototype.execute = function () {
  56354. };
  56355. /**
  56356. * Serializes the actions and its related information.
  56357. * @param parent defines the object to serialize in
  56358. * @returns the serialized object
  56359. */
  56360. DoNothingAction.prototype.serialize = function (parent) {
  56361. return _super.prototype._serialize.call(this, {
  56362. name: "DoNothingAction",
  56363. properties: []
  56364. }, parent);
  56365. };
  56366. return DoNothingAction;
  56367. }(BABYLON.Action));
  56368. BABYLON.DoNothingAction = DoNothingAction;
  56369. /**
  56370. * This defines an action responsible to trigger several actions once triggered.
  56371. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56372. */
  56373. var CombineAction = /** @class */ (function (_super) {
  56374. __extends(CombineAction, _super);
  56375. /**
  56376. * Instantiate the action
  56377. * @param triggerOptions defines the trigger options
  56378. * @param children defines the list of aggregated animations to run
  56379. * @param condition defines the trigger related conditions
  56380. */
  56381. function CombineAction(triggerOptions, children, condition) {
  56382. var _this = _super.call(this, triggerOptions, condition) || this;
  56383. _this.children = children;
  56384. return _this;
  56385. }
  56386. /** @hidden */
  56387. CombineAction.prototype._prepare = function () {
  56388. for (var index = 0; index < this.children.length; index++) {
  56389. this.children[index]._actionManager = this._actionManager;
  56390. this.children[index]._prepare();
  56391. }
  56392. };
  56393. /**
  56394. * Execute the action and executes all the aggregated actions.
  56395. */
  56396. CombineAction.prototype.execute = function (evt) {
  56397. for (var index = 0; index < this.children.length; index++) {
  56398. this.children[index].execute(evt);
  56399. }
  56400. };
  56401. /**
  56402. * Serializes the actions and its related information.
  56403. * @param parent defines the object to serialize in
  56404. * @returns the serialized object
  56405. */
  56406. CombineAction.prototype.serialize = function (parent) {
  56407. var serializationObject = _super.prototype._serialize.call(this, {
  56408. name: "CombineAction",
  56409. properties: [],
  56410. combine: []
  56411. }, parent);
  56412. for (var i = 0; i < this.children.length; i++) {
  56413. serializationObject.combine.push(this.children[i].serialize(null));
  56414. }
  56415. return serializationObject;
  56416. };
  56417. return CombineAction;
  56418. }(BABYLON.Action));
  56419. BABYLON.CombineAction = CombineAction;
  56420. /**
  56421. * This defines an action responsible to run code (external event) once triggered.
  56422. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56423. */
  56424. var ExecuteCodeAction = /** @class */ (function (_super) {
  56425. __extends(ExecuteCodeAction, _super);
  56426. /**
  56427. * Instantiate the action
  56428. * @param triggerOptions defines the trigger options
  56429. * @param func defines the callback function to run
  56430. * @param condition defines the trigger related conditions
  56431. */
  56432. function ExecuteCodeAction(triggerOptions, func, condition) {
  56433. var _this = _super.call(this, triggerOptions, condition) || this;
  56434. _this.func = func;
  56435. return _this;
  56436. }
  56437. /**
  56438. * Execute the action and run the attached code.
  56439. */
  56440. ExecuteCodeAction.prototype.execute = function (evt) {
  56441. this.func(evt);
  56442. };
  56443. return ExecuteCodeAction;
  56444. }(BABYLON.Action));
  56445. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  56446. /**
  56447. * This defines an action responsible to set the parent property of the target once triggered.
  56448. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56449. */
  56450. var SetParentAction = /** @class */ (function (_super) {
  56451. __extends(SetParentAction, _super);
  56452. /**
  56453. * Instantiate the action
  56454. * @param triggerOptions defines the trigger options
  56455. * @param target defines the target containing the parent property
  56456. * @param parent defines from where the animation should start (animation frame)
  56457. * @param condition defines the trigger related conditions
  56458. */
  56459. function SetParentAction(triggerOptions, target, parent, condition) {
  56460. var _this = _super.call(this, triggerOptions, condition) || this;
  56461. _this._target = target;
  56462. _this._parent = parent;
  56463. return _this;
  56464. }
  56465. /** @hidden */
  56466. SetParentAction.prototype._prepare = function () {
  56467. };
  56468. /**
  56469. * Execute the action and set the parent property.
  56470. */
  56471. SetParentAction.prototype.execute = function () {
  56472. if (this._target.parent === this._parent) {
  56473. return;
  56474. }
  56475. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  56476. invertParentWorldMatrix.invert();
  56477. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  56478. this._target.parent = this._parent;
  56479. };
  56480. /**
  56481. * Serializes the actions and its related information.
  56482. * @param parent defines the object to serialize in
  56483. * @returns the serialized object
  56484. */
  56485. SetParentAction.prototype.serialize = function (parent) {
  56486. return _super.prototype._serialize.call(this, {
  56487. name: "SetParentAction",
  56488. properties: [
  56489. BABYLON.Action._GetTargetProperty(this._target),
  56490. BABYLON.Action._GetTargetProperty(this._parent),
  56491. ]
  56492. }, parent);
  56493. };
  56494. return SetParentAction;
  56495. }(BABYLON.Action));
  56496. BABYLON.SetParentAction = SetParentAction;
  56497. })(BABYLON || (BABYLON = {}));
  56498. //# sourceMappingURL=babylon.directActions.js.map
  56499. var BABYLON;
  56500. (function (BABYLON) {
  56501. /**
  56502. * Class used to manage multiple sprites on the same spritesheet
  56503. * @see http://doc.babylonjs.com/babylon101/sprites
  56504. */
  56505. var SpriteManager = /** @class */ (function () {
  56506. /**
  56507. * Creates a new sprite manager
  56508. * @param name defines the manager's name
  56509. * @param imgUrl defines the sprite sheet url
  56510. * @param capacity defines the maximum allowed number of sprites
  56511. * @param cellSize defines the size of a sprite cell
  56512. * @param scene defines the hosting scene
  56513. * @param epsilon defines the epsilon value to align texture (0.01 by default)
  56514. * @param samplingMode defines the smapling mode to use with spritesheet
  56515. */
  56516. function SpriteManager(
  56517. /** defines the manager's name */
  56518. name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  56519. if (epsilon === void 0) { epsilon = 0.01; }
  56520. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56521. this.name = name;
  56522. /** Gets the list of sprites */
  56523. this.sprites = new Array();
  56524. /** Gets or sets the rendering group id (0 by default) */
  56525. this.renderingGroupId = 0;
  56526. /** Gets or sets camera layer mask */
  56527. this.layerMask = 0x0FFFFFFF;
  56528. /** Gets or sets a boolean indicating if the manager must consider scene fog when rendering */
  56529. this.fogEnabled = true;
  56530. /** Gets or sets a boolean indicating if the sprites are pickable */
  56531. this.isPickable = false;
  56532. /**
  56533. * An event triggered when the manager is disposed.
  56534. */
  56535. this.onDisposeObservable = new BABYLON.Observable();
  56536. this._vertexBuffers = {};
  56537. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  56538. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  56539. }
  56540. this._capacity = capacity;
  56541. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  56542. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56543. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56544. if (cellSize.width && cellSize.height) {
  56545. this.cellWidth = cellSize.width;
  56546. this.cellHeight = cellSize.height;
  56547. }
  56548. else if (cellSize !== undefined) {
  56549. this.cellWidth = cellSize;
  56550. this.cellHeight = cellSize;
  56551. }
  56552. else {
  56553. return;
  56554. }
  56555. this._epsilon = epsilon;
  56556. this._scene = scene;
  56557. this._scene.spriteManagers.push(this);
  56558. var indices = [];
  56559. var index = 0;
  56560. for (var count = 0; count < capacity; count++) {
  56561. indices.push(index);
  56562. indices.push(index + 1);
  56563. indices.push(index + 2);
  56564. indices.push(index);
  56565. indices.push(index + 2);
  56566. indices.push(index + 3);
  56567. index += 4;
  56568. }
  56569. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  56570. // VBO
  56571. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  56572. this._vertexData = new Float32Array(capacity * 16 * 4);
  56573. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  56574. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  56575. var options = this._buffer.createVertexBuffer("options", 4, 4);
  56576. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  56577. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  56578. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56579. this._vertexBuffers["options"] = options;
  56580. this._vertexBuffers["cellInfo"] = cellInfo;
  56581. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56582. // Effects
  56583. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  56584. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  56585. }
  56586. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  56587. /**
  56588. * Callback called when the manager is disposed
  56589. */
  56590. set: function (callback) {
  56591. if (this._onDisposeObserver) {
  56592. this.onDisposeObservable.remove(this._onDisposeObserver);
  56593. }
  56594. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56595. },
  56596. enumerable: true,
  56597. configurable: true
  56598. });
  56599. Object.defineProperty(SpriteManager.prototype, "texture", {
  56600. /**
  56601. * Gets or sets the spritesheet texture
  56602. */
  56603. get: function () {
  56604. return this._spriteTexture;
  56605. },
  56606. set: function (value) {
  56607. this._spriteTexture = value;
  56608. },
  56609. enumerable: true,
  56610. configurable: true
  56611. });
  56612. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  56613. var arrayOffset = index * 16;
  56614. if (offsetX === 0) {
  56615. offsetX = this._epsilon;
  56616. }
  56617. else if (offsetX === 1) {
  56618. offsetX = 1 - this._epsilon;
  56619. }
  56620. if (offsetY === 0) {
  56621. offsetY = this._epsilon;
  56622. }
  56623. else if (offsetY === 1) {
  56624. offsetY = 1 - this._epsilon;
  56625. }
  56626. this._vertexData[arrayOffset] = sprite.position.x;
  56627. this._vertexData[arrayOffset + 1] = sprite.position.y;
  56628. this._vertexData[arrayOffset + 2] = sprite.position.z;
  56629. this._vertexData[arrayOffset + 3] = sprite.angle;
  56630. this._vertexData[arrayOffset + 4] = sprite.width;
  56631. this._vertexData[arrayOffset + 5] = sprite.height;
  56632. this._vertexData[arrayOffset + 6] = offsetX;
  56633. this._vertexData[arrayOffset + 7] = offsetY;
  56634. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  56635. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  56636. var offset = (sprite.cellIndex / rowSize) >> 0;
  56637. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  56638. this._vertexData[arrayOffset + 11] = offset;
  56639. // Color
  56640. this._vertexData[arrayOffset + 12] = sprite.color.r;
  56641. this._vertexData[arrayOffset + 13] = sprite.color.g;
  56642. this._vertexData[arrayOffset + 14] = sprite.color.b;
  56643. this._vertexData[arrayOffset + 15] = sprite.color.a;
  56644. };
  56645. /**
  56646. * Intersects the sprites with a ray
  56647. * @param ray defines the ray to intersect with
  56648. * @param camera defines the current active camera
  56649. * @param predicate defines a predicate used to select candidate sprites
  56650. * @param fastCheck defines if a fast check only must be done (the first potential sprite is will be used and not the closer)
  56651. * @returns null if no hit or a PickingInfo
  56652. */
  56653. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  56654. var count = Math.min(this._capacity, this.sprites.length);
  56655. var min = BABYLON.Vector3.Zero();
  56656. var max = BABYLON.Vector3.Zero();
  56657. var distance = Number.MAX_VALUE;
  56658. var currentSprite = null;
  56659. var cameraSpacePosition = BABYLON.Vector3.Zero();
  56660. var cameraView = camera.getViewMatrix();
  56661. for (var index = 0; index < count; index++) {
  56662. var sprite = this.sprites[index];
  56663. if (!sprite) {
  56664. continue;
  56665. }
  56666. if (predicate) {
  56667. if (!predicate(sprite)) {
  56668. continue;
  56669. }
  56670. }
  56671. else if (!sprite.isPickable) {
  56672. continue;
  56673. }
  56674. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  56675. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  56676. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  56677. if (ray.intersectsBoxMinMax(min, max)) {
  56678. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  56679. if (distance > currentDistance) {
  56680. distance = currentDistance;
  56681. currentSprite = sprite;
  56682. if (fastCheck) {
  56683. break;
  56684. }
  56685. }
  56686. }
  56687. }
  56688. if (currentSprite) {
  56689. var result = new BABYLON.PickingInfo();
  56690. result.hit = true;
  56691. result.pickedSprite = currentSprite;
  56692. result.distance = distance;
  56693. return result;
  56694. }
  56695. return null;
  56696. };
  56697. /**
  56698. * Render all child sprites
  56699. */
  56700. SpriteManager.prototype.render = function () {
  56701. // Check
  56702. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady()) {
  56703. return;
  56704. }
  56705. var engine = this._scene.getEngine();
  56706. var baseSize = this._spriteTexture.getBaseSize();
  56707. // Sprites
  56708. var deltaTime = engine.getDeltaTime();
  56709. var max = Math.min(this._capacity, this.sprites.length);
  56710. var rowSize = baseSize.width / this.cellWidth;
  56711. var offset = 0;
  56712. for (var index = 0; index < max; index++) {
  56713. var sprite = this.sprites[index];
  56714. if (!sprite || !sprite.isVisible) {
  56715. continue;
  56716. }
  56717. sprite._animate(deltaTime);
  56718. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  56719. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  56720. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  56721. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  56722. }
  56723. this._buffer.update(this._vertexData);
  56724. // Render
  56725. var effect = this._effectBase;
  56726. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  56727. effect = this._effectFog;
  56728. }
  56729. engine.enableEffect(effect);
  56730. var viewMatrix = this._scene.getViewMatrix();
  56731. effect.setTexture("diffuseSampler", this._spriteTexture);
  56732. effect.setMatrix("view", viewMatrix);
  56733. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56734. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  56735. // Fog
  56736. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  56737. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  56738. effect.setColor3("vFogColor", this._scene.fogColor);
  56739. }
  56740. // VBOs
  56741. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56742. // Draw order
  56743. engine.setDepthFunctionToLessOrEqual();
  56744. effect.setBool("alphaTest", true);
  56745. engine.setColorWrite(false);
  56746. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  56747. engine.setColorWrite(true);
  56748. effect.setBool("alphaTest", false);
  56749. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56750. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  56751. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56752. };
  56753. /**
  56754. * Release associated resources
  56755. */
  56756. SpriteManager.prototype.dispose = function () {
  56757. if (this._buffer) {
  56758. this._buffer.dispose();
  56759. this._buffer = null;
  56760. }
  56761. if (this._indexBuffer) {
  56762. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56763. this._indexBuffer = null;
  56764. }
  56765. if (this._spriteTexture) {
  56766. this._spriteTexture.dispose();
  56767. this._spriteTexture = null;
  56768. }
  56769. // Remove from scene
  56770. var index = this._scene.spriteManagers.indexOf(this);
  56771. this._scene.spriteManagers.splice(index, 1);
  56772. // Callback
  56773. this.onDisposeObservable.notifyObservers(this);
  56774. this.onDisposeObservable.clear();
  56775. };
  56776. return SpriteManager;
  56777. }());
  56778. BABYLON.SpriteManager = SpriteManager;
  56779. })(BABYLON || (BABYLON = {}));
  56780. //# sourceMappingURL=babylon.spriteManager.js.map
  56781. var BABYLON;
  56782. (function (BABYLON) {
  56783. /**
  56784. * Class used to represent a sprite
  56785. * @see http://doc.babylonjs.com/babylon101/sprites
  56786. */
  56787. var Sprite = /** @class */ (function () {
  56788. /**
  56789. * Creates a new Sprite
  56790. * @param name defines the name
  56791. * @param manager defines the manager
  56792. */
  56793. function Sprite(
  56794. /** defines the name */
  56795. name, manager) {
  56796. this.name = name;
  56797. /** Gets or sets the main color */
  56798. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56799. /** Gets or sets the width */
  56800. this.width = 1.0;
  56801. /** Gets or sets the height */
  56802. this.height = 1.0;
  56803. /** Gets or sets rotation angle */
  56804. this.angle = 0;
  56805. /** Gets or sets the cell index in the sprite sheet */
  56806. this.cellIndex = 0;
  56807. /** Gets or sets a boolean indicating if UV coordinates should be inverted in U axis */
  56808. this.invertU = 0;
  56809. /** Gets or sets a boolean indicating if UV coordinates should be inverted in B axis */
  56810. this.invertV = 0;
  56811. /** Gets the list of attached animations */
  56812. this.animations = new Array();
  56813. /** Gets or sets a boolean indicating if the sprite can be picked */
  56814. this.isPickable = false;
  56815. this._animationStarted = false;
  56816. this._loopAnimation = false;
  56817. this._fromIndex = 0;
  56818. this._toIndex = 0;
  56819. this._delay = 0;
  56820. this._direction = 1;
  56821. this._time = 0;
  56822. /**
  56823. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  56824. */
  56825. this.isVisible = true;
  56826. this._manager = manager;
  56827. this._manager.sprites.push(this);
  56828. this.position = BABYLON.Vector3.Zero();
  56829. }
  56830. Object.defineProperty(Sprite.prototype, "size", {
  56831. /**
  56832. * Gets or sets the sprite size
  56833. */
  56834. get: function () {
  56835. return this.width;
  56836. },
  56837. set: function (value) {
  56838. this.width = value;
  56839. this.height = value;
  56840. },
  56841. enumerable: true,
  56842. configurable: true
  56843. });
  56844. /**
  56845. * Starts an animation
  56846. * @param from defines the initial key
  56847. * @param to defines the end key
  56848. * @param loop defines if the animation must loop
  56849. * @param delay defines the start delay (in ms)
  56850. * @param onAnimationEnd defines a callback to call when animation ends
  56851. */
  56852. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  56853. this._fromIndex = from;
  56854. this._toIndex = to;
  56855. this._loopAnimation = loop;
  56856. this._delay = delay;
  56857. this._animationStarted = true;
  56858. this._direction = from < to ? 1 : -1;
  56859. this.cellIndex = from;
  56860. this._time = 0;
  56861. this._onAnimationEnd = onAnimationEnd;
  56862. };
  56863. /** Stops current animation (if any) */
  56864. Sprite.prototype.stopAnimation = function () {
  56865. this._animationStarted = false;
  56866. };
  56867. /** @hidden */
  56868. Sprite.prototype._animate = function (deltaTime) {
  56869. if (!this._animationStarted) {
  56870. return;
  56871. }
  56872. this._time += deltaTime;
  56873. if (this._time > this._delay) {
  56874. this._time = this._time % this._delay;
  56875. this.cellIndex += this._direction;
  56876. if (this.cellIndex > this._toIndex) {
  56877. if (this._loopAnimation) {
  56878. this.cellIndex = this._fromIndex;
  56879. }
  56880. else {
  56881. this.cellIndex = this._toIndex;
  56882. this._animationStarted = false;
  56883. if (this._onAnimationEnd) {
  56884. this._onAnimationEnd();
  56885. }
  56886. if (this.disposeWhenFinishedAnimating) {
  56887. this.dispose();
  56888. }
  56889. }
  56890. }
  56891. }
  56892. };
  56893. /** Release associated resources */
  56894. Sprite.prototype.dispose = function () {
  56895. for (var i = 0; i < this._manager.sprites.length; i++) {
  56896. if (this._manager.sprites[i] == this) {
  56897. this._manager.sprites.splice(i, 1);
  56898. }
  56899. }
  56900. };
  56901. return Sprite;
  56902. }());
  56903. BABYLON.Sprite = Sprite;
  56904. })(BABYLON || (BABYLON = {}));
  56905. //# sourceMappingURL=babylon.sprite.js.map
  56906. var BABYLON;
  56907. (function (BABYLON) {
  56908. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  56909. if (!BABYLON.PickingInfo) {
  56910. return null;
  56911. }
  56912. var pickingInfo = null;
  56913. if (!camera) {
  56914. if (!this.activeCamera) {
  56915. return null;
  56916. }
  56917. camera = this.activeCamera;
  56918. }
  56919. if (this.spriteManagers.length > 0) {
  56920. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  56921. var spriteManager = this.spriteManagers[spriteIndex];
  56922. if (!spriteManager.isPickable) {
  56923. continue;
  56924. }
  56925. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  56926. if (!result || !result.hit) {
  56927. continue;
  56928. }
  56929. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
  56930. continue;
  56931. }
  56932. pickingInfo = result;
  56933. if (fastCheck) {
  56934. break;
  56935. }
  56936. }
  56937. }
  56938. return pickingInfo || new BABYLON.PickingInfo();
  56939. };
  56940. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  56941. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  56942. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  56943. };
  56944. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  56945. if (!this._tempSpritePickingRay) {
  56946. return null;
  56947. }
  56948. if (!camera) {
  56949. if (!this.activeCamera) {
  56950. return null;
  56951. }
  56952. camera = this.activeCamera;
  56953. }
  56954. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  56955. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  56956. };
  56957. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  56958. if (this._pointerOverSprite === sprite) {
  56959. return;
  56960. }
  56961. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  56962. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  56963. }
  56964. this._pointerOverSprite = sprite;
  56965. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  56966. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  56967. }
  56968. };
  56969. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  56970. return this._pointerOverSprite;
  56971. };
  56972. /**
  56973. * Defines the sprite scene component responsible to manage sprites
  56974. * in a given scene.
  56975. */
  56976. var SpriteSceneComponent = /** @class */ (function () {
  56977. /**
  56978. * Creates a new instance of the component for the given scene
  56979. * @param scene Defines the scene to register the component in
  56980. */
  56981. function SpriteSceneComponent(scene) {
  56982. /**
  56983. * The component name helpfull to identify the component in the list of scene components.
  56984. */
  56985. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  56986. this.scene = scene;
  56987. this.scene.spriteManagers = new Array();
  56988. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  56989. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  56990. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  56991. this._spritePredicate = function (sprite) {
  56992. if (!sprite.actionManager) {
  56993. return false;
  56994. }
  56995. return sprite.isPickable && sprite.actionManager.hasPointerTriggers;
  56996. };
  56997. }
  56998. /**
  56999. * Registers the component in a given scene
  57000. */
  57001. SpriteSceneComponent.prototype.register = function () {
  57002. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  57003. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  57004. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  57005. };
  57006. /**
  57007. * Rebuilds the elements related to this component in case of
  57008. * context lost for instance.
  57009. */
  57010. SpriteSceneComponent.prototype.rebuild = function () {
  57011. /** Nothing to do for sprites */
  57012. };
  57013. /**
  57014. * Disposes the component and the associated ressources.
  57015. */
  57016. SpriteSceneComponent.prototype.dispose = function () {
  57017. this.scene.onBeforeSpritesRenderingObservable.clear();
  57018. this.scene.onAfterSpritesRenderingObservable.clear();
  57019. var spriteManagers = this.scene.spriteManagers;
  57020. while (spriteManagers.length) {
  57021. spriteManagers[0].dispose();
  57022. }
  57023. };
  57024. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  57025. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  57026. if (result) {
  57027. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  57028. }
  57029. return result;
  57030. };
  57031. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  57032. var scene = this.scene;
  57033. if (isMeshPicked) {
  57034. scene.setPointerOverSprite(null);
  57035. }
  57036. else {
  57037. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  57038. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  57039. scene.setPointerOverSprite(pickResult.pickedSprite);
  57040. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  57041. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  57042. }
  57043. else {
  57044. canvas.style.cursor = scene.hoverCursor;
  57045. }
  57046. }
  57047. else {
  57048. scene.setPointerOverSprite(null);
  57049. }
  57050. }
  57051. return pickResult;
  57052. };
  57053. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  57054. var scene = this.scene;
  57055. scene._pickedDownSprite = null;
  57056. if (scene.spriteManagers.length > 0) {
  57057. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  57058. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  57059. if (pickResult.pickedSprite.actionManager) {
  57060. scene._pickedDownSprite = pickResult.pickedSprite;
  57061. switch (evt.button) {
  57062. case 0:
  57063. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  57064. break;
  57065. case 1:
  57066. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  57067. break;
  57068. case 2:
  57069. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  57070. break;
  57071. }
  57072. if (pickResult.pickedSprite.actionManager) {
  57073. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  57074. }
  57075. }
  57076. }
  57077. }
  57078. return pickResult;
  57079. };
  57080. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  57081. var scene = this.scene;
  57082. if (scene.spriteManagers.length > 0) {
  57083. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  57084. if (spritePickResult) {
  57085. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  57086. if (spritePickResult.pickedSprite.actionManager) {
  57087. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  57088. if (spritePickResult.pickedSprite.actionManager) {
  57089. if (!this.scene._isPointerSwiping()) {
  57090. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  57091. }
  57092. }
  57093. }
  57094. }
  57095. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  57096. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  57097. }
  57098. }
  57099. }
  57100. return pickResult;
  57101. };
  57102. return SpriteSceneComponent;
  57103. }());
  57104. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  57105. })(BABYLON || (BABYLON = {}));
  57106. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  57107. var BABYLON;
  57108. (function (BABYLON) {
  57109. /**
  57110. * @hidden
  57111. */
  57112. var IntersectionInfo = /** @class */ (function () {
  57113. function IntersectionInfo(bu, bv, distance) {
  57114. this.bu = bu;
  57115. this.bv = bv;
  57116. this.distance = distance;
  57117. this.faceId = 0;
  57118. this.subMeshId = 0;
  57119. }
  57120. return IntersectionInfo;
  57121. }());
  57122. BABYLON.IntersectionInfo = IntersectionInfo;
  57123. /**
  57124. * Information about the result of picking within a scene
  57125. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  57126. */
  57127. var PickingInfo = /** @class */ (function () {
  57128. function PickingInfo() {
  57129. /**
  57130. * If the pick collided with an object
  57131. */
  57132. this.hit = false;
  57133. /**
  57134. * Distance away where the pick collided
  57135. */
  57136. this.distance = 0;
  57137. /**
  57138. * The location of pick collision
  57139. */
  57140. this.pickedPoint = null;
  57141. /**
  57142. * The mesh corresponding the the pick collision
  57143. */
  57144. this.pickedMesh = null;
  57145. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  57146. this.bu = 0;
  57147. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  57148. this.bv = 0;
  57149. /** The id of the face on the mesh that was picked */
  57150. this.faceId = -1;
  57151. /** Id of the the submesh that was picked */
  57152. this.subMeshId = 0;
  57153. /** If a sprite was picked, this will be the sprite the pick collided with */
  57154. this.pickedSprite = null;
  57155. /**
  57156. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  57157. */
  57158. this.originMesh = null;
  57159. /**
  57160. * The ray that was used to perform the picking.
  57161. */
  57162. this.ray = null;
  57163. }
  57164. /**
  57165. * Gets the normal correspodning to the face the pick collided with
  57166. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  57167. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  57168. * @returns The normal correspodning to the face the pick collided with
  57169. */
  57170. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  57171. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  57172. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  57173. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  57174. return null;
  57175. }
  57176. var indices = this.pickedMesh.getIndices();
  57177. if (!indices) {
  57178. return null;
  57179. }
  57180. var result;
  57181. if (useVerticesNormals) {
  57182. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57183. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  57184. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  57185. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  57186. normal0 = normal0.scale(this.bu);
  57187. normal1 = normal1.scale(this.bv);
  57188. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  57189. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  57190. }
  57191. else {
  57192. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57193. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  57194. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  57195. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  57196. var p1p2 = vertex1.subtract(vertex2);
  57197. var p3p2 = vertex3.subtract(vertex2);
  57198. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  57199. }
  57200. if (useWorldCoordinates) {
  57201. var wm = this.pickedMesh.getWorldMatrix();
  57202. if (this.pickedMesh.nonUniformScaling) {
  57203. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  57204. wm = BABYLON.Tmp.Matrix[0];
  57205. wm.setTranslationFromFloats(0, 0, 0);
  57206. wm.invert();
  57207. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  57208. wm = BABYLON.Tmp.Matrix[1];
  57209. }
  57210. result = BABYLON.Vector3.TransformNormal(result, wm);
  57211. }
  57212. result.normalize();
  57213. return result;
  57214. };
  57215. /**
  57216. * Gets the texture coordinates of where the pick occured
  57217. * @returns the vector containing the coordnates of the texture
  57218. */
  57219. PickingInfo.prototype.getTextureCoordinates = function () {
  57220. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57221. return null;
  57222. }
  57223. var indices = this.pickedMesh.getIndices();
  57224. if (!indices) {
  57225. return null;
  57226. }
  57227. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57228. if (!uvs) {
  57229. return null;
  57230. }
  57231. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  57232. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  57233. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  57234. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  57235. uv1 = uv1.scale(this.bu);
  57236. uv2 = uv2.scale(this.bv);
  57237. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  57238. };
  57239. return PickingInfo;
  57240. }());
  57241. BABYLON.PickingInfo = PickingInfo;
  57242. })(BABYLON || (BABYLON = {}));
  57243. //# sourceMappingURL=babylon.pickingInfo.js.map
  57244. var BABYLON;
  57245. (function (BABYLON) {
  57246. /**
  57247. * Class representing a ray with position and direction
  57248. */
  57249. var Ray = /** @class */ (function () {
  57250. /**
  57251. * Creates a new ray
  57252. * @param origin origin point
  57253. * @param direction direction
  57254. * @param length length of the ray
  57255. */
  57256. function Ray(
  57257. /** origin point */
  57258. origin,
  57259. /** direction */
  57260. direction,
  57261. /** length of the ray */
  57262. length) {
  57263. if (length === void 0) { length = Number.MAX_VALUE; }
  57264. this.origin = origin;
  57265. this.direction = direction;
  57266. this.length = length;
  57267. }
  57268. // Methods
  57269. /**
  57270. * Checks if the ray intersects a box
  57271. * @param minimum bound of the box
  57272. * @param maximum bound of the box
  57273. * @returns if the box was hit
  57274. */
  57275. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  57276. var d = 0.0;
  57277. var maxValue = Number.MAX_VALUE;
  57278. var inv;
  57279. var min;
  57280. var max;
  57281. var temp;
  57282. if (Math.abs(this.direction.x) < 0.0000001) {
  57283. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  57284. return false;
  57285. }
  57286. }
  57287. else {
  57288. inv = 1.0 / this.direction.x;
  57289. min = (minimum.x - this.origin.x) * inv;
  57290. max = (maximum.x - this.origin.x) * inv;
  57291. if (max === -Infinity) {
  57292. max = Infinity;
  57293. }
  57294. if (min > max) {
  57295. temp = min;
  57296. min = max;
  57297. max = temp;
  57298. }
  57299. d = Math.max(min, d);
  57300. maxValue = Math.min(max, maxValue);
  57301. if (d > maxValue) {
  57302. return false;
  57303. }
  57304. }
  57305. if (Math.abs(this.direction.y) < 0.0000001) {
  57306. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  57307. return false;
  57308. }
  57309. }
  57310. else {
  57311. inv = 1.0 / this.direction.y;
  57312. min = (minimum.y - this.origin.y) * inv;
  57313. max = (maximum.y - this.origin.y) * inv;
  57314. if (max === -Infinity) {
  57315. max = Infinity;
  57316. }
  57317. if (min > max) {
  57318. temp = min;
  57319. min = max;
  57320. max = temp;
  57321. }
  57322. d = Math.max(min, d);
  57323. maxValue = Math.min(max, maxValue);
  57324. if (d > maxValue) {
  57325. return false;
  57326. }
  57327. }
  57328. if (Math.abs(this.direction.z) < 0.0000001) {
  57329. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  57330. return false;
  57331. }
  57332. }
  57333. else {
  57334. inv = 1.0 / this.direction.z;
  57335. min = (minimum.z - this.origin.z) * inv;
  57336. max = (maximum.z - this.origin.z) * inv;
  57337. if (max === -Infinity) {
  57338. max = Infinity;
  57339. }
  57340. if (min > max) {
  57341. temp = min;
  57342. min = max;
  57343. max = temp;
  57344. }
  57345. d = Math.max(min, d);
  57346. maxValue = Math.min(max, maxValue);
  57347. if (d > maxValue) {
  57348. return false;
  57349. }
  57350. }
  57351. return true;
  57352. };
  57353. /**
  57354. * Checks if the ray intersects a box
  57355. * @param box the bounding box to check
  57356. * @returns if the box was hit
  57357. */
  57358. Ray.prototype.intersectsBox = function (box) {
  57359. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  57360. };
  57361. /**
  57362. * If the ray hits a sphere
  57363. * @param sphere the bounding sphere to check
  57364. * @returns true if it hits the sphere
  57365. */
  57366. Ray.prototype.intersectsSphere = function (sphere) {
  57367. var x = sphere.center.x - this.origin.x;
  57368. var y = sphere.center.y - this.origin.y;
  57369. var z = sphere.center.z - this.origin.z;
  57370. var pyth = (x * x) + (y * y) + (z * z);
  57371. var rr = sphere.radius * sphere.radius;
  57372. if (pyth <= rr) {
  57373. return true;
  57374. }
  57375. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  57376. if (dot < 0.0) {
  57377. return false;
  57378. }
  57379. var temp = pyth - (dot * dot);
  57380. return temp <= rr;
  57381. };
  57382. /**
  57383. * If the ray hits a triange
  57384. * @param vertex0 triangle vertex
  57385. * @param vertex1 triangle vertex
  57386. * @param vertex2 triangle vertex
  57387. * @returns intersection information if hit
  57388. */
  57389. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  57390. if (!this._edge1) {
  57391. this._edge1 = BABYLON.Vector3.Zero();
  57392. this._edge2 = BABYLON.Vector3.Zero();
  57393. this._pvec = BABYLON.Vector3.Zero();
  57394. this._tvec = BABYLON.Vector3.Zero();
  57395. this._qvec = BABYLON.Vector3.Zero();
  57396. }
  57397. vertex1.subtractToRef(vertex0, this._edge1);
  57398. vertex2.subtractToRef(vertex0, this._edge2);
  57399. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  57400. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  57401. if (det === 0) {
  57402. return null;
  57403. }
  57404. var invdet = 1 / det;
  57405. this.origin.subtractToRef(vertex0, this._tvec);
  57406. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  57407. if (bu < 0 || bu > 1.0) {
  57408. return null;
  57409. }
  57410. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  57411. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  57412. if (bv < 0 || bu + bv > 1.0) {
  57413. return null;
  57414. }
  57415. //check if the distance is longer than the predefined length.
  57416. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  57417. if (distance > this.length) {
  57418. return null;
  57419. }
  57420. return new BABYLON.IntersectionInfo(bu, bv, distance);
  57421. };
  57422. /**
  57423. * Checks if ray intersects a plane
  57424. * @param plane the plane to check
  57425. * @returns the distance away it was hit
  57426. */
  57427. Ray.prototype.intersectsPlane = function (plane) {
  57428. var distance;
  57429. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  57430. if (Math.abs(result1) < 9.99999997475243E-07) {
  57431. return null;
  57432. }
  57433. else {
  57434. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  57435. distance = (-plane.d - result2) / result1;
  57436. if (distance < 0.0) {
  57437. if (distance < -9.99999997475243E-07) {
  57438. return null;
  57439. }
  57440. else {
  57441. return 0;
  57442. }
  57443. }
  57444. return distance;
  57445. }
  57446. };
  57447. /**
  57448. * Checks if ray intersects a mesh
  57449. * @param mesh the mesh to check
  57450. * @param fastCheck if only the bounding box should checked
  57451. * @returns picking info of the intersecton
  57452. */
  57453. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  57454. var tm = BABYLON.Tmp.Matrix[0];
  57455. mesh.getWorldMatrix().invertToRef(tm);
  57456. if (this._tmpRay) {
  57457. Ray.TransformToRef(this, tm, this._tmpRay);
  57458. }
  57459. else {
  57460. this._tmpRay = Ray.Transform(this, tm);
  57461. }
  57462. return mesh.intersects(this._tmpRay, fastCheck);
  57463. };
  57464. /**
  57465. * Checks if ray intersects a mesh
  57466. * @param meshes the meshes to check
  57467. * @param fastCheck if only the bounding box should checked
  57468. * @param results array to store result in
  57469. * @returns Array of picking infos
  57470. */
  57471. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  57472. if (results) {
  57473. results.length = 0;
  57474. }
  57475. else {
  57476. results = [];
  57477. }
  57478. for (var i = 0; i < meshes.length; i++) {
  57479. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  57480. if (pickInfo.hit) {
  57481. results.push(pickInfo);
  57482. }
  57483. }
  57484. results.sort(this._comparePickingInfo);
  57485. return results;
  57486. };
  57487. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  57488. if (pickingInfoA.distance < pickingInfoB.distance) {
  57489. return -1;
  57490. }
  57491. else if (pickingInfoA.distance > pickingInfoB.distance) {
  57492. return 1;
  57493. }
  57494. else {
  57495. return 0;
  57496. }
  57497. };
  57498. /**
  57499. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  57500. * @param sega the first point of the segment to test the intersection against
  57501. * @param segb the second point of the segment to test the intersection against
  57502. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  57503. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  57504. */
  57505. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  57506. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  57507. var u = segb.subtract(sega);
  57508. var v = rsegb.subtract(this.origin);
  57509. var w = sega.subtract(this.origin);
  57510. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  57511. var b = BABYLON.Vector3.Dot(u, v);
  57512. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  57513. var d = BABYLON.Vector3.Dot(u, w);
  57514. var e = BABYLON.Vector3.Dot(v, w);
  57515. var D = a * c - b * b; // always >= 0
  57516. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  57517. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  57518. // compute the line parameters of the two closest points
  57519. if (D < Ray.smallnum) { // the lines are almost parallel
  57520. sN = 0.0; // force using point P0 on segment S1
  57521. sD = 1.0; // to prevent possible division by 0.0 later
  57522. tN = e;
  57523. tD = c;
  57524. }
  57525. else { // get the closest points on the infinite lines
  57526. sN = (b * e - c * d);
  57527. tN = (a * e - b * d);
  57528. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  57529. sN = 0.0;
  57530. tN = e;
  57531. tD = c;
  57532. }
  57533. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  57534. sN = sD;
  57535. tN = e + b;
  57536. tD = c;
  57537. }
  57538. }
  57539. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  57540. tN = 0.0;
  57541. // recompute sc for this edge
  57542. if (-d < 0.0) {
  57543. sN = 0.0;
  57544. }
  57545. else if (-d > a) {
  57546. sN = sD;
  57547. }
  57548. else {
  57549. sN = -d;
  57550. sD = a;
  57551. }
  57552. }
  57553. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  57554. tN = tD;
  57555. // recompute sc for this edge
  57556. if ((-d + b) < 0.0) {
  57557. sN = 0;
  57558. }
  57559. else if ((-d + b) > a) {
  57560. sN = sD;
  57561. }
  57562. else {
  57563. sN = (-d + b);
  57564. sD = a;
  57565. }
  57566. }
  57567. // finally do the division to get sc and tc
  57568. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  57569. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  57570. // get the difference of the two closest points
  57571. var qtc = v.multiplyByFloats(tc, tc, tc);
  57572. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  57573. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  57574. if (isIntersected) {
  57575. return qtc.length();
  57576. }
  57577. return -1;
  57578. };
  57579. /**
  57580. * Update the ray from viewport position
  57581. * @param x position
  57582. * @param y y position
  57583. * @param viewportWidth viewport width
  57584. * @param viewportHeight viewport height
  57585. * @param world world matrix
  57586. * @param view view matrix
  57587. * @param projection projection matrix
  57588. * @returns this ray updated
  57589. */
  57590. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  57591. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  57592. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  57593. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  57594. this.direction.normalize();
  57595. return this;
  57596. };
  57597. // Statics
  57598. /**
  57599. * Creates a ray with origin and direction of 0,0,0
  57600. * @returns the new ray
  57601. */
  57602. Ray.Zero = function () {
  57603. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  57604. };
  57605. /**
  57606. * Creates a new ray from screen space and viewport
  57607. * @param x position
  57608. * @param y y position
  57609. * @param viewportWidth viewport width
  57610. * @param viewportHeight viewport height
  57611. * @param world world matrix
  57612. * @param view view matrix
  57613. * @param projection projection matrix
  57614. * @returns new ray
  57615. */
  57616. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  57617. var result = Ray.Zero();
  57618. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  57619. };
  57620. /**
  57621. * 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
  57622. * transformed to the given world matrix.
  57623. * @param origin The origin point
  57624. * @param end The end point
  57625. * @param world a matrix to transform the ray to. Default is the identity matrix.
  57626. * @returns the new ray
  57627. */
  57628. Ray.CreateNewFromTo = function (origin, end, world) {
  57629. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  57630. var direction = end.subtract(origin);
  57631. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  57632. direction.normalize();
  57633. return Ray.Transform(new Ray(origin, direction, length), world);
  57634. };
  57635. /**
  57636. * Transforms a ray by a matrix
  57637. * @param ray ray to transform
  57638. * @param matrix matrix to apply
  57639. * @returns the resulting new ray
  57640. */
  57641. Ray.Transform = function (ray, matrix) {
  57642. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  57643. Ray.TransformToRef(ray, matrix, result);
  57644. return result;
  57645. };
  57646. /**
  57647. * Transforms a ray by a matrix
  57648. * @param ray ray to transform
  57649. * @param matrix matrix to apply
  57650. * @param result ray to store result in
  57651. */
  57652. Ray.TransformToRef = function (ray, matrix, result) {
  57653. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  57654. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  57655. result.length = ray.length;
  57656. var dir = result.direction;
  57657. var len = dir.length();
  57658. if (!(len === 0 || len === 1)) {
  57659. var num = 1.0 / len;
  57660. dir.x *= num;
  57661. dir.y *= num;
  57662. dir.z *= num;
  57663. result.length *= len;
  57664. }
  57665. };
  57666. Ray.smallnum = 0.00000001;
  57667. Ray.rayl = 10e8;
  57668. return Ray;
  57669. }());
  57670. BABYLON.Ray = Ray;
  57671. })(BABYLON || (BABYLON = {}));
  57672. //# sourceMappingURL=babylon.ray.js.map
  57673. var BABYLON;
  57674. (function (BABYLON) {
  57675. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  57676. if (boxMin.x > sphereCenter.x + sphereRadius) {
  57677. return false;
  57678. }
  57679. if (sphereCenter.x - sphereRadius > boxMax.x) {
  57680. return false;
  57681. }
  57682. if (boxMin.y > sphereCenter.y + sphereRadius) {
  57683. return false;
  57684. }
  57685. if (sphereCenter.y - sphereRadius > boxMax.y) {
  57686. return false;
  57687. }
  57688. if (boxMin.z > sphereCenter.z + sphereRadius) {
  57689. return false;
  57690. }
  57691. if (sphereCenter.z - sphereRadius > boxMax.z) {
  57692. return false;
  57693. }
  57694. return true;
  57695. };
  57696. var getLowestRoot = (function () {
  57697. var result = { root: 0, found: false };
  57698. return function (a, b, c, maxR) {
  57699. result.root = 0;
  57700. result.found = false;
  57701. var determinant = b * b - 4.0 * a * c;
  57702. if (determinant < 0) {
  57703. return result;
  57704. }
  57705. var sqrtD = Math.sqrt(determinant);
  57706. var r1 = (-b - sqrtD) / (2.0 * a);
  57707. var r2 = (-b + sqrtD) / (2.0 * a);
  57708. if (r1 > r2) {
  57709. var temp = r2;
  57710. r2 = r1;
  57711. r1 = temp;
  57712. }
  57713. if (r1 > 0 && r1 < maxR) {
  57714. result.root = r1;
  57715. result.found = true;
  57716. return result;
  57717. }
  57718. if (r2 > 0 && r2 < maxR) {
  57719. result.root = r2;
  57720. result.found = true;
  57721. return result;
  57722. }
  57723. return result;
  57724. };
  57725. })();
  57726. /** @hidden */
  57727. var Collider = /** @class */ (function () {
  57728. function Collider() {
  57729. this._collisionPoint = BABYLON.Vector3.Zero();
  57730. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  57731. this._tempVector = BABYLON.Vector3.Zero();
  57732. this._tempVector2 = BABYLON.Vector3.Zero();
  57733. this._tempVector3 = BABYLON.Vector3.Zero();
  57734. this._tempVector4 = BABYLON.Vector3.Zero();
  57735. this._edge = BABYLON.Vector3.Zero();
  57736. this._baseToVertex = BABYLON.Vector3.Zero();
  57737. this._destinationPoint = BABYLON.Vector3.Zero();
  57738. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  57739. this._displacementVector = BABYLON.Vector3.Zero();
  57740. /** @hidden */
  57741. this._radius = BABYLON.Vector3.One();
  57742. /** @hidden */
  57743. this._retry = 0;
  57744. /** @hidden */
  57745. this._basePointWorld = BABYLON.Vector3.Zero();
  57746. this._velocityWorld = BABYLON.Vector3.Zero();
  57747. this._normalizedVelocity = BABYLON.Vector3.Zero();
  57748. this._collisionMask = -1;
  57749. }
  57750. Object.defineProperty(Collider.prototype, "collisionMask", {
  57751. get: function () {
  57752. return this._collisionMask;
  57753. },
  57754. set: function (mask) {
  57755. this._collisionMask = !isNaN(mask) ? mask : -1;
  57756. },
  57757. enumerable: true,
  57758. configurable: true
  57759. });
  57760. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  57761. /**
  57762. * Gets the plane normal used to compute the sliding response (in local space)
  57763. */
  57764. get: function () {
  57765. return this._slidePlaneNormal;
  57766. },
  57767. enumerable: true,
  57768. configurable: true
  57769. });
  57770. // Methods
  57771. /** @hidden */
  57772. Collider.prototype._initialize = function (source, dir, e) {
  57773. this._velocity = dir;
  57774. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  57775. this._basePoint = source;
  57776. source.multiplyToRef(this._radius, this._basePointWorld);
  57777. dir.multiplyToRef(this._radius, this._velocityWorld);
  57778. this._velocityWorldLength = this._velocityWorld.length();
  57779. this._epsilon = e;
  57780. this.collisionFound = false;
  57781. };
  57782. /** @hidden */
  57783. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  57784. pa.subtractToRef(point, this._tempVector);
  57785. pb.subtractToRef(point, this._tempVector2);
  57786. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  57787. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  57788. if (d < 0) {
  57789. return false;
  57790. }
  57791. pc.subtractToRef(point, this._tempVector3);
  57792. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  57793. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  57794. if (d < 0) {
  57795. return false;
  57796. }
  57797. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  57798. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  57799. return d >= 0;
  57800. };
  57801. /** @hidden */
  57802. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  57803. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  57804. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  57805. if (distance > this._velocityWorldLength + max + sphereRadius) {
  57806. return false;
  57807. }
  57808. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max)) {
  57809. return false;
  57810. }
  57811. return true;
  57812. };
  57813. /** @hidden */
  57814. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  57815. var t0;
  57816. var embeddedInPlane = false;
  57817. //defensive programming, actually not needed.
  57818. if (!trianglePlaneArray) {
  57819. trianglePlaneArray = [];
  57820. }
  57821. if (!trianglePlaneArray[faceIndex]) {
  57822. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  57823. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  57824. }
  57825. var trianglePlane = trianglePlaneArray[faceIndex];
  57826. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0)) {
  57827. return;
  57828. }
  57829. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  57830. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  57831. if (normalDotVelocity == 0) {
  57832. if (Math.abs(signedDistToTrianglePlane) >= 1.0) {
  57833. return;
  57834. }
  57835. embeddedInPlane = true;
  57836. t0 = 0;
  57837. }
  57838. else {
  57839. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  57840. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  57841. if (t0 > t1) {
  57842. var temp = t1;
  57843. t1 = t0;
  57844. t0 = temp;
  57845. }
  57846. if (t0 > 1.0 || t1 < 0.0) {
  57847. return;
  57848. }
  57849. if (t0 < 0) {
  57850. t0 = 0;
  57851. }
  57852. if (t0 > 1.0) {
  57853. t0 = 1.0;
  57854. }
  57855. }
  57856. this._collisionPoint.copyFromFloats(0, 0, 0);
  57857. var found = false;
  57858. var t = 1.0;
  57859. if (!embeddedInPlane) {
  57860. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  57861. this._velocity.scaleToRef(t0, this._tempVector);
  57862. this._planeIntersectionPoint.addInPlace(this._tempVector);
  57863. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  57864. found = true;
  57865. t = t0;
  57866. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  57867. }
  57868. }
  57869. if (!found) {
  57870. var velocitySquaredLength = this._velocity.lengthSquared();
  57871. var a = velocitySquaredLength;
  57872. this._basePoint.subtractToRef(p1, this._tempVector);
  57873. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57874. var c = this._tempVector.lengthSquared() - 1.0;
  57875. var lowestRoot = getLowestRoot(a, b, c, t);
  57876. if (lowestRoot.found) {
  57877. t = lowestRoot.root;
  57878. found = true;
  57879. this._collisionPoint.copyFrom(p1);
  57880. }
  57881. this._basePoint.subtractToRef(p2, this._tempVector);
  57882. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57883. c = this._tempVector.lengthSquared() - 1.0;
  57884. lowestRoot = getLowestRoot(a, b, c, t);
  57885. if (lowestRoot.found) {
  57886. t = lowestRoot.root;
  57887. found = true;
  57888. this._collisionPoint.copyFrom(p2);
  57889. }
  57890. this._basePoint.subtractToRef(p3, this._tempVector);
  57891. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57892. c = this._tempVector.lengthSquared() - 1.0;
  57893. lowestRoot = getLowestRoot(a, b, c, t);
  57894. if (lowestRoot.found) {
  57895. t = lowestRoot.root;
  57896. found = true;
  57897. this._collisionPoint.copyFrom(p3);
  57898. }
  57899. p2.subtractToRef(p1, this._edge);
  57900. p1.subtractToRef(this._basePoint, this._baseToVertex);
  57901. var edgeSquaredLength = this._edge.lengthSquared();
  57902. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57903. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57904. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57905. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57906. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57907. lowestRoot = getLowestRoot(a, b, c, t);
  57908. if (lowestRoot.found) {
  57909. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57910. if (f >= 0.0 && f <= 1.0) {
  57911. t = lowestRoot.root;
  57912. found = true;
  57913. this._edge.scaleInPlace(f);
  57914. p1.addToRef(this._edge, this._collisionPoint);
  57915. }
  57916. }
  57917. p3.subtractToRef(p2, this._edge);
  57918. p2.subtractToRef(this._basePoint, this._baseToVertex);
  57919. edgeSquaredLength = this._edge.lengthSquared();
  57920. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57921. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57922. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57923. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57924. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57925. lowestRoot = getLowestRoot(a, b, c, t);
  57926. if (lowestRoot.found) {
  57927. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57928. if (f >= 0.0 && f <= 1.0) {
  57929. t = lowestRoot.root;
  57930. found = true;
  57931. this._edge.scaleInPlace(f);
  57932. p2.addToRef(this._edge, this._collisionPoint);
  57933. }
  57934. }
  57935. p1.subtractToRef(p3, this._edge);
  57936. p3.subtractToRef(this._basePoint, this._baseToVertex);
  57937. edgeSquaredLength = this._edge.lengthSquared();
  57938. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57939. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57940. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57941. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57942. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57943. lowestRoot = getLowestRoot(a, b, c, t);
  57944. if (lowestRoot.found) {
  57945. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57946. if (f >= 0.0 && f <= 1.0) {
  57947. t = lowestRoot.root;
  57948. found = true;
  57949. this._edge.scaleInPlace(f);
  57950. p3.addToRef(this._edge, this._collisionPoint);
  57951. }
  57952. }
  57953. }
  57954. if (found) {
  57955. var distToCollision = t * this._velocity.length();
  57956. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  57957. if (!this.intersectionPoint) {
  57958. this.intersectionPoint = this._collisionPoint.clone();
  57959. }
  57960. else {
  57961. this.intersectionPoint.copyFrom(this._collisionPoint);
  57962. }
  57963. this._nearestDistance = distToCollision;
  57964. this.collisionFound = true;
  57965. }
  57966. }
  57967. };
  57968. /** @hidden */
  57969. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  57970. for (var i = indexStart; i < indexEnd; i += 3) {
  57971. var p1 = pts[indices[i] - decal];
  57972. var p2 = pts[indices[i + 1] - decal];
  57973. var p3 = pts[indices[i + 2] - decal];
  57974. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  57975. }
  57976. };
  57977. /** @hidden */
  57978. Collider.prototype._getResponse = function (pos, vel) {
  57979. pos.addToRef(vel, this._destinationPoint);
  57980. vel.scaleInPlace((this._nearestDistance / vel.length()));
  57981. this._basePoint.addToRef(vel, pos);
  57982. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  57983. this._slidePlaneNormal.normalize();
  57984. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  57985. pos.addInPlace(this._displacementVector);
  57986. this.intersectionPoint.addInPlace(this._displacementVector);
  57987. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  57988. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  57989. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  57990. };
  57991. return Collider;
  57992. }());
  57993. BABYLON.Collider = Collider;
  57994. })(BABYLON || (BABYLON = {}));
  57995. //# sourceMappingURL=babylon.collider.js.map
  57996. var BABYLON;
  57997. (function (BABYLON) {
  57998. //WebWorker code will be inserted to this variable.
  57999. /** @hidden */
  58000. BABYLON.CollisionWorker = "";
  58001. /** Defines supported task for worker process */
  58002. var WorkerTaskType;
  58003. (function (WorkerTaskType) {
  58004. /** Initialization */
  58005. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  58006. /** Update of geometry */
  58007. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  58008. /** Evaluate collision */
  58009. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  58010. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  58011. /** Defines kind of replies returned by worker */
  58012. var WorkerReplyType;
  58013. (function (WorkerReplyType) {
  58014. /** Success */
  58015. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  58016. /** Unkown error */
  58017. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  58018. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  58019. /** @hidden */
  58020. var CollisionCoordinatorWorker = /** @class */ (function () {
  58021. function CollisionCoordinatorWorker() {
  58022. var _this = this;
  58023. this._scaledPosition = BABYLON.Vector3.Zero();
  58024. this._scaledVelocity = BABYLON.Vector3.Zero();
  58025. this.onMeshUpdated = function (transformNode) {
  58026. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  58027. };
  58028. this.onGeometryUpdated = function (geometry) {
  58029. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  58030. };
  58031. this._afterRender = function () {
  58032. if (!_this._init) {
  58033. return;
  58034. }
  58035. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  58036. return;
  58037. }
  58038. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  58039. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  58040. if (_this._runningUpdated > 4) {
  58041. return;
  58042. }
  58043. ++_this._runningUpdated;
  58044. var payload = {
  58045. updatedMeshes: _this._addUpdateMeshesList,
  58046. updatedGeometries: _this._addUpdateGeometriesList,
  58047. removedGeometries: _this._toRemoveGeometryArray,
  58048. removedMeshes: _this._toRemoveMeshesArray
  58049. };
  58050. var message = {
  58051. payload: payload,
  58052. taskType: WorkerTaskType.UPDATE
  58053. };
  58054. var serializable = [];
  58055. for (var id in payload.updatedGeometries) {
  58056. if (payload.updatedGeometries.hasOwnProperty(id)) {
  58057. //prepare transferables
  58058. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  58059. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  58060. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  58061. }
  58062. }
  58063. _this._worker.postMessage(message, serializable);
  58064. _this._addUpdateMeshesList = {};
  58065. _this._addUpdateGeometriesList = {};
  58066. _this._toRemoveGeometryArray = [];
  58067. _this._toRemoveMeshesArray = [];
  58068. };
  58069. this._onMessageFromWorker = function (e) {
  58070. var returnData = e.data;
  58071. if (returnData.error != WorkerReplyType.SUCCESS) {
  58072. //TODO what errors can be returned from the worker?
  58073. BABYLON.Tools.Warn("error returned from worker!");
  58074. return;
  58075. }
  58076. switch (returnData.taskType) {
  58077. case WorkerTaskType.INIT:
  58078. _this._init = true;
  58079. //Update the worked with ALL of the scene's current state
  58080. _this._scene.meshes.forEach(function (mesh) {
  58081. _this.onMeshAdded(mesh);
  58082. });
  58083. _this._scene.getGeometries().forEach(function (geometry) {
  58084. _this.onGeometryAdded(geometry);
  58085. });
  58086. break;
  58087. case WorkerTaskType.UPDATE:
  58088. _this._runningUpdated--;
  58089. break;
  58090. case WorkerTaskType.COLLIDE:
  58091. var returnPayload = returnData.payload;
  58092. if (!_this._collisionsCallbackArray[returnPayload.collisionId]) {
  58093. return;
  58094. }
  58095. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  58096. if (callback) {
  58097. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  58098. if (mesh) {
  58099. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  58100. }
  58101. }
  58102. //cleanup
  58103. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  58104. break;
  58105. }
  58106. };
  58107. this._collisionsCallbackArray = [];
  58108. this._init = false;
  58109. this._runningUpdated = 0;
  58110. this._addUpdateMeshesList = {};
  58111. this._addUpdateGeometriesList = {};
  58112. this._toRemoveGeometryArray = [];
  58113. this._toRemoveMeshesArray = [];
  58114. }
  58115. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  58116. if (!this._init) {
  58117. return;
  58118. }
  58119. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000]) {
  58120. return;
  58121. }
  58122. position.divideToRef(collider._radius, this._scaledPosition);
  58123. displacement.divideToRef(collider._radius, this._scaledVelocity);
  58124. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  58125. var payload = {
  58126. collider: {
  58127. position: this._scaledPosition.asArray(),
  58128. velocity: this._scaledVelocity.asArray(),
  58129. radius: collider._radius.asArray()
  58130. },
  58131. collisionId: collisionIndex,
  58132. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  58133. maximumRetry: maximumRetry
  58134. };
  58135. var message = {
  58136. payload: payload,
  58137. taskType: WorkerTaskType.COLLIDE
  58138. };
  58139. this._worker.postMessage(message);
  58140. };
  58141. CollisionCoordinatorWorker.prototype.init = function (scene) {
  58142. this._scene = scene;
  58143. this._scene.registerAfterRender(this._afterRender);
  58144. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  58145. this._worker = new Worker(workerUrl);
  58146. this._worker.onmessage = this._onMessageFromWorker;
  58147. var message = {
  58148. payload: {},
  58149. taskType: WorkerTaskType.INIT
  58150. };
  58151. this._worker.postMessage(message);
  58152. };
  58153. CollisionCoordinatorWorker.prototype.destroy = function () {
  58154. this._scene.unregisterAfterRender(this._afterRender);
  58155. this._worker.terminate();
  58156. };
  58157. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  58158. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  58159. this.onMeshUpdated(mesh);
  58160. };
  58161. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  58162. this._toRemoveMeshesArray.push(mesh.uniqueId);
  58163. };
  58164. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  58165. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  58166. geometry.onGeometryUpdated = this.onGeometryUpdated;
  58167. this.onGeometryUpdated(geometry);
  58168. };
  58169. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  58170. this._toRemoveGeometryArray.push(geometry.id);
  58171. };
  58172. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  58173. var submeshes = [];
  58174. if (mesh.subMeshes) {
  58175. submeshes = mesh.subMeshes.map(function (sm, idx) {
  58176. var boundingInfo = sm.getBoundingInfo();
  58177. return {
  58178. position: idx,
  58179. verticesStart: sm.verticesStart,
  58180. verticesCount: sm.verticesCount,
  58181. indexStart: sm.indexStart,
  58182. indexCount: sm.indexCount,
  58183. hasMaterial: !!sm.getMaterial(),
  58184. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  58185. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  58186. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  58187. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  58188. };
  58189. });
  58190. }
  58191. var geometryId = null;
  58192. if (mesh instanceof BABYLON.Mesh) {
  58193. var geometry = mesh.geometry;
  58194. geometryId = geometry ? geometry.id : null;
  58195. }
  58196. else if (mesh instanceof BABYLON.InstancedMesh) {
  58197. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  58198. geometryId = geometry ? geometry.id : null;
  58199. }
  58200. var boundingInfo = mesh.getBoundingInfo();
  58201. return {
  58202. uniqueId: mesh.uniqueId,
  58203. id: mesh.id,
  58204. name: mesh.name,
  58205. geometryId: geometryId,
  58206. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  58207. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  58208. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  58209. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  58210. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  58211. subMeshes: submeshes,
  58212. checkCollisions: mesh.checkCollisions
  58213. };
  58214. };
  58215. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  58216. return {
  58217. id: geometry.id,
  58218. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  58219. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  58220. indices: new Uint32Array(geometry.getIndices() || []),
  58221. };
  58222. };
  58223. return CollisionCoordinatorWorker;
  58224. }());
  58225. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  58226. /** @hidden */
  58227. var CollisionCoordinatorLegacy = /** @class */ (function () {
  58228. function CollisionCoordinatorLegacy() {
  58229. this._scaledPosition = BABYLON.Vector3.Zero();
  58230. this._scaledVelocity = BABYLON.Vector3.Zero();
  58231. this._finalPosition = BABYLON.Vector3.Zero();
  58232. }
  58233. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  58234. position.divideToRef(collider._radius, this._scaledPosition);
  58235. displacement.divideToRef(collider._radius, this._scaledVelocity);
  58236. collider.collidedMesh = null;
  58237. collider._retry = 0;
  58238. collider._initialVelocity = this._scaledVelocity;
  58239. collider._initialPosition = this._scaledPosition;
  58240. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  58241. this._finalPosition.multiplyInPlace(collider._radius);
  58242. //run the callback
  58243. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  58244. };
  58245. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  58246. this._scene = scene;
  58247. };
  58248. CollisionCoordinatorLegacy.prototype.destroy = function () {
  58249. //Legacy need no destruction method.
  58250. };
  58251. //No update in legacy mode
  58252. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  58253. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  58254. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  58255. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  58256. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  58257. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  58258. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  58259. if (excludedMesh === void 0) { excludedMesh = null; }
  58260. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  58261. if (collider._retry >= maximumRetry) {
  58262. finalPosition.copyFrom(position);
  58263. return;
  58264. }
  58265. // Check if this is a mesh else camera or -1
  58266. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  58267. collider._initialize(position, velocity, closeDistance);
  58268. // Check all meshes
  58269. for (var index = 0; index < this._scene.meshes.length; index++) {
  58270. var mesh = this._scene.meshes[index];
  58271. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  58272. mesh._checkCollision(collider);
  58273. }
  58274. }
  58275. if (!collider.collisionFound) {
  58276. position.addToRef(velocity, finalPosition);
  58277. return;
  58278. }
  58279. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  58280. collider._getResponse(position, velocity);
  58281. }
  58282. if (velocity.length() <= closeDistance) {
  58283. finalPosition.copyFrom(position);
  58284. return;
  58285. }
  58286. collider._retry++;
  58287. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  58288. };
  58289. return CollisionCoordinatorLegacy;
  58290. }());
  58291. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  58292. })(BABYLON || (BABYLON = {}));
  58293. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  58294. var BABYLON;
  58295. (function (BABYLON) {
  58296. /**
  58297. * A particle represents one of the element emitted by a particle system.
  58298. * This is mainly define by its coordinates, direction, velocity and age.
  58299. */
  58300. var Particle = /** @class */ (function () {
  58301. /**
  58302. * Creates a new instance Particle
  58303. * @param particleSystem the particle system the particle belongs to
  58304. */
  58305. function Particle(
  58306. /**
  58307. * The particle system the particle belongs to.
  58308. */
  58309. particleSystem) {
  58310. this.particleSystem = particleSystem;
  58311. /**
  58312. * The world position of the particle in the scene.
  58313. */
  58314. this.position = BABYLON.Vector3.Zero();
  58315. /**
  58316. * The world direction of the particle in the scene.
  58317. */
  58318. this.direction = BABYLON.Vector3.Zero();
  58319. /**
  58320. * The color of the particle.
  58321. */
  58322. this.color = new BABYLON.Color4(0, 0, 0, 0);
  58323. /**
  58324. * The color change of the particle per step.
  58325. */
  58326. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  58327. /**
  58328. * Defines how long will the life of the particle be.
  58329. */
  58330. this.lifeTime = 1.0;
  58331. /**
  58332. * The current age of the particle.
  58333. */
  58334. this.age = 0;
  58335. /**
  58336. * The current size of the particle.
  58337. */
  58338. this.size = 0;
  58339. /**
  58340. * The current scale of the particle.
  58341. */
  58342. this.scale = new BABYLON.Vector2(1, 1);
  58343. /**
  58344. * The current angle of the particle.
  58345. */
  58346. this.angle = 0;
  58347. /**
  58348. * Defines how fast is the angle changing.
  58349. */
  58350. this.angularSpeed = 0;
  58351. /**
  58352. * Defines the cell index used by the particle to be rendered from a sprite.
  58353. */
  58354. this.cellIndex = 0;
  58355. /** @hidden */
  58356. this._attachedSubEmitters = null;
  58357. /** @hidden */
  58358. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  58359. /** @hidden */
  58360. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  58361. /** @hidden */
  58362. this._currentSize1 = 0;
  58363. /** @hidden */
  58364. this._currentSize2 = 0;
  58365. /** @hidden */
  58366. this._currentAngularSpeed1 = 0;
  58367. /** @hidden */
  58368. this._currentAngularSpeed2 = 0;
  58369. /** @hidden */
  58370. this._currentVelocity1 = 0;
  58371. /** @hidden */
  58372. this._currentVelocity2 = 0;
  58373. /** @hidden */
  58374. this._currentLimitVelocity1 = 0;
  58375. /** @hidden */
  58376. this._currentLimitVelocity2 = 0;
  58377. /** @hidden */
  58378. this._currentDrag1 = 0;
  58379. /** @hidden */
  58380. this._currentDrag2 = 0;
  58381. this.id = Particle._Count++;
  58382. if (!this.particleSystem.isAnimationSheetEnabled) {
  58383. return;
  58384. }
  58385. this.updateCellInfoFromSystem();
  58386. }
  58387. Particle.prototype.updateCellInfoFromSystem = function () {
  58388. this.cellIndex = this.particleSystem.startSpriteCellID;
  58389. };
  58390. /**
  58391. * Defines how the sprite cell index is updated for the particle
  58392. */
  58393. Particle.prototype.updateCellIndex = function () {
  58394. var offsetAge = this.age;
  58395. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  58396. if (this.particleSystem.spriteRandomStartCell) {
  58397. if (this._randomCellOffset === undefined) {
  58398. this._randomCellOffset = Math.random() * this.lifeTime;
  58399. }
  58400. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  58401. changeSpeed = 1;
  58402. offsetAge = this._randomCellOffset;
  58403. }
  58404. else {
  58405. offsetAge += this._randomCellOffset;
  58406. }
  58407. }
  58408. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  58409. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  58410. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  58411. };
  58412. /** @hidden */
  58413. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  58414. if (subEmitter.particleSystem.emitter.position) {
  58415. var emitterMesh = subEmitter.particleSystem.emitter;
  58416. emitterMesh.position.copyFrom(this.position);
  58417. if (subEmitter.inheritDirection) {
  58418. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  58419. // Look at using Y as forward
  58420. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  58421. }
  58422. }
  58423. else {
  58424. var emitterPosition = subEmitter.particleSystem.emitter;
  58425. emitterPosition.copyFrom(this.position);
  58426. }
  58427. // Set inheritedVelocityOffset to be used when new particles are created
  58428. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  58429. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  58430. };
  58431. /** @hidden */
  58432. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  58433. var _this = this;
  58434. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  58435. this._attachedSubEmitters.forEach(function (subEmitter) {
  58436. _this._inheritParticleInfoToSubEmitter(subEmitter);
  58437. });
  58438. }
  58439. };
  58440. /** @hidden */
  58441. Particle.prototype._reset = function () {
  58442. this.age = 0;
  58443. this._currentColorGradient = null;
  58444. this._currentSizeGradient = null;
  58445. this._currentAngularSpeedGradient = null;
  58446. this._currentVelocityGradient = null;
  58447. this._currentLimitVelocityGradient = null;
  58448. this._currentDragGradient = null;
  58449. this.cellIndex = this.particleSystem.startSpriteCellID;
  58450. this._randomCellOffset = undefined;
  58451. };
  58452. /**
  58453. * Copy the properties of particle to another one.
  58454. * @param other the particle to copy the information to.
  58455. */
  58456. Particle.prototype.copyTo = function (other) {
  58457. other.position.copyFrom(this.position);
  58458. if (this._initialDirection) {
  58459. if (other._initialDirection) {
  58460. other._initialDirection.copyFrom(this._initialDirection);
  58461. }
  58462. else {
  58463. other._initialDirection = this._initialDirection.clone();
  58464. }
  58465. }
  58466. else {
  58467. other._initialDirection = null;
  58468. }
  58469. other.direction.copyFrom(this.direction);
  58470. other.color.copyFrom(this.color);
  58471. other.colorStep.copyFrom(this.colorStep);
  58472. other.lifeTime = this.lifeTime;
  58473. other.age = this.age;
  58474. other._randomCellOffset = this._randomCellOffset;
  58475. other.size = this.size;
  58476. other.scale.copyFrom(this.scale);
  58477. other.angle = this.angle;
  58478. other.angularSpeed = this.angularSpeed;
  58479. other.particleSystem = this.particleSystem;
  58480. other.cellIndex = this.cellIndex;
  58481. other.id = this.id;
  58482. other._attachedSubEmitters = this._attachedSubEmitters;
  58483. if (this._currentColorGradient) {
  58484. other._currentColorGradient = this._currentColorGradient;
  58485. other._currentColor1.copyFrom(this._currentColor1);
  58486. other._currentColor2.copyFrom(this._currentColor2);
  58487. }
  58488. if (this._currentSizeGradient) {
  58489. other._currentSizeGradient = this._currentSizeGradient;
  58490. other._currentSize1 = this._currentSize1;
  58491. other._currentSize2 = this._currentSize2;
  58492. }
  58493. if (this._currentAngularSpeedGradient) {
  58494. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  58495. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  58496. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  58497. }
  58498. if (this._currentVelocityGradient) {
  58499. other._currentVelocityGradient = this._currentVelocityGradient;
  58500. other._currentVelocity1 = this._currentVelocity1;
  58501. other._currentVelocity2 = this._currentVelocity2;
  58502. }
  58503. if (this._currentLimitVelocityGradient) {
  58504. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  58505. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  58506. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  58507. }
  58508. if (this._currentDragGradient) {
  58509. other._currentDragGradient = this._currentDragGradient;
  58510. other._currentDrag1 = this._currentDrag1;
  58511. other._currentDrag2 = this._currentDrag2;
  58512. }
  58513. if (this.particleSystem.isAnimationSheetEnabled) {
  58514. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  58515. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  58516. }
  58517. if (this.particleSystem.useRampGradients) {
  58518. other.remapData.copyFrom(this.remapData);
  58519. }
  58520. if (this._randomNoiseCoordinates1) {
  58521. if (other._randomNoiseCoordinates1) {
  58522. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  58523. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  58524. }
  58525. else {
  58526. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  58527. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  58528. }
  58529. }
  58530. };
  58531. Particle._Count = 0;
  58532. return Particle;
  58533. }());
  58534. BABYLON.Particle = Particle;
  58535. })(BABYLON || (BABYLON = {}));
  58536. //# sourceMappingURL=babylon.particle.js.map
  58537. var BABYLON;
  58538. (function (BABYLON) {
  58539. /**
  58540. * This represents the base class for particle system in Babylon.
  58541. * 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.
  58542. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  58543. * @example https://doc.babylonjs.com/babylon101/particles
  58544. */
  58545. var BaseParticleSystem = /** @class */ (function () {
  58546. /**
  58547. * Instantiates a particle system.
  58548. * 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.
  58549. * @param name The name of the particle system
  58550. */
  58551. function BaseParticleSystem(name) {
  58552. /**
  58553. * List of animations used by the particle system.
  58554. */
  58555. this.animations = [];
  58556. /**
  58557. * The rendering group used by the Particle system to chose when to render.
  58558. */
  58559. this.renderingGroupId = 0;
  58560. /**
  58561. * The emitter represents the Mesh or position we are attaching the particle system to.
  58562. */
  58563. this.emitter = null;
  58564. /**
  58565. * The maximum number of particles to emit per frame
  58566. */
  58567. this.emitRate = 10;
  58568. /**
  58569. * If you want to launch only a few particles at once, that can be done, as well.
  58570. */
  58571. this.manualEmitCount = -1;
  58572. /**
  58573. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  58574. */
  58575. this.updateSpeed = 0.01;
  58576. /**
  58577. * The amount of time the particle system is running (depends of the overall update speed).
  58578. */
  58579. this.targetStopDuration = 0;
  58580. /**
  58581. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  58582. */
  58583. this.disposeOnStop = false;
  58584. /**
  58585. * Minimum power of emitting particles.
  58586. */
  58587. this.minEmitPower = 1;
  58588. /**
  58589. * Maximum power of emitting particles.
  58590. */
  58591. this.maxEmitPower = 1;
  58592. /**
  58593. * Minimum life time of emitting particles.
  58594. */
  58595. this.minLifeTime = 1;
  58596. /**
  58597. * Maximum life time of emitting particles.
  58598. */
  58599. this.maxLifeTime = 1;
  58600. /**
  58601. * Minimum Size of emitting particles.
  58602. */
  58603. this.minSize = 1;
  58604. /**
  58605. * Maximum Size of emitting particles.
  58606. */
  58607. this.maxSize = 1;
  58608. /**
  58609. * Minimum scale of emitting particles on X axis.
  58610. */
  58611. this.minScaleX = 1;
  58612. /**
  58613. * Maximum scale of emitting particles on X axis.
  58614. */
  58615. this.maxScaleX = 1;
  58616. /**
  58617. * Minimum scale of emitting particles on Y axis.
  58618. */
  58619. this.minScaleY = 1;
  58620. /**
  58621. * Maximum scale of emitting particles on Y axis.
  58622. */
  58623. this.maxScaleY = 1;
  58624. /**
  58625. * Gets or sets the minimal initial rotation in radians.
  58626. */
  58627. this.minInitialRotation = 0;
  58628. /**
  58629. * Gets or sets the maximal initial rotation in radians.
  58630. */
  58631. this.maxInitialRotation = 0;
  58632. /**
  58633. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  58634. */
  58635. this.minAngularSpeed = 0;
  58636. /**
  58637. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  58638. */
  58639. this.maxAngularSpeed = 0;
  58640. /**
  58641. * The layer mask we are rendering the particles through.
  58642. */
  58643. this.layerMask = 0x0FFFFFFF;
  58644. /**
  58645. * This can help using your own shader to render the particle system.
  58646. * The according effect will be created
  58647. */
  58648. this.customShader = null;
  58649. /**
  58650. * By default particle system starts as soon as they are created. This prevents the
  58651. * automatic start to happen and let you decide when to start emitting particles.
  58652. */
  58653. this.preventAutoStart = false;
  58654. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  58655. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  58656. /**
  58657. * Callback triggered when the particle animation is ending.
  58658. */
  58659. this.onAnimationEnd = null;
  58660. /**
  58661. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  58662. */
  58663. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  58664. /**
  58665. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  58666. * to override the particles.
  58667. */
  58668. this.forceDepthWrite = false;
  58669. /** 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 */
  58670. this.preWarmCycles = 0;
  58671. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  58672. this.preWarmStepOffset = 1;
  58673. /**
  58674. * 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)
  58675. */
  58676. this.spriteCellChangeSpeed = 1;
  58677. /**
  58678. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  58679. */
  58680. this.startSpriteCellID = 0;
  58681. /**
  58682. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  58683. */
  58684. this.endSpriteCellID = 0;
  58685. /**
  58686. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  58687. */
  58688. this.spriteCellWidth = 0;
  58689. /**
  58690. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  58691. */
  58692. this.spriteCellHeight = 0;
  58693. /**
  58694. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  58695. */
  58696. this.spriteRandomStartCell = false;
  58697. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  58698. this.translationPivot = new BABYLON.Vector2(0, 0);
  58699. /**
  58700. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  58701. */
  58702. this.beginAnimationOnStart = false;
  58703. /**
  58704. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  58705. */
  58706. this.beginAnimationFrom = 0;
  58707. /**
  58708. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  58709. */
  58710. this.beginAnimationTo = 60;
  58711. /**
  58712. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  58713. */
  58714. this.beginAnimationLoop = false;
  58715. /**
  58716. * You can use gravity if you want to give an orientation to your particles.
  58717. */
  58718. this.gravity = BABYLON.Vector3.Zero();
  58719. this._colorGradients = null;
  58720. this._sizeGradients = null;
  58721. this._lifeTimeGradients = null;
  58722. this._angularSpeedGradients = null;
  58723. this._velocityGradients = null;
  58724. this._limitVelocityGradients = null;
  58725. this._dragGradients = null;
  58726. this._emitRateGradients = null;
  58727. this._startSizeGradients = null;
  58728. this._rampGradients = null;
  58729. this._colorRemapGradients = null;
  58730. this._alphaRemapGradients = null;
  58731. /**
  58732. * Defines the delay in milliseconds before starting the system (0 by default)
  58733. */
  58734. this.startDelay = 0;
  58735. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  58736. this.limitVelocityDamping = 0.4;
  58737. /**
  58738. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  58739. */
  58740. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58741. /**
  58742. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  58743. */
  58744. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58745. /**
  58746. * Color the particle will have at the end of its lifetime
  58747. */
  58748. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  58749. /**
  58750. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  58751. */
  58752. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58753. /** @hidden */
  58754. this._isSubEmitter = false;
  58755. /**
  58756. * Gets or sets the billboard mode to use when isBillboardBased = true.
  58757. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  58758. */
  58759. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  58760. this._isBillboardBased = true;
  58761. /**
  58762. * Local cache of defines for image processing.
  58763. */
  58764. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  58765. this.id = name;
  58766. this.name = name;
  58767. }
  58768. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  58769. /**
  58770. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  58771. */
  58772. get: function () {
  58773. return this._isAnimationSheetEnabled;
  58774. },
  58775. set: function (value) {
  58776. if (this._isAnimationSheetEnabled == value) {
  58777. return;
  58778. }
  58779. this._isAnimationSheetEnabled = value;
  58780. this._reset();
  58781. },
  58782. enumerable: true,
  58783. configurable: true
  58784. });
  58785. /**
  58786. * Get hosting scene
  58787. * @returns the scene
  58788. */
  58789. BaseParticleSystem.prototype.getScene = function () {
  58790. return this._scene;
  58791. };
  58792. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  58793. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  58794. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  58795. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  58796. };
  58797. /**
  58798. * Gets the current list of drag gradients.
  58799. * You must use addDragGradient and removeDragGradient to udpate this list
  58800. * @returns the list of drag gradients
  58801. */
  58802. BaseParticleSystem.prototype.getDragGradients = function () {
  58803. return this._dragGradients;
  58804. };
  58805. /**
  58806. * Gets the current list of limit velocity gradients.
  58807. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  58808. * @returns the list of limit velocity gradients
  58809. */
  58810. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  58811. return this._limitVelocityGradients;
  58812. };
  58813. /**
  58814. * Gets the current list of color gradients.
  58815. * You must use addColorGradient and removeColorGradient to udpate this list
  58816. * @returns the list of color gradients
  58817. */
  58818. BaseParticleSystem.prototype.getColorGradients = function () {
  58819. return this._colorGradients;
  58820. };
  58821. /**
  58822. * Gets the current list of size gradients.
  58823. * You must use addSizeGradient and removeSizeGradient to udpate this list
  58824. * @returns the list of size gradients
  58825. */
  58826. BaseParticleSystem.prototype.getSizeGradients = function () {
  58827. return this._sizeGradients;
  58828. };
  58829. /**
  58830. * Gets the current list of color remap gradients.
  58831. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  58832. * @returns the list of color remap gradients
  58833. */
  58834. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  58835. return this._colorRemapGradients;
  58836. };
  58837. /**
  58838. * Gets the current list of alpha remap gradients.
  58839. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  58840. * @returns the list of alpha remap gradients
  58841. */
  58842. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  58843. return this._alphaRemapGradients;
  58844. };
  58845. /**
  58846. * Gets the current list of life time gradients.
  58847. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  58848. * @returns the list of life time gradients
  58849. */
  58850. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  58851. return this._lifeTimeGradients;
  58852. };
  58853. /**
  58854. * Gets the current list of angular speed gradients.
  58855. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  58856. * @returns the list of angular speed gradients
  58857. */
  58858. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  58859. return this._angularSpeedGradients;
  58860. };
  58861. /**
  58862. * Gets the current list of velocity gradients.
  58863. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  58864. * @returns the list of velocity gradients
  58865. */
  58866. BaseParticleSystem.prototype.getVelocityGradients = function () {
  58867. return this._velocityGradients;
  58868. };
  58869. /**
  58870. * Gets the current list of start size gradients.
  58871. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  58872. * @returns the list of start size gradients
  58873. */
  58874. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  58875. return this._startSizeGradients;
  58876. };
  58877. /**
  58878. * Gets the current list of emit rate gradients.
  58879. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  58880. * @returns the list of emit rate gradients
  58881. */
  58882. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  58883. return this._emitRateGradients;
  58884. };
  58885. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  58886. /**
  58887. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58888. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58889. */
  58890. get: function () {
  58891. if (this.particleEmitterType.direction1) {
  58892. return this.particleEmitterType.direction1;
  58893. }
  58894. return BABYLON.Vector3.Zero();
  58895. },
  58896. set: function (value) {
  58897. if (this.particleEmitterType.direction1) {
  58898. this.particleEmitterType.direction1 = value;
  58899. }
  58900. },
  58901. enumerable: true,
  58902. configurable: true
  58903. });
  58904. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  58905. /**
  58906. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58907. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58908. */
  58909. get: function () {
  58910. if (this.particleEmitterType.direction2) {
  58911. return this.particleEmitterType.direction2;
  58912. }
  58913. return BABYLON.Vector3.Zero();
  58914. },
  58915. set: function (value) {
  58916. if (this.particleEmitterType.direction2) {
  58917. this.particleEmitterType.direction2 = value;
  58918. }
  58919. },
  58920. enumerable: true,
  58921. configurable: true
  58922. });
  58923. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  58924. /**
  58925. * 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.
  58926. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58927. */
  58928. get: function () {
  58929. if (this.particleEmitterType.minEmitBox) {
  58930. return this.particleEmitterType.minEmitBox;
  58931. }
  58932. return BABYLON.Vector3.Zero();
  58933. },
  58934. set: function (value) {
  58935. if (this.particleEmitterType.minEmitBox) {
  58936. this.particleEmitterType.minEmitBox = value;
  58937. }
  58938. },
  58939. enumerable: true,
  58940. configurable: true
  58941. });
  58942. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  58943. /**
  58944. * 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.
  58945. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58946. */
  58947. get: function () {
  58948. if (this.particleEmitterType.maxEmitBox) {
  58949. return this.particleEmitterType.maxEmitBox;
  58950. }
  58951. return BABYLON.Vector3.Zero();
  58952. },
  58953. set: function (value) {
  58954. if (this.particleEmitterType.maxEmitBox) {
  58955. this.particleEmitterType.maxEmitBox = value;
  58956. }
  58957. },
  58958. enumerable: true,
  58959. configurable: true
  58960. });
  58961. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  58962. /**
  58963. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  58964. */
  58965. get: function () {
  58966. return this._isBillboardBased;
  58967. },
  58968. set: function (value) {
  58969. if (this._isBillboardBased === value) {
  58970. return;
  58971. }
  58972. this._isBillboardBased = value;
  58973. this._reset();
  58974. },
  58975. enumerable: true,
  58976. configurable: true
  58977. });
  58978. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  58979. /**
  58980. * Gets the image processing configuration used either in this material.
  58981. */
  58982. get: function () {
  58983. return this._imageProcessingConfiguration;
  58984. },
  58985. /**
  58986. * Sets the Default image processing configuration used either in the this material.
  58987. *
  58988. * If sets to null, the scene one is in use.
  58989. */
  58990. set: function (value) {
  58991. this._attachImageProcessingConfiguration(value);
  58992. },
  58993. enumerable: true,
  58994. configurable: true
  58995. });
  58996. /**
  58997. * Attaches a new image processing configuration to the Standard Material.
  58998. * @param configuration
  58999. */
  59000. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  59001. if (configuration === this._imageProcessingConfiguration) {
  59002. return;
  59003. }
  59004. // Pick the scene configuration if needed.
  59005. if (!configuration) {
  59006. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  59007. }
  59008. else {
  59009. this._imageProcessingConfiguration = configuration;
  59010. }
  59011. };
  59012. /** @hidden */
  59013. BaseParticleSystem.prototype._reset = function () {
  59014. };
  59015. /** @hidden */
  59016. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  59017. if (!gradients) {
  59018. return this;
  59019. }
  59020. var index = 0;
  59021. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  59022. var valueGradient = gradients_1[_i];
  59023. if (valueGradient.gradient === gradient) {
  59024. gradients.splice(index, 1);
  59025. break;
  59026. }
  59027. index++;
  59028. }
  59029. if (texture) {
  59030. texture.dispose();
  59031. }
  59032. return this;
  59033. };
  59034. /**
  59035. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  59036. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  59037. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  59038. * @returns the emitter
  59039. */
  59040. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  59041. var particleEmitter = new BABYLON.PointParticleEmitter();
  59042. particleEmitter.direction1 = direction1;
  59043. particleEmitter.direction2 = direction2;
  59044. this.particleEmitterType = particleEmitter;
  59045. return particleEmitter;
  59046. };
  59047. /**
  59048. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  59049. * @param radius The radius of the hemisphere to emit from
  59050. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  59051. * @returns the emitter
  59052. */
  59053. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  59054. if (radius === void 0) { radius = 1; }
  59055. if (radiusRange === void 0) { radiusRange = 1; }
  59056. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  59057. this.particleEmitterType = particleEmitter;
  59058. return particleEmitter;
  59059. };
  59060. /**
  59061. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  59062. * @param radius The radius of the sphere to emit from
  59063. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  59064. * @returns the emitter
  59065. */
  59066. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  59067. if (radius === void 0) { radius = 1; }
  59068. if (radiusRange === void 0) { radiusRange = 1; }
  59069. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  59070. this.particleEmitterType = particleEmitter;
  59071. return particleEmitter;
  59072. };
  59073. /**
  59074. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  59075. * @param radius The radius of the sphere to emit from
  59076. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  59077. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  59078. * @returns the emitter
  59079. */
  59080. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  59081. if (radius === void 0) { radius = 1; }
  59082. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  59083. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  59084. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  59085. this.particleEmitterType = particleEmitter;
  59086. return particleEmitter;
  59087. };
  59088. /**
  59089. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  59090. * @param radius The radius of the emission cylinder
  59091. * @param height The height of the emission cylinder
  59092. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  59093. * @param directionRandomizer How much to randomize the particle direction [0-1]
  59094. * @returns the emitter
  59095. */
  59096. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  59097. if (radius === void 0) { radius = 1; }
  59098. if (height === void 0) { height = 1; }
  59099. if (radiusRange === void 0) { radiusRange = 1; }
  59100. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59101. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  59102. this.particleEmitterType = particleEmitter;
  59103. return particleEmitter;
  59104. };
  59105. /**
  59106. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  59107. * @param radius The radius of the cylinder to emit from
  59108. * @param height The height of the emission cylinder
  59109. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59110. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  59111. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  59112. * @returns the emitter
  59113. */
  59114. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  59115. if (radius === void 0) { radius = 1; }
  59116. if (height === void 0) { height = 1; }
  59117. if (radiusRange === void 0) { radiusRange = 1; }
  59118. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  59119. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  59120. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  59121. this.particleEmitterType = particleEmitter;
  59122. return particleEmitter;
  59123. };
  59124. /**
  59125. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  59126. * @param radius The radius of the cone to emit from
  59127. * @param angle The base angle of the cone
  59128. * @returns the emitter
  59129. */
  59130. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  59131. if (radius === void 0) { radius = 1; }
  59132. if (angle === void 0) { angle = Math.PI / 4; }
  59133. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  59134. this.particleEmitterType = particleEmitter;
  59135. return particleEmitter;
  59136. };
  59137. /**
  59138. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  59139. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  59140. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  59141. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  59142. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  59143. * @returns the emitter
  59144. */
  59145. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  59146. var particleEmitter = new BABYLON.BoxParticleEmitter();
  59147. this.particleEmitterType = particleEmitter;
  59148. this.direction1 = direction1;
  59149. this.direction2 = direction2;
  59150. this.minEmitBox = minEmitBox;
  59151. this.maxEmitBox = maxEmitBox;
  59152. return particleEmitter;
  59153. };
  59154. /**
  59155. * Source color is added to the destination color without alpha affecting the result
  59156. */
  59157. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  59158. /**
  59159. * Blend current color and particle color using particle’s alpha
  59160. */
  59161. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  59162. /**
  59163. * Add current color and particle color multiplied by particle’s alpha
  59164. */
  59165. BaseParticleSystem.BLENDMODE_ADD = 2;
  59166. /**
  59167. * Multiply current color with particle color
  59168. */
  59169. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  59170. /**
  59171. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  59172. */
  59173. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  59174. return BaseParticleSystem;
  59175. }());
  59176. BABYLON.BaseParticleSystem = BaseParticleSystem;
  59177. })(BABYLON || (BABYLON = {}));
  59178. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  59179. var BABYLON;
  59180. (function (BABYLON) {
  59181. /**
  59182. * This represents a particle system in Babylon.
  59183. * 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.
  59184. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  59185. * @example https://doc.babylonjs.com/babylon101/particles
  59186. */
  59187. var ParticleSystem = /** @class */ (function (_super) {
  59188. __extends(ParticleSystem, _super);
  59189. /**
  59190. * Instantiates a particle system.
  59191. * 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.
  59192. * @param name The name of the particle system
  59193. * @param capacity The max number of particles alive at the same time
  59194. * @param scene The scene the particle system belongs to
  59195. * @param customEffect a custom effect used to change the way particles are rendered by default
  59196. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  59197. * @param epsilon Offset used to render the particles
  59198. */
  59199. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  59200. if (customEffect === void 0) { customEffect = null; }
  59201. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  59202. if (epsilon === void 0) { epsilon = 0.01; }
  59203. var _this = _super.call(this, name) || this;
  59204. /**
  59205. * @hidden
  59206. */
  59207. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  59208. /**
  59209. * An event triggered when the system is disposed
  59210. */
  59211. _this.onDisposeObservable = new BABYLON.Observable();
  59212. _this._particles = new Array();
  59213. _this._stockParticles = new Array();
  59214. _this._newPartsExcess = 0;
  59215. _this._vertexBuffers = {};
  59216. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  59217. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  59218. _this._scaledDirection = BABYLON.Vector3.Zero();
  59219. _this._scaledGravity = BABYLON.Vector3.Zero();
  59220. _this._currentRenderId = -1;
  59221. _this._useInstancing = false;
  59222. _this._started = false;
  59223. _this._stopped = false;
  59224. _this._actualFrame = 0;
  59225. /** @hidden */
  59226. _this._currentEmitRate1 = 0;
  59227. /** @hidden */
  59228. _this._currentEmitRate2 = 0;
  59229. /** @hidden */
  59230. _this._currentStartSize1 = 0;
  59231. /** @hidden */
  59232. _this._currentStartSize2 = 0;
  59233. _this._rawTextureWidth = 256;
  59234. _this._useRampGradients = false;
  59235. /**
  59236. * @hidden
  59237. * If the particle systems emitter should be disposed when the particle system is disposed
  59238. */
  59239. _this._disposeEmitterOnDispose = false;
  59240. // start of sub system methods
  59241. /**
  59242. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  59243. * Its lifetime will start back at 0.
  59244. */
  59245. _this.recycleParticle = function (particle) {
  59246. // move particle from activeParticle list to stock particles
  59247. var lastParticle = _this._particles.pop();
  59248. if (lastParticle !== particle) {
  59249. lastParticle.copyTo(particle);
  59250. }
  59251. _this._stockParticles.push(lastParticle);
  59252. };
  59253. _this._createParticle = function () {
  59254. var particle;
  59255. if (_this._stockParticles.length !== 0) {
  59256. particle = _this._stockParticles.pop();
  59257. particle._reset();
  59258. }
  59259. else {
  59260. particle = new BABYLON.Particle(_this);
  59261. }
  59262. // Attach emitters
  59263. if (_this._subEmitters && _this._subEmitters.length > 0) {
  59264. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  59265. particle._attachedSubEmitters = [];
  59266. subEmitters.forEach(function (subEmitter) {
  59267. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  59268. var newEmitter = subEmitter.clone();
  59269. particle._attachedSubEmitters.push(newEmitter);
  59270. newEmitter.particleSystem.start();
  59271. }
  59272. });
  59273. }
  59274. return particle;
  59275. };
  59276. _this._emitFromParticle = function (particle) {
  59277. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  59278. return;
  59279. }
  59280. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  59281. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  59282. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  59283. var subSystem = subEmitter.clone();
  59284. particle._inheritParticleInfoToSubEmitter(subSystem);
  59285. subSystem.particleSystem._rootParticleSystem = _this;
  59286. _this.activeSubSystems.push(subSystem.particleSystem);
  59287. subSystem.particleSystem.start();
  59288. }
  59289. });
  59290. };
  59291. _this._capacity = capacity;
  59292. _this._epsilon = epsilon;
  59293. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  59294. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59295. // Setup the default processing configuration to the scene.
  59296. _this._attachImageProcessingConfiguration(null);
  59297. _this._customEffect = customEffect;
  59298. _this._scene.particleSystems.push(_this);
  59299. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  59300. _this._createIndexBuffer();
  59301. _this._createVertexBuffers();
  59302. // Default emitter type
  59303. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  59304. // Update
  59305. _this.updateFunction = function (particles) {
  59306. var noiseTextureSize = null;
  59307. var noiseTextureData = null;
  59308. if (_this.noiseTexture) { // We need to get texture data back to CPU
  59309. noiseTextureSize = _this.noiseTexture.getSize();
  59310. noiseTextureData = (_this.noiseTexture.getContent());
  59311. }
  59312. var _loop_1 = function () {
  59313. particle = particles[index];
  59314. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  59315. var previousAge = particle.age;
  59316. particle.age += scaledUpdateSpeed;
  59317. // Evaluate step to death
  59318. if (particle.age > particle.lifeTime) {
  59319. var diff = particle.age - previousAge;
  59320. var oldDiff = particle.lifeTime - previousAge;
  59321. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  59322. particle.age = particle.lifeTime;
  59323. }
  59324. var ratio = particle.age / particle.lifeTime;
  59325. // Color
  59326. if (_this._colorGradients && _this._colorGradients.length > 0) {
  59327. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  59328. if (currentGradient !== particle._currentColorGradient) {
  59329. particle._currentColor1.copyFrom(particle._currentColor2);
  59330. nextGradient.getColorToRef(particle._currentColor2);
  59331. particle._currentColorGradient = currentGradient;
  59332. }
  59333. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  59334. });
  59335. }
  59336. else {
  59337. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  59338. particle.color.addInPlace(_this._scaledColorStep);
  59339. if (particle.color.a < 0) {
  59340. particle.color.a = 0;
  59341. }
  59342. }
  59343. // Angular speed
  59344. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  59345. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  59346. if (currentGradient !== particle._currentAngularSpeedGradient) {
  59347. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  59348. particle._currentAngularSpeed2 = nextGradient.getFactor();
  59349. particle._currentAngularSpeedGradient = currentGradient;
  59350. }
  59351. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  59352. });
  59353. }
  59354. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  59355. // Direction
  59356. var directionScale = scaledUpdateSpeed;
  59357. /// Velocity
  59358. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  59359. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  59360. if (currentGradient !== particle._currentVelocityGradient) {
  59361. particle._currentVelocity1 = particle._currentVelocity2;
  59362. particle._currentVelocity2 = nextGradient.getFactor();
  59363. particle._currentVelocityGradient = currentGradient;
  59364. }
  59365. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  59366. });
  59367. }
  59368. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  59369. /// Limit velocity
  59370. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  59371. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  59372. if (currentGradient !== particle._currentLimitVelocityGradient) {
  59373. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  59374. particle._currentLimitVelocity2 = nextGradient.getFactor();
  59375. particle._currentLimitVelocityGradient = currentGradient;
  59376. }
  59377. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  59378. var currentVelocity = particle.direction.length();
  59379. if (currentVelocity > limitVelocity) {
  59380. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  59381. }
  59382. });
  59383. }
  59384. /// Drag
  59385. if (_this._dragGradients && _this._dragGradients.length > 0) {
  59386. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  59387. if (currentGradient !== particle._currentDragGradient) {
  59388. particle._currentDrag1 = particle._currentDrag2;
  59389. particle._currentDrag2 = nextGradient.getFactor();
  59390. particle._currentDragGradient = currentGradient;
  59391. }
  59392. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  59393. _this._scaledDirection.scaleInPlace(1.0 - drag);
  59394. });
  59395. }
  59396. particle.position.addInPlace(_this._scaledDirection);
  59397. // Noise
  59398. if (noiseTextureData && noiseTextureSize) {
  59399. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  59400. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  59401. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  59402. var force = BABYLON.Tmp.Vector3[0];
  59403. var scaledForce = BABYLON.Tmp.Vector3[1];
  59404. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  59405. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  59406. particle.direction.addInPlace(scaledForce);
  59407. }
  59408. // Gravity
  59409. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  59410. particle.direction.addInPlace(_this._scaledGravity);
  59411. // Size
  59412. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  59413. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  59414. if (currentGradient !== particle._currentSizeGradient) {
  59415. particle._currentSize1 = particle._currentSize2;
  59416. particle._currentSize2 = nextGradient.getFactor();
  59417. particle._currentSizeGradient = currentGradient;
  59418. }
  59419. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  59420. });
  59421. }
  59422. // Remap data
  59423. if (_this._useRampGradients) {
  59424. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  59425. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  59426. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  59427. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  59428. particle.remapData.x = min;
  59429. particle.remapData.y = max - min;
  59430. });
  59431. }
  59432. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  59433. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  59434. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  59435. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  59436. particle.remapData.z = min;
  59437. particle.remapData.w = max - min;
  59438. });
  59439. }
  59440. }
  59441. if (_this._isAnimationSheetEnabled) {
  59442. particle.updateCellIndex();
  59443. }
  59444. // Update the position of the attached sub-emitters to match their attached particle
  59445. particle._inheritParticleInfoToSubEmitters();
  59446. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  59447. _this._emitFromParticle(particle);
  59448. if (particle._attachedSubEmitters) {
  59449. particle._attachedSubEmitters.forEach(function (subEmitter) {
  59450. subEmitter.particleSystem.disposeOnStop = true;
  59451. subEmitter.particleSystem.stop();
  59452. });
  59453. particle._attachedSubEmitters = null;
  59454. }
  59455. _this.recycleParticle(particle);
  59456. index--;
  59457. return "continue";
  59458. }
  59459. };
  59460. var particle;
  59461. for (var index = 0; index < particles.length; index++) {
  59462. _loop_1();
  59463. }
  59464. };
  59465. return _this;
  59466. }
  59467. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  59468. /**
  59469. * Sets a callback that will be triggered when the system is disposed
  59470. */
  59471. set: function (callback) {
  59472. if (this._onDisposeObserver) {
  59473. this.onDisposeObservable.remove(this._onDisposeObserver);
  59474. }
  59475. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  59476. },
  59477. enumerable: true,
  59478. configurable: true
  59479. });
  59480. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  59481. /** Gets or sets a boolean indicating that ramp gradients must be used
  59482. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  59483. */
  59484. get: function () {
  59485. return this._useRampGradients;
  59486. },
  59487. set: function (value) {
  59488. if (this._useRampGradients === value) {
  59489. return;
  59490. }
  59491. this._useRampGradients = value;
  59492. this._resetEffect();
  59493. },
  59494. enumerable: true,
  59495. configurable: true
  59496. });
  59497. Object.defineProperty(ParticleSystem.prototype, "particles", {
  59498. //end of Sub-emitter
  59499. /**
  59500. * Gets the current list of active particles
  59501. */
  59502. get: function () {
  59503. return this._particles;
  59504. },
  59505. enumerable: true,
  59506. configurable: true
  59507. });
  59508. /**
  59509. * Returns the string "ParticleSystem"
  59510. * @returns a string containing the class name
  59511. */
  59512. ParticleSystem.prototype.getClassName = function () {
  59513. return "ParticleSystem";
  59514. };
  59515. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  59516. var newGradient = new BABYLON.FactorGradient();
  59517. newGradient.gradient = gradient;
  59518. newGradient.factor1 = factor;
  59519. newGradient.factor2 = factor2;
  59520. factorGradients.push(newGradient);
  59521. factorGradients.sort(function (a, b) {
  59522. if (a.gradient < b.gradient) {
  59523. return -1;
  59524. }
  59525. else if (a.gradient > b.gradient) {
  59526. return 1;
  59527. }
  59528. return 0;
  59529. });
  59530. };
  59531. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  59532. if (!factorGradients) {
  59533. return;
  59534. }
  59535. var index = 0;
  59536. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  59537. var factorGradient = factorGradients_1[_i];
  59538. if (factorGradient.gradient === gradient) {
  59539. factorGradients.splice(index, 1);
  59540. break;
  59541. }
  59542. index++;
  59543. }
  59544. };
  59545. /**
  59546. * Adds a new life time gradient
  59547. * @param gradient defines the gradient to use (between 0 and 1)
  59548. * @param factor defines the life time factor to affect to the specified gradient
  59549. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59550. * @returns the current particle system
  59551. */
  59552. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  59553. if (!this._lifeTimeGradients) {
  59554. this._lifeTimeGradients = [];
  59555. }
  59556. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  59557. return this;
  59558. };
  59559. /**
  59560. * Remove a specific life time gradient
  59561. * @param gradient defines the gradient to remove
  59562. * @returns the current particle system
  59563. */
  59564. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  59565. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  59566. return this;
  59567. };
  59568. /**
  59569. * Adds a new size gradient
  59570. * @param gradient defines the gradient to use (between 0 and 1)
  59571. * @param factor defines the size factor to affect to the specified gradient
  59572. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59573. * @returns the current particle system
  59574. */
  59575. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  59576. if (!this._sizeGradients) {
  59577. this._sizeGradients = [];
  59578. }
  59579. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  59580. return this;
  59581. };
  59582. /**
  59583. * Remove a specific size gradient
  59584. * @param gradient defines the gradient to remove
  59585. * @returns the current particle system
  59586. */
  59587. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  59588. this._removeFactorGradient(this._sizeGradients, gradient);
  59589. return this;
  59590. };
  59591. /**
  59592. * Adds a new color remap gradient
  59593. * @param gradient defines the gradient to use (between 0 and 1)
  59594. * @param min defines the color remap minimal range
  59595. * @param max defines the color remap maximal range
  59596. * @returns the current particle system
  59597. */
  59598. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  59599. if (!this._colorRemapGradients) {
  59600. this._colorRemapGradients = [];
  59601. }
  59602. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  59603. return this;
  59604. };
  59605. /**
  59606. * Remove a specific color remap gradient
  59607. * @param gradient defines the gradient to remove
  59608. * @returns the current particle system
  59609. */
  59610. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  59611. this._removeFactorGradient(this._colorRemapGradients, gradient);
  59612. return this;
  59613. };
  59614. /**
  59615. * Adds a new alpha remap gradient
  59616. * @param gradient defines the gradient to use (between 0 and 1)
  59617. * @param min defines the alpha remap minimal range
  59618. * @param max defines the alpha remap maximal range
  59619. * @returns the current particle system
  59620. */
  59621. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  59622. if (!this._alphaRemapGradients) {
  59623. this._alphaRemapGradients = [];
  59624. }
  59625. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  59626. return this;
  59627. };
  59628. /**
  59629. * Remove a specific alpha remap gradient
  59630. * @param gradient defines the gradient to remove
  59631. * @returns the current particle system
  59632. */
  59633. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  59634. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  59635. return this;
  59636. };
  59637. /**
  59638. * Adds a new angular speed gradient
  59639. * @param gradient defines the gradient to use (between 0 and 1)
  59640. * @param factor defines the angular speed to affect to the specified gradient
  59641. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59642. * @returns the current particle system
  59643. */
  59644. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  59645. if (!this._angularSpeedGradients) {
  59646. this._angularSpeedGradients = [];
  59647. }
  59648. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  59649. return this;
  59650. };
  59651. /**
  59652. * Remove a specific angular speed gradient
  59653. * @param gradient defines the gradient to remove
  59654. * @returns the current particle system
  59655. */
  59656. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  59657. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  59658. return this;
  59659. };
  59660. /**
  59661. * Adds a new velocity gradient
  59662. * @param gradient defines the gradient to use (between 0 and 1)
  59663. * @param factor defines the velocity to affect to the specified gradient
  59664. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59665. * @returns the current particle system
  59666. */
  59667. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  59668. if (!this._velocityGradients) {
  59669. this._velocityGradients = [];
  59670. }
  59671. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  59672. return this;
  59673. };
  59674. /**
  59675. * Remove a specific velocity gradient
  59676. * @param gradient defines the gradient to remove
  59677. * @returns the current particle system
  59678. */
  59679. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  59680. this._removeFactorGradient(this._velocityGradients, gradient);
  59681. return this;
  59682. };
  59683. /**
  59684. * Adds a new limit velocity gradient
  59685. * @param gradient defines the gradient to use (between 0 and 1)
  59686. * @param factor defines the limit velocity value to affect to the specified gradient
  59687. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59688. * @returns the current particle system
  59689. */
  59690. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  59691. if (!this._limitVelocityGradients) {
  59692. this._limitVelocityGradients = [];
  59693. }
  59694. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  59695. return this;
  59696. };
  59697. /**
  59698. * Remove a specific limit velocity gradient
  59699. * @param gradient defines the gradient to remove
  59700. * @returns the current particle system
  59701. */
  59702. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  59703. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  59704. return this;
  59705. };
  59706. /**
  59707. * Adds a new drag gradient
  59708. * @param gradient defines the gradient to use (between 0 and 1)
  59709. * @param factor defines the drag value to affect to the specified gradient
  59710. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59711. * @returns the current particle system
  59712. */
  59713. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  59714. if (!this._dragGradients) {
  59715. this._dragGradients = [];
  59716. }
  59717. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  59718. return this;
  59719. };
  59720. /**
  59721. * Remove a specific drag gradient
  59722. * @param gradient defines the gradient to remove
  59723. * @returns the current particle system
  59724. */
  59725. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  59726. this._removeFactorGradient(this._dragGradients, gradient);
  59727. return this;
  59728. };
  59729. /**
  59730. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  59731. * @param gradient defines the gradient to use (between 0 and 1)
  59732. * @param factor defines the emit rate value to affect to the specified gradient
  59733. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59734. * @returns the current particle system
  59735. */
  59736. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  59737. if (!this._emitRateGradients) {
  59738. this._emitRateGradients = [];
  59739. }
  59740. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  59741. return this;
  59742. };
  59743. /**
  59744. * Remove a specific emit rate gradient
  59745. * @param gradient defines the gradient to remove
  59746. * @returns the current particle system
  59747. */
  59748. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  59749. this._removeFactorGradient(this._emitRateGradients, gradient);
  59750. return this;
  59751. };
  59752. /**
  59753. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  59754. * @param gradient defines the gradient to use (between 0 and 1)
  59755. * @param factor defines the start size value to affect to the specified gradient
  59756. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59757. * @returns the current particle system
  59758. */
  59759. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  59760. if (!this._startSizeGradients) {
  59761. this._startSizeGradients = [];
  59762. }
  59763. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  59764. return this;
  59765. };
  59766. /**
  59767. * Remove a specific start size gradient
  59768. * @param gradient defines the gradient to remove
  59769. * @returns the current particle system
  59770. */
  59771. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  59772. this._removeFactorGradient(this._emitRateGradients, gradient);
  59773. return this;
  59774. };
  59775. ParticleSystem.prototype._createRampGradientTexture = function () {
  59776. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  59777. return;
  59778. }
  59779. var data = new Uint8Array(this._rawTextureWidth * 4);
  59780. var tmpColor = BABYLON.Tmp.Color3[0];
  59781. for (var x = 0; x < this._rawTextureWidth; x++) {
  59782. var ratio = x / this._rawTextureWidth;
  59783. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  59784. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  59785. data[x * 4] = tmpColor.r * 255;
  59786. data[x * 4 + 1] = tmpColor.g * 255;
  59787. data[x * 4 + 2] = tmpColor.b * 255;
  59788. data[x * 4 + 3] = 255;
  59789. });
  59790. }
  59791. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  59792. };
  59793. /**
  59794. * Gets the current list of ramp gradients.
  59795. * You must use addRampGradient and removeRampGradient to udpate this list
  59796. * @returns the list of ramp gradients
  59797. */
  59798. ParticleSystem.prototype.getRampGradients = function () {
  59799. return this._rampGradients;
  59800. };
  59801. /**
  59802. * Adds a new ramp gradient used to remap particle colors
  59803. * @param gradient defines the gradient to use (between 0 and 1)
  59804. * @param color defines the color to affect to the specified gradient
  59805. * @returns the current particle system
  59806. */
  59807. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  59808. if (!this._rampGradients) {
  59809. this._rampGradients = [];
  59810. }
  59811. var rampGradient = new BABYLON.Color3Gradient();
  59812. rampGradient.gradient = gradient;
  59813. rampGradient.color = color;
  59814. this._rampGradients.push(rampGradient);
  59815. this._rampGradients.sort(function (a, b) {
  59816. if (a.gradient < b.gradient) {
  59817. return -1;
  59818. }
  59819. else if (a.gradient > b.gradient) {
  59820. return 1;
  59821. }
  59822. return 0;
  59823. });
  59824. if (this._rampGradientsTexture) {
  59825. this._rampGradientsTexture.dispose();
  59826. this._rampGradientsTexture = null;
  59827. }
  59828. this._createRampGradientTexture();
  59829. return this;
  59830. };
  59831. /**
  59832. * Remove a specific ramp gradient
  59833. * @param gradient defines the gradient to remove
  59834. * @returns the current particle system
  59835. */
  59836. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  59837. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  59838. this._rampGradientsTexture = null;
  59839. if (this._rampGradients && this._rampGradients.length > 0) {
  59840. this._createRampGradientTexture();
  59841. }
  59842. return this;
  59843. };
  59844. /**
  59845. * Adds a new color gradient
  59846. * @param gradient defines the gradient to use (between 0 and 1)
  59847. * @param color1 defines the color to affect to the specified gradient
  59848. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  59849. * @returns this particle system
  59850. */
  59851. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  59852. if (!this._colorGradients) {
  59853. this._colorGradients = [];
  59854. }
  59855. var colorGradient = new BABYLON.ColorGradient();
  59856. colorGradient.gradient = gradient;
  59857. colorGradient.color1 = color1;
  59858. colorGradient.color2 = color2;
  59859. this._colorGradients.push(colorGradient);
  59860. this._colorGradients.sort(function (a, b) {
  59861. if (a.gradient < b.gradient) {
  59862. return -1;
  59863. }
  59864. else if (a.gradient > b.gradient) {
  59865. return 1;
  59866. }
  59867. return 0;
  59868. });
  59869. return this;
  59870. };
  59871. /**
  59872. * Remove a specific color gradient
  59873. * @param gradient defines the gradient to remove
  59874. * @returns this particle system
  59875. */
  59876. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  59877. if (!this._colorGradients) {
  59878. return this;
  59879. }
  59880. var index = 0;
  59881. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  59882. var colorGradient = _a[_i];
  59883. if (colorGradient.gradient === gradient) {
  59884. this._colorGradients.splice(index, 1);
  59885. break;
  59886. }
  59887. index++;
  59888. }
  59889. return this;
  59890. };
  59891. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  59892. u = Math.abs(u) * 0.5 + 0.5;
  59893. v = Math.abs(v) * 0.5 + 0.5;
  59894. var wrappedU = ((u * width) % width) | 0;
  59895. var wrappedV = ((v * height) % height) | 0;
  59896. var position = (wrappedU + wrappedV * width) * 4;
  59897. return pixels[position] / 255;
  59898. };
  59899. ParticleSystem.prototype._reset = function () {
  59900. this._resetEffect();
  59901. };
  59902. ParticleSystem.prototype._resetEffect = function () {
  59903. if (this._vertexBuffer) {
  59904. this._vertexBuffer.dispose();
  59905. this._vertexBuffer = null;
  59906. }
  59907. if (this._spriteBuffer) {
  59908. this._spriteBuffer.dispose();
  59909. this._spriteBuffer = null;
  59910. }
  59911. this._createVertexBuffers();
  59912. };
  59913. ParticleSystem.prototype._createVertexBuffers = function () {
  59914. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  59915. if (this._isAnimationSheetEnabled) {
  59916. this._vertexBufferSize += 1;
  59917. }
  59918. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59919. this._vertexBufferSize += 3;
  59920. }
  59921. if (this._useRampGradients) {
  59922. this._vertexBufferSize += 4;
  59923. }
  59924. var engine = this._scene.getEngine();
  59925. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  59926. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  59927. var dataOffset = 0;
  59928. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  59929. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  59930. dataOffset += 3;
  59931. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  59932. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  59933. dataOffset += 4;
  59934. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  59935. this._vertexBuffers["angle"] = options;
  59936. dataOffset += 1;
  59937. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  59938. this._vertexBuffers["size"] = size;
  59939. dataOffset += 2;
  59940. if (this._isAnimationSheetEnabled) {
  59941. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  59942. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  59943. dataOffset += 1;
  59944. }
  59945. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59946. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  59947. this._vertexBuffers["direction"] = directionBuffer;
  59948. dataOffset += 3;
  59949. }
  59950. if (this._useRampGradients) {
  59951. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  59952. this._vertexBuffers["remapData"] = rampDataBuffer;
  59953. dataOffset += 4;
  59954. }
  59955. var offsets;
  59956. if (this._useInstancing) {
  59957. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  59958. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  59959. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  59960. }
  59961. else {
  59962. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  59963. dataOffset += 2;
  59964. }
  59965. this._vertexBuffers["offset"] = offsets;
  59966. };
  59967. ParticleSystem.prototype._createIndexBuffer = function () {
  59968. if (this._useInstancing) {
  59969. return;
  59970. }
  59971. var indices = [];
  59972. var index = 0;
  59973. for (var count = 0; count < this._capacity; count++) {
  59974. indices.push(index);
  59975. indices.push(index + 1);
  59976. indices.push(index + 2);
  59977. indices.push(index);
  59978. indices.push(index + 2);
  59979. indices.push(index + 3);
  59980. index += 4;
  59981. }
  59982. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  59983. };
  59984. /**
  59985. * Gets the maximum number of particles active at the same time.
  59986. * @returns The max number of active particles.
  59987. */
  59988. ParticleSystem.prototype.getCapacity = function () {
  59989. return this._capacity;
  59990. };
  59991. /**
  59992. * Gets whether there are still active particles in the system.
  59993. * @returns True if it is alive, otherwise false.
  59994. */
  59995. ParticleSystem.prototype.isAlive = function () {
  59996. return this._alive;
  59997. };
  59998. /**
  59999. * Gets if the system has been started. (Note: this will still be true after stop is called)
  60000. * @returns True if it has been started, otherwise false.
  60001. */
  60002. ParticleSystem.prototype.isStarted = function () {
  60003. return this._started;
  60004. };
  60005. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  60006. var _this = this;
  60007. this._subEmitters = new Array();
  60008. if (this.subEmitters) {
  60009. this.subEmitters.forEach(function (subEmitter) {
  60010. if (subEmitter instanceof ParticleSystem) {
  60011. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  60012. }
  60013. else if (subEmitter instanceof BABYLON.SubEmitter) {
  60014. _this._subEmitters.push([subEmitter]);
  60015. }
  60016. else if (subEmitter instanceof Array) {
  60017. _this._subEmitters.push(subEmitter);
  60018. }
  60019. });
  60020. }
  60021. };
  60022. /**
  60023. * Starts the particle system and begins to emit
  60024. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  60025. */
  60026. ParticleSystem.prototype.start = function (delay) {
  60027. var _this = this;
  60028. if (delay === void 0) { delay = this.startDelay; }
  60029. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  60030. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  60031. }
  60032. if (delay) {
  60033. setTimeout(function () {
  60034. _this.start(0);
  60035. }, delay);
  60036. return;
  60037. }
  60038. // Convert the subEmitters field to the constant type field _subEmitters
  60039. this._prepareSubEmitterInternalArray();
  60040. this._started = true;
  60041. this._stopped = false;
  60042. this._actualFrame = 0;
  60043. if (this._subEmitters && this._subEmitters.length != 0) {
  60044. this.activeSubSystems = new Array();
  60045. }
  60046. // Reset emit gradient so it acts the same on every start
  60047. if (this._emitRateGradients) {
  60048. if (this._emitRateGradients.length > 0) {
  60049. this._currentEmitRateGradient = this._emitRateGradients[0];
  60050. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  60051. this._currentEmitRate2 = this._currentEmitRate1;
  60052. }
  60053. if (this._emitRateGradients.length > 1) {
  60054. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  60055. }
  60056. }
  60057. // Reset start size gradient so it acts the same on every start
  60058. if (this._startSizeGradients) {
  60059. if (this._startSizeGradients.length > 0) {
  60060. this._currentStartSizeGradient = this._startSizeGradients[0];
  60061. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  60062. this._currentStartSize2 = this._currentStartSize1;
  60063. }
  60064. if (this._startSizeGradients.length > 1) {
  60065. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  60066. }
  60067. }
  60068. if (this.preWarmCycles) {
  60069. if (this.emitter instanceof BABYLON.AbstractMesh) {
  60070. this.emitter.computeWorldMatrix(true);
  60071. }
  60072. var noiseTextureAsProcedural_1 = this.noiseTexture;
  60073. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  60074. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  60075. setTimeout(function () {
  60076. for (var index = 0; index < _this.preWarmCycles; index++) {
  60077. _this.animate(true);
  60078. noiseTextureAsProcedural_1.render();
  60079. }
  60080. });
  60081. });
  60082. }
  60083. else {
  60084. for (var index = 0; index < this.preWarmCycles; index++) {
  60085. this.animate(true);
  60086. }
  60087. }
  60088. }
  60089. // Animations
  60090. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  60091. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  60092. }
  60093. };
  60094. /**
  60095. * Stops the particle system.
  60096. * @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.
  60097. */
  60098. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  60099. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  60100. this._stopped = true;
  60101. if (stopSubEmitters) {
  60102. this._stopSubEmitters();
  60103. }
  60104. };
  60105. // animation sheet
  60106. /**
  60107. * Remove all active particles
  60108. */
  60109. ParticleSystem.prototype.reset = function () {
  60110. this._stockParticles = [];
  60111. this._particles = [];
  60112. };
  60113. /**
  60114. * @hidden (for internal use only)
  60115. */
  60116. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  60117. var offset = index * this._vertexBufferSize;
  60118. this._vertexData[offset++] = particle.position.x;
  60119. this._vertexData[offset++] = particle.position.y;
  60120. this._vertexData[offset++] = particle.position.z;
  60121. this._vertexData[offset++] = particle.color.r;
  60122. this._vertexData[offset++] = particle.color.g;
  60123. this._vertexData[offset++] = particle.color.b;
  60124. this._vertexData[offset++] = particle.color.a;
  60125. this._vertexData[offset++] = particle.angle;
  60126. this._vertexData[offset++] = particle.scale.x * particle.size;
  60127. this._vertexData[offset++] = particle.scale.y * particle.size;
  60128. if (this._isAnimationSheetEnabled) {
  60129. this._vertexData[offset++] = particle.cellIndex;
  60130. }
  60131. if (!this._isBillboardBased) {
  60132. if (particle._initialDirection) {
  60133. this._vertexData[offset++] = particle._initialDirection.x;
  60134. this._vertexData[offset++] = particle._initialDirection.y;
  60135. this._vertexData[offset++] = particle._initialDirection.z;
  60136. }
  60137. else {
  60138. this._vertexData[offset++] = particle.direction.x;
  60139. this._vertexData[offset++] = particle.direction.y;
  60140. this._vertexData[offset++] = particle.direction.z;
  60141. }
  60142. }
  60143. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  60144. this._vertexData[offset++] = particle.direction.x;
  60145. this._vertexData[offset++] = particle.direction.y;
  60146. this._vertexData[offset++] = particle.direction.z;
  60147. }
  60148. if (this._useRampGradients) {
  60149. this._vertexData[offset++] = particle.remapData.x;
  60150. this._vertexData[offset++] = particle.remapData.y;
  60151. this._vertexData[offset++] = particle.remapData.z;
  60152. this._vertexData[offset++] = particle.remapData.w;
  60153. }
  60154. if (!this._useInstancing) {
  60155. if (this._isAnimationSheetEnabled) {
  60156. if (offsetX === 0) {
  60157. offsetX = this._epsilon;
  60158. }
  60159. else if (offsetX === 1) {
  60160. offsetX = 1 - this._epsilon;
  60161. }
  60162. if (offsetY === 0) {
  60163. offsetY = this._epsilon;
  60164. }
  60165. else if (offsetY === 1) {
  60166. offsetY = 1 - this._epsilon;
  60167. }
  60168. }
  60169. this._vertexData[offset++] = offsetX;
  60170. this._vertexData[offset++] = offsetY;
  60171. }
  60172. };
  60173. ParticleSystem.prototype._stopSubEmitters = function () {
  60174. if (!this.activeSubSystems) {
  60175. return;
  60176. }
  60177. this.activeSubSystems.forEach(function (subSystem) {
  60178. subSystem.stop(true);
  60179. });
  60180. this.activeSubSystems = new Array();
  60181. };
  60182. ParticleSystem.prototype._removeFromRoot = function () {
  60183. if (!this._rootParticleSystem) {
  60184. return;
  60185. }
  60186. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  60187. if (index !== -1) {
  60188. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  60189. }
  60190. this._rootParticleSystem = null;
  60191. };
  60192. // End of sub system methods
  60193. ParticleSystem.prototype._update = function (newParticles) {
  60194. var _this = this;
  60195. // Update current
  60196. this._alive = this._particles.length > 0;
  60197. if (this.emitter.position) {
  60198. var emitterMesh = this.emitter;
  60199. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  60200. }
  60201. else {
  60202. var emitterPosition = this.emitter;
  60203. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  60204. }
  60205. this.updateFunction(this._particles);
  60206. // Add new ones
  60207. var particle;
  60208. var _loop_2 = function () {
  60209. if (this_1._particles.length === this_1._capacity) {
  60210. return "break";
  60211. }
  60212. particle = this_1._createParticle();
  60213. this_1._particles.push(particle);
  60214. // Emitter
  60215. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  60216. if (this_1.startPositionFunction) {
  60217. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  60218. }
  60219. else {
  60220. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  60221. }
  60222. if (this_1.startDirectionFunction) {
  60223. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  60224. }
  60225. else {
  60226. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  60227. }
  60228. if (emitPower === 0) {
  60229. if (!particle._initialDirection) {
  60230. particle._initialDirection = particle.direction.clone();
  60231. }
  60232. else {
  60233. particle._initialDirection.copyFrom(particle.direction);
  60234. }
  60235. }
  60236. else {
  60237. particle._initialDirection = null;
  60238. }
  60239. particle.direction.scaleInPlace(emitPower);
  60240. // Life time
  60241. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  60242. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  60243. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  60244. var factorGradient1 = currentGradient;
  60245. var factorGradient2 = nextGradient;
  60246. var lifeTime1 = factorGradient1.getFactor();
  60247. var lifeTime2 = factorGradient2.getFactor();
  60248. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  60249. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  60250. });
  60251. }
  60252. else {
  60253. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  60254. }
  60255. // Size
  60256. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  60257. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  60258. }
  60259. else {
  60260. particle._currentSizeGradient = this_1._sizeGradients[0];
  60261. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  60262. particle.size = particle._currentSize1;
  60263. if (this_1._sizeGradients.length > 1) {
  60264. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  60265. }
  60266. else {
  60267. particle._currentSize2 = particle._currentSize1;
  60268. }
  60269. }
  60270. // Size and scale
  60271. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  60272. // Adjust scale by start size
  60273. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  60274. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  60275. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  60276. if (currentGradient !== _this._currentStartSizeGradient) {
  60277. _this._currentStartSize1 = _this._currentStartSize2;
  60278. _this._currentStartSize2 = nextGradient.getFactor();
  60279. _this._currentStartSizeGradient = currentGradient;
  60280. }
  60281. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  60282. particle.scale.scaleInPlace(value);
  60283. });
  60284. }
  60285. // Angle
  60286. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  60287. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  60288. }
  60289. else {
  60290. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  60291. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  60292. particle._currentAngularSpeed1 = particle.angularSpeed;
  60293. if (this_1._angularSpeedGradients.length > 1) {
  60294. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  60295. }
  60296. else {
  60297. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  60298. }
  60299. }
  60300. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  60301. // Velocity
  60302. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  60303. particle._currentVelocityGradient = this_1._velocityGradients[0];
  60304. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  60305. if (this_1._velocityGradients.length > 1) {
  60306. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  60307. }
  60308. else {
  60309. particle._currentVelocity2 = particle._currentVelocity1;
  60310. }
  60311. }
  60312. // Limit velocity
  60313. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  60314. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  60315. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  60316. if (this_1._limitVelocityGradients.length > 1) {
  60317. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  60318. }
  60319. else {
  60320. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  60321. }
  60322. }
  60323. // Drag
  60324. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  60325. particle._currentDragGradient = this_1._dragGradients[0];
  60326. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  60327. if (this_1._dragGradients.length > 1) {
  60328. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  60329. }
  60330. else {
  60331. particle._currentDrag2 = particle._currentDrag1;
  60332. }
  60333. }
  60334. // Color
  60335. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  60336. step = BABYLON.Scalar.RandomRange(0, 1.0);
  60337. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  60338. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  60339. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  60340. }
  60341. else {
  60342. particle._currentColorGradient = this_1._colorGradients[0];
  60343. particle._currentColorGradient.getColorToRef(particle.color);
  60344. particle._currentColor1.copyFrom(particle.color);
  60345. if (this_1._colorGradients.length > 1) {
  60346. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  60347. }
  60348. else {
  60349. particle._currentColor2.copyFrom(particle.color);
  60350. }
  60351. }
  60352. // Sheet
  60353. if (this_1._isAnimationSheetEnabled) {
  60354. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  60355. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  60356. }
  60357. // Inherited Velocity
  60358. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  60359. // Ramp
  60360. if (this_1._useRampGradients) {
  60361. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  60362. }
  60363. // Noise texture coordinates
  60364. if (this_1.noiseTexture) {
  60365. if (particle._randomNoiseCoordinates1) {
  60366. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  60367. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  60368. }
  60369. else {
  60370. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  60371. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  60372. }
  60373. }
  60374. // Update the position of the attached sub-emitters to match their attached particle
  60375. particle._inheritParticleInfoToSubEmitters();
  60376. };
  60377. var this_1 = this, step;
  60378. for (var index = 0; index < newParticles; index++) {
  60379. var state_1 = _loop_2();
  60380. if (state_1 === "break")
  60381. break;
  60382. }
  60383. };
  60384. /** @hidden */
  60385. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  60386. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60387. if (isBillboardBased === void 0) { isBillboardBased = false; }
  60388. if (useRampGradients === void 0) { useRampGradients = false; }
  60389. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  60390. if (isAnimationSheetEnabled) {
  60391. attributeNamesOrOptions.push("cellIndex");
  60392. }
  60393. if (!isBillboardBased) {
  60394. attributeNamesOrOptions.push("direction");
  60395. }
  60396. if (useRampGradients) {
  60397. attributeNamesOrOptions.push("remapData");
  60398. }
  60399. return attributeNamesOrOptions;
  60400. };
  60401. /** @hidden */
  60402. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  60403. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60404. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  60405. if (isAnimationSheetEnabled) {
  60406. effectCreationOption.push("particlesInfos");
  60407. }
  60408. return effectCreationOption;
  60409. };
  60410. /** @hidden */
  60411. ParticleSystem.prototype._getEffect = function (blendMode) {
  60412. if (this._customEffect) {
  60413. return this._customEffect;
  60414. }
  60415. var defines = [];
  60416. if (this._scene.clipPlane) {
  60417. defines.push("#define CLIPPLANE");
  60418. }
  60419. if (this._scene.clipPlane2) {
  60420. defines.push("#define CLIPPLANE2");
  60421. }
  60422. if (this._scene.clipPlane3) {
  60423. defines.push("#define CLIPPLANE3");
  60424. }
  60425. if (this._scene.clipPlane4) {
  60426. defines.push("#define CLIPPLANE4");
  60427. }
  60428. if (this._isAnimationSheetEnabled) {
  60429. defines.push("#define ANIMATESHEET");
  60430. }
  60431. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  60432. defines.push("#define BLENDMULTIPLYMODE");
  60433. }
  60434. if (this._useRampGradients) {
  60435. defines.push("#define RAMPGRADIENT");
  60436. }
  60437. if (this._isBillboardBased) {
  60438. defines.push("#define BILLBOARD");
  60439. switch (this.billboardMode) {
  60440. case ParticleSystem.BILLBOARDMODE_Y:
  60441. defines.push("#define BILLBOARDY");
  60442. break;
  60443. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  60444. defines.push("#define BILLBOARDSTRETCHED");
  60445. break;
  60446. case ParticleSystem.BILLBOARDMODE_ALL:
  60447. default:
  60448. break;
  60449. }
  60450. }
  60451. if (this._imageProcessingConfiguration) {
  60452. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  60453. defines.push(this._imageProcessingConfigurationDefines.toString());
  60454. }
  60455. // Effect
  60456. var join = defines.join("\n");
  60457. if (this._cachedDefines !== join) {
  60458. this._cachedDefines = join;
  60459. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  60460. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  60461. var samplers = ["diffuseSampler", "rampSampler"];
  60462. if (BABYLON.ImageProcessingConfiguration) {
  60463. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  60464. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  60465. }
  60466. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  60467. }
  60468. return this._effect;
  60469. };
  60470. /**
  60471. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  60472. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  60473. */
  60474. ParticleSystem.prototype.animate = function (preWarmOnly) {
  60475. var _this = this;
  60476. if (preWarmOnly === void 0) { preWarmOnly = false; }
  60477. if (!this._started) {
  60478. return;
  60479. }
  60480. if (!preWarmOnly) {
  60481. // Check
  60482. if (!this.isReady()) {
  60483. return;
  60484. }
  60485. if (this._currentRenderId === this._scene.getRenderId()) {
  60486. return;
  60487. }
  60488. this._currentRenderId = this._scene.getRenderId();
  60489. }
  60490. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  60491. // Determine the number of particles we need to create
  60492. var newParticles;
  60493. if (this.manualEmitCount > -1) {
  60494. newParticles = this.manualEmitCount;
  60495. this._newPartsExcess = 0;
  60496. this.manualEmitCount = 0;
  60497. }
  60498. else {
  60499. var rate_1 = this.emitRate;
  60500. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  60501. var ratio = this._actualFrame / this.targetStopDuration;
  60502. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  60503. if (currentGradient !== _this._currentEmitRateGradient) {
  60504. _this._currentEmitRate1 = _this._currentEmitRate2;
  60505. _this._currentEmitRate2 = nextGradient.getFactor();
  60506. _this._currentEmitRateGradient = currentGradient;
  60507. }
  60508. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  60509. });
  60510. }
  60511. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  60512. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  60513. }
  60514. if (this._newPartsExcess > 1.0) {
  60515. newParticles += this._newPartsExcess >> 0;
  60516. this._newPartsExcess -= this._newPartsExcess >> 0;
  60517. }
  60518. this._alive = false;
  60519. if (!this._stopped) {
  60520. this._actualFrame += this._scaledUpdateSpeed;
  60521. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  60522. this.stop();
  60523. }
  60524. }
  60525. else {
  60526. newParticles = 0;
  60527. }
  60528. this._update(newParticles);
  60529. // Stopped?
  60530. if (this._stopped) {
  60531. if (!this._alive) {
  60532. this._started = false;
  60533. if (this.onAnimationEnd) {
  60534. this.onAnimationEnd();
  60535. }
  60536. if (this.disposeOnStop) {
  60537. this._scene._toBeDisposed.push(this);
  60538. }
  60539. }
  60540. }
  60541. if (!preWarmOnly) {
  60542. // Update VBO
  60543. var offset = 0;
  60544. for (var index = 0; index < this._particles.length; index++) {
  60545. var particle = this._particles[index];
  60546. this._appendParticleVertices(offset, particle);
  60547. offset += this._useInstancing ? 1 : 4;
  60548. }
  60549. if (this._vertexBuffer) {
  60550. this._vertexBuffer.update(this._vertexData);
  60551. }
  60552. }
  60553. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  60554. this.stop();
  60555. }
  60556. };
  60557. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  60558. this._appendParticleVertex(offset++, particle, 0, 0);
  60559. if (!this._useInstancing) {
  60560. this._appendParticleVertex(offset++, particle, 1, 0);
  60561. this._appendParticleVertex(offset++, particle, 1, 1);
  60562. this._appendParticleVertex(offset++, particle, 0, 1);
  60563. }
  60564. };
  60565. /**
  60566. * Rebuilds the particle system.
  60567. */
  60568. ParticleSystem.prototype.rebuild = function () {
  60569. this._createIndexBuffer();
  60570. if (this._vertexBuffer) {
  60571. this._vertexBuffer._rebuild();
  60572. }
  60573. };
  60574. /**
  60575. * Is this system ready to be used/rendered
  60576. * @return true if the system is ready
  60577. */
  60578. ParticleSystem.prototype.isReady = function () {
  60579. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  60580. return false;
  60581. }
  60582. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  60583. if (!this._getEffect(this.blendMode).isReady()) {
  60584. return false;
  60585. }
  60586. }
  60587. else {
  60588. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  60589. return false;
  60590. }
  60591. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  60592. return false;
  60593. }
  60594. }
  60595. return true;
  60596. };
  60597. ParticleSystem.prototype._render = function (blendMode) {
  60598. var effect = this._getEffect(blendMode);
  60599. var engine = this._scene.getEngine();
  60600. // Render
  60601. engine.enableEffect(effect);
  60602. var viewMatrix = this._scene.getViewMatrix();
  60603. effect.setTexture("diffuseSampler", this.particleTexture);
  60604. effect.setMatrix("view", viewMatrix);
  60605. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  60606. if (this._isAnimationSheetEnabled && this.particleTexture) {
  60607. var baseSize = this.particleTexture.getBaseSize();
  60608. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  60609. }
  60610. effect.setVector2("translationPivot", this.translationPivot);
  60611. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  60612. if (this._isBillboardBased) {
  60613. var camera = this._scene.activeCamera;
  60614. effect.setVector3("eyePosition", camera.globalPosition);
  60615. }
  60616. if (this._rampGradientsTexture) {
  60617. effect.setTexture("rampSampler", this._rampGradientsTexture);
  60618. }
  60619. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  60620. var invView = viewMatrix.clone();
  60621. invView.invert();
  60622. effect.setMatrix("invView", invView);
  60623. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  60624. }
  60625. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  60626. // image processing
  60627. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  60628. this._imageProcessingConfiguration.bind(effect);
  60629. }
  60630. // Draw order
  60631. switch (blendMode) {
  60632. case ParticleSystem.BLENDMODE_ADD:
  60633. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  60634. break;
  60635. case ParticleSystem.BLENDMODE_ONEONE:
  60636. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  60637. break;
  60638. case ParticleSystem.BLENDMODE_STANDARD:
  60639. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  60640. break;
  60641. case ParticleSystem.BLENDMODE_MULTIPLY:
  60642. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  60643. break;
  60644. }
  60645. if (this._useInstancing) {
  60646. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  60647. }
  60648. else {
  60649. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  60650. }
  60651. return this._particles.length;
  60652. };
  60653. /**
  60654. * Renders the particle system in its current state.
  60655. * @returns the current number of particles
  60656. */
  60657. ParticleSystem.prototype.render = function () {
  60658. // Check
  60659. if (!this.isReady() || !this._particles.length) {
  60660. return 0;
  60661. }
  60662. var engine = this._scene.getEngine();
  60663. engine.setState(false);
  60664. if (this.forceDepthWrite) {
  60665. engine.setDepthWrite(true);
  60666. }
  60667. var outparticles = 0;
  60668. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  60669. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  60670. }
  60671. outparticles = this._render(this.blendMode);
  60672. engine.unbindInstanceAttributes();
  60673. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60674. return outparticles;
  60675. };
  60676. /**
  60677. * Disposes the particle system and free the associated resources
  60678. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  60679. */
  60680. ParticleSystem.prototype.dispose = function (disposeTexture) {
  60681. if (disposeTexture === void 0) { disposeTexture = true; }
  60682. if (this._vertexBuffer) {
  60683. this._vertexBuffer.dispose();
  60684. this._vertexBuffer = null;
  60685. }
  60686. if (this._spriteBuffer) {
  60687. this._spriteBuffer.dispose();
  60688. this._spriteBuffer = null;
  60689. }
  60690. if (this._indexBuffer) {
  60691. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  60692. this._indexBuffer = null;
  60693. }
  60694. if (disposeTexture && this.particleTexture) {
  60695. this.particleTexture.dispose();
  60696. this.particleTexture = null;
  60697. }
  60698. if (disposeTexture && this.noiseTexture) {
  60699. this.noiseTexture.dispose();
  60700. this.noiseTexture = null;
  60701. }
  60702. if (this._rampGradientsTexture) {
  60703. this._rampGradientsTexture.dispose();
  60704. this._rampGradientsTexture = null;
  60705. }
  60706. this._removeFromRoot();
  60707. if (this._subEmitters && this._subEmitters.length) {
  60708. for (var index = 0; index < this._subEmitters.length; index++) {
  60709. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  60710. var subEmitter = _a[_i];
  60711. subEmitter.dispose();
  60712. }
  60713. }
  60714. this._subEmitters = [];
  60715. this.subEmitters = [];
  60716. }
  60717. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  60718. this.emitter.dispose(true);
  60719. }
  60720. // Remove from scene
  60721. var index = this._scene.particleSystems.indexOf(this);
  60722. if (index > -1) {
  60723. this._scene.particleSystems.splice(index, 1);
  60724. }
  60725. this._scene._activeParticleSystems.dispose();
  60726. // Callback
  60727. this.onDisposeObservable.notifyObservers(this);
  60728. this.onDisposeObservable.clear();
  60729. this.reset();
  60730. };
  60731. // Clone
  60732. /**
  60733. * Clones the particle system.
  60734. * @param name The name of the cloned object
  60735. * @param newEmitter The new emitter to use
  60736. * @returns the cloned particle system
  60737. */
  60738. ParticleSystem.prototype.clone = function (name, newEmitter) {
  60739. var custom = null;
  60740. var program = null;
  60741. if (this.customShader != null) {
  60742. program = this.customShader;
  60743. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  60744. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  60745. }
  60746. else if (this._customEffect) {
  60747. custom = this._customEffect;
  60748. }
  60749. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  60750. result.customShader = program;
  60751. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  60752. if (newEmitter === undefined) {
  60753. newEmitter = this.emitter;
  60754. }
  60755. result.noiseTexture = this.noiseTexture;
  60756. result.emitter = newEmitter;
  60757. if (this.particleTexture) {
  60758. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  60759. }
  60760. // Clone gradients
  60761. if (this._colorGradients) {
  60762. this._colorGradients.forEach(function (v) {
  60763. result.addColorGradient(v.gradient, v.color1, v.color2);
  60764. });
  60765. }
  60766. if (this._dragGradients) {
  60767. this._dragGradients.forEach(function (v) {
  60768. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  60769. });
  60770. }
  60771. if (this._angularSpeedGradients) {
  60772. this._angularSpeedGradients.forEach(function (v) {
  60773. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  60774. });
  60775. }
  60776. if (this._emitRateGradients) {
  60777. this._emitRateGradients.forEach(function (v) {
  60778. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  60779. });
  60780. }
  60781. if (this._lifeTimeGradients) {
  60782. this._lifeTimeGradients.forEach(function (v) {
  60783. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  60784. });
  60785. }
  60786. if (this._limitVelocityGradients) {
  60787. this._limitVelocityGradients.forEach(function (v) {
  60788. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  60789. });
  60790. }
  60791. if (this._sizeGradients) {
  60792. this._sizeGradients.forEach(function (v) {
  60793. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  60794. });
  60795. }
  60796. if (this._startSizeGradients) {
  60797. this._startSizeGradients.forEach(function (v) {
  60798. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  60799. });
  60800. }
  60801. if (this._velocityGradients) {
  60802. this._velocityGradients.forEach(function (v) {
  60803. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  60804. });
  60805. }
  60806. if (this._rampGradients) {
  60807. this._rampGradients.forEach(function (v) {
  60808. result.addRampGradient(v.gradient, v.color);
  60809. });
  60810. }
  60811. if (this._colorRemapGradients) {
  60812. this._colorRemapGradients.forEach(function (v) {
  60813. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  60814. });
  60815. }
  60816. if (this._alphaRemapGradients) {
  60817. this._alphaRemapGradients.forEach(function (v) {
  60818. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  60819. });
  60820. }
  60821. if (!this.preventAutoStart) {
  60822. result.start();
  60823. }
  60824. return result;
  60825. };
  60826. /**
  60827. * Serializes the particle system to a JSON object.
  60828. * @returns the JSON object
  60829. */
  60830. ParticleSystem.prototype.serialize = function () {
  60831. var serializationObject = {};
  60832. ParticleSystem._Serialize(serializationObject, this);
  60833. serializationObject.textureMask = this.textureMask.asArray();
  60834. serializationObject.customShader = this.customShader;
  60835. serializationObject.preventAutoStart = this.preventAutoStart;
  60836. // SubEmitters
  60837. if (this.subEmitters) {
  60838. serializationObject.subEmitters = [];
  60839. if (!this._subEmitters) {
  60840. this._prepareSubEmitterInternalArray();
  60841. }
  60842. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  60843. var subs = _a[_i];
  60844. var cell = [];
  60845. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  60846. var sub = subs_1[_b];
  60847. cell.push(sub.serialize());
  60848. }
  60849. serializationObject.subEmitters.push(cell);
  60850. }
  60851. }
  60852. return serializationObject;
  60853. };
  60854. /** @hidden */
  60855. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  60856. serializationObject.name = particleSystem.name;
  60857. serializationObject.id = particleSystem.id;
  60858. serializationObject.capacity = particleSystem.getCapacity();
  60859. // Emitter
  60860. if (particleSystem.emitter.position) {
  60861. var emitterMesh = particleSystem.emitter;
  60862. serializationObject.emitterId = emitterMesh.id;
  60863. }
  60864. else {
  60865. var emitterPosition = particleSystem.emitter;
  60866. serializationObject.emitter = emitterPosition.asArray();
  60867. }
  60868. // Emitter
  60869. if (particleSystem.particleEmitterType) {
  60870. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  60871. }
  60872. if (particleSystem.particleTexture) {
  60873. serializationObject.textureName = particleSystem.particleTexture.name;
  60874. serializationObject.invertY = particleSystem.particleTexture._invertY;
  60875. }
  60876. // Animations
  60877. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  60878. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  60879. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  60880. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  60881. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  60882. // Particle system
  60883. serializationObject.startDelay = particleSystem.startDelay;
  60884. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  60885. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  60886. serializationObject.billboardMode = particleSystem.billboardMode;
  60887. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  60888. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  60889. serializationObject.minSize = particleSystem.minSize;
  60890. serializationObject.maxSize = particleSystem.maxSize;
  60891. serializationObject.minScaleX = particleSystem.minScaleX;
  60892. serializationObject.maxScaleX = particleSystem.maxScaleX;
  60893. serializationObject.minScaleY = particleSystem.minScaleY;
  60894. serializationObject.maxScaleY = particleSystem.maxScaleY;
  60895. serializationObject.minEmitPower = particleSystem.minEmitPower;
  60896. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  60897. serializationObject.minLifeTime = particleSystem.minLifeTime;
  60898. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  60899. serializationObject.emitRate = particleSystem.emitRate;
  60900. serializationObject.gravity = particleSystem.gravity.asArray();
  60901. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  60902. serializationObject.color1 = particleSystem.color1.asArray();
  60903. serializationObject.color2 = particleSystem.color2.asArray();
  60904. serializationObject.colorDead = particleSystem.colorDead.asArray();
  60905. serializationObject.updateSpeed = particleSystem.updateSpeed;
  60906. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  60907. serializationObject.blendMode = particleSystem.blendMode;
  60908. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  60909. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  60910. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  60911. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  60912. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  60913. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  60914. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  60915. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  60916. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  60917. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  60918. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  60919. var colorGradients = particleSystem.getColorGradients();
  60920. if (colorGradients) {
  60921. serializationObject.colorGradients = [];
  60922. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  60923. var colorGradient = colorGradients_1[_i];
  60924. var serializedGradient = {
  60925. gradient: colorGradient.gradient,
  60926. color1: colorGradient.color1.asArray()
  60927. };
  60928. if (colorGradient.color2) {
  60929. serializedGradient.color2 = colorGradient.color2.asArray();
  60930. }
  60931. serializationObject.colorGradients.push(serializedGradient);
  60932. }
  60933. }
  60934. var rampGradients = particleSystem.getRampGradients();
  60935. if (rampGradients) {
  60936. serializationObject.rampGradients = [];
  60937. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  60938. var rampGradient = rampGradients_1[_a];
  60939. var serializedGradient = {
  60940. gradient: rampGradient.gradient,
  60941. color: rampGradient.color.asArray()
  60942. };
  60943. serializationObject.rampGradients.push(serializedGradient);
  60944. }
  60945. serializationObject.useRampGradients = particleSystem.useRampGradients;
  60946. }
  60947. var colorRemapGradients = particleSystem.getColorRemapGradients();
  60948. if (colorRemapGradients) {
  60949. serializationObject.colorRemapGradients = [];
  60950. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  60951. var colorRemapGradient = colorRemapGradients_1[_b];
  60952. var serializedGradient = {
  60953. gradient: colorRemapGradient.gradient,
  60954. factor1: colorRemapGradient.factor1
  60955. };
  60956. if (colorRemapGradient.factor2 !== undefined) {
  60957. serializedGradient.factor2 = colorRemapGradient.factor2;
  60958. }
  60959. serializationObject.colorRemapGradients.push(serializedGradient);
  60960. }
  60961. }
  60962. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  60963. if (alphaRemapGradients) {
  60964. serializationObject.alphaRemapGradients = [];
  60965. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  60966. var alphaRemapGradient = alphaRemapGradients_1[_c];
  60967. var serializedGradient = {
  60968. gradient: alphaRemapGradient.gradient,
  60969. factor1: alphaRemapGradient.factor1
  60970. };
  60971. if (alphaRemapGradient.factor2 !== undefined) {
  60972. serializedGradient.factor2 = alphaRemapGradient.factor2;
  60973. }
  60974. serializationObject.alphaRemapGradients.push(serializedGradient);
  60975. }
  60976. }
  60977. var sizeGradients = particleSystem.getSizeGradients();
  60978. if (sizeGradients) {
  60979. serializationObject.sizeGradients = [];
  60980. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  60981. var sizeGradient = sizeGradients_1[_d];
  60982. var serializedGradient = {
  60983. gradient: sizeGradient.gradient,
  60984. factor1: sizeGradient.factor1
  60985. };
  60986. if (sizeGradient.factor2 !== undefined) {
  60987. serializedGradient.factor2 = sizeGradient.factor2;
  60988. }
  60989. serializationObject.sizeGradients.push(serializedGradient);
  60990. }
  60991. }
  60992. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  60993. if (angularSpeedGradients) {
  60994. serializationObject.angularSpeedGradients = [];
  60995. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  60996. var angularSpeedGradient = angularSpeedGradients_1[_e];
  60997. var serializedGradient = {
  60998. gradient: angularSpeedGradient.gradient,
  60999. factor1: angularSpeedGradient.factor1
  61000. };
  61001. if (angularSpeedGradient.factor2 !== undefined) {
  61002. serializedGradient.factor2 = angularSpeedGradient.factor2;
  61003. }
  61004. serializationObject.angularSpeedGradients.push(serializedGradient);
  61005. }
  61006. }
  61007. var velocityGradients = particleSystem.getVelocityGradients();
  61008. if (velocityGradients) {
  61009. serializationObject.velocityGradients = [];
  61010. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  61011. var velocityGradient = velocityGradients_1[_f];
  61012. var serializedGradient = {
  61013. gradient: velocityGradient.gradient,
  61014. factor1: velocityGradient.factor1
  61015. };
  61016. if (velocityGradient.factor2 !== undefined) {
  61017. serializedGradient.factor2 = velocityGradient.factor2;
  61018. }
  61019. serializationObject.velocityGradients.push(serializedGradient);
  61020. }
  61021. }
  61022. var dragGradients = particleSystem.getDragGradients();
  61023. if (dragGradients) {
  61024. serializationObject.dragyGradients = [];
  61025. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  61026. var dragGradient = dragGradients_1[_g];
  61027. var serializedGradient = {
  61028. gradient: dragGradient.gradient,
  61029. factor1: dragGradient.factor1
  61030. };
  61031. if (dragGradient.factor2 !== undefined) {
  61032. serializedGradient.factor2 = dragGradient.factor2;
  61033. }
  61034. serializationObject.dragGradients.push(serializedGradient);
  61035. }
  61036. }
  61037. var emitRateGradients = particleSystem.getEmitRateGradients();
  61038. if (emitRateGradients) {
  61039. serializationObject.emitRateGradients = [];
  61040. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  61041. var emitRateGradient = emitRateGradients_1[_h];
  61042. var serializedGradient = {
  61043. gradient: emitRateGradient.gradient,
  61044. factor1: emitRateGradient.factor1
  61045. };
  61046. if (emitRateGradient.factor2 !== undefined) {
  61047. serializedGradient.factor2 = emitRateGradient.factor2;
  61048. }
  61049. serializationObject.emitRateGradients.push(serializedGradient);
  61050. }
  61051. }
  61052. var startSizeGradients = particleSystem.getStartSizeGradients();
  61053. if (startSizeGradients) {
  61054. serializationObject.startSizeGradients = [];
  61055. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  61056. var startSizeGradient = startSizeGradients_1[_j];
  61057. var serializedGradient = {
  61058. gradient: startSizeGradient.gradient,
  61059. factor1: startSizeGradient.factor1
  61060. };
  61061. if (startSizeGradient.factor2 !== undefined) {
  61062. serializedGradient.factor2 = startSizeGradient.factor2;
  61063. }
  61064. serializationObject.startSizeGradients.push(serializedGradient);
  61065. }
  61066. }
  61067. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  61068. if (lifeTimeGradients) {
  61069. serializationObject.lifeTimeGradients = [];
  61070. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  61071. var lifeTimeGradient = lifeTimeGradients_1[_k];
  61072. var serializedGradient = {
  61073. gradient: lifeTimeGradient.gradient,
  61074. factor1: lifeTimeGradient.factor1
  61075. };
  61076. if (lifeTimeGradient.factor2 !== undefined) {
  61077. serializedGradient.factor2 = lifeTimeGradient.factor2;
  61078. }
  61079. serializationObject.lifeTimeGradients.push(serializedGradient);
  61080. }
  61081. }
  61082. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  61083. if (limitVelocityGradients) {
  61084. serializationObject.limitVelocityGradients = [];
  61085. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  61086. var limitVelocityGradient = limitVelocityGradients_1[_l];
  61087. var serializedGradient = {
  61088. gradient: limitVelocityGradient.gradient,
  61089. factor1: limitVelocityGradient.factor1
  61090. };
  61091. if (limitVelocityGradient.factor2 !== undefined) {
  61092. serializedGradient.factor2 = limitVelocityGradient.factor2;
  61093. }
  61094. serializationObject.limitVelocityGradients.push(serializedGradient);
  61095. }
  61096. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  61097. }
  61098. if (particleSystem.noiseTexture) {
  61099. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  61100. }
  61101. };
  61102. /** @hidden */
  61103. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  61104. // Texture
  61105. if (parsedParticleSystem.textureName) {
  61106. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  61107. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  61108. }
  61109. // Emitter
  61110. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  61111. particleSystem.emitter = BABYLON.Vector3.Zero();
  61112. }
  61113. else if (parsedParticleSystem.emitterId) {
  61114. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  61115. }
  61116. else {
  61117. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  61118. }
  61119. // Misc.
  61120. if (parsedParticleSystem.renderingGroupId !== undefined) {
  61121. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  61122. }
  61123. if (parsedParticleSystem.isBillboardBased !== undefined) {
  61124. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  61125. }
  61126. if (parsedParticleSystem.billboardMode !== undefined) {
  61127. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  61128. }
  61129. // Animations
  61130. if (parsedParticleSystem.animations) {
  61131. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  61132. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  61133. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  61134. }
  61135. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  61136. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  61137. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  61138. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  61139. }
  61140. if (parsedParticleSystem.autoAnimate) {
  61141. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  61142. }
  61143. // Particle system
  61144. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  61145. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  61146. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  61147. particleSystem.minSize = parsedParticleSystem.minSize;
  61148. particleSystem.maxSize = parsedParticleSystem.maxSize;
  61149. if (parsedParticleSystem.minScaleX) {
  61150. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  61151. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  61152. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  61153. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  61154. }
  61155. if (parsedParticleSystem.preWarmCycles !== undefined) {
  61156. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  61157. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  61158. }
  61159. if (parsedParticleSystem.minInitialRotation !== undefined) {
  61160. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  61161. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  61162. }
  61163. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  61164. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  61165. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  61166. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  61167. particleSystem.emitRate = parsedParticleSystem.emitRate;
  61168. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  61169. if (parsedParticleSystem.noiseStrength) {
  61170. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  61171. }
  61172. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  61173. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  61174. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  61175. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  61176. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  61177. particleSystem.blendMode = parsedParticleSystem.blendMode;
  61178. if (parsedParticleSystem.colorGradients) {
  61179. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  61180. var colorGradient = _a[_i];
  61181. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  61182. }
  61183. }
  61184. if (parsedParticleSystem.rampGradients) {
  61185. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  61186. var rampGradient = _c[_b];
  61187. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  61188. }
  61189. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  61190. }
  61191. if (parsedParticleSystem.colorRemapGradients) {
  61192. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  61193. var colorRemapGradient = _e[_d];
  61194. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  61195. }
  61196. }
  61197. if (parsedParticleSystem.alphaRemapGradients) {
  61198. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  61199. var alphaRemapGradient = _g[_f];
  61200. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  61201. }
  61202. }
  61203. if (parsedParticleSystem.sizeGradients) {
  61204. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  61205. var sizeGradient = _j[_h];
  61206. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  61207. }
  61208. }
  61209. if (parsedParticleSystem.sizeGradients) {
  61210. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  61211. var sizeGradient = _l[_k];
  61212. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  61213. }
  61214. }
  61215. if (parsedParticleSystem.angularSpeedGradients) {
  61216. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  61217. var angularSpeedGradient = _o[_m];
  61218. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  61219. }
  61220. }
  61221. if (parsedParticleSystem.velocityGradients) {
  61222. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  61223. var velocityGradient = _q[_p];
  61224. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  61225. }
  61226. }
  61227. if (parsedParticleSystem.dragGradients) {
  61228. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  61229. var dragGradient = _s[_r];
  61230. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  61231. }
  61232. }
  61233. if (parsedParticleSystem.emitRateGradients) {
  61234. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  61235. var emitRateGradient = _u[_t];
  61236. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  61237. }
  61238. }
  61239. if (parsedParticleSystem.startSizeGradients) {
  61240. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  61241. var startSizeGradient = _w[_v];
  61242. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  61243. }
  61244. }
  61245. if (parsedParticleSystem.lifeTimeGradients) {
  61246. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  61247. var lifeTimeGradient = _y[_x];
  61248. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  61249. }
  61250. }
  61251. if (parsedParticleSystem.limitVelocityGradients) {
  61252. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  61253. var limitVelocityGradient = _0[_z];
  61254. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  61255. }
  61256. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  61257. }
  61258. if (parsedParticleSystem.noiseTexture) {
  61259. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  61260. }
  61261. // Emitter
  61262. var emitterType;
  61263. if (parsedParticleSystem.particleEmitterType) {
  61264. switch (parsedParticleSystem.particleEmitterType.type) {
  61265. case "SphereParticleEmitter":
  61266. emitterType = new BABYLON.SphereParticleEmitter();
  61267. break;
  61268. case "SphereDirectedParticleEmitter":
  61269. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  61270. break;
  61271. case "ConeEmitter":
  61272. case "ConeParticleEmitter":
  61273. emitterType = new BABYLON.ConeParticleEmitter();
  61274. break;
  61275. case "CylinderParticleEmitter":
  61276. emitterType = new BABYLON.CylinderParticleEmitter();
  61277. break;
  61278. case "HemisphericParticleEmitter":
  61279. emitterType = new BABYLON.HemisphericParticleEmitter();
  61280. break;
  61281. case "BoxEmitter":
  61282. case "BoxParticleEmitter":
  61283. default:
  61284. emitterType = new BABYLON.BoxParticleEmitter();
  61285. break;
  61286. }
  61287. emitterType.parse(parsedParticleSystem.particleEmitterType);
  61288. }
  61289. else {
  61290. emitterType = new BABYLON.BoxParticleEmitter();
  61291. emitterType.parse(parsedParticleSystem);
  61292. }
  61293. particleSystem.particleEmitterType = emitterType;
  61294. // Animation sheet
  61295. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  61296. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  61297. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  61298. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  61299. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  61300. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  61301. };
  61302. /**
  61303. * Parses a JSON object to create a particle system.
  61304. * @param parsedParticleSystem The JSON object to parse
  61305. * @param scene The scene to create the particle system in
  61306. * @param rootUrl The root url to use to load external dependencies like texture
  61307. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  61308. * @returns the Parsed particle system
  61309. */
  61310. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  61311. if (doNotStart === void 0) { doNotStart = false; }
  61312. var name = parsedParticleSystem.name;
  61313. var custom = null;
  61314. var program = null;
  61315. if (parsedParticleSystem.customShader) {
  61316. program = parsedParticleSystem.customShader;
  61317. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  61318. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  61319. }
  61320. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  61321. particleSystem.customShader = program;
  61322. if (parsedParticleSystem.id) {
  61323. particleSystem.id = parsedParticleSystem.id;
  61324. }
  61325. // SubEmitters
  61326. if (parsedParticleSystem.subEmitters) {
  61327. particleSystem.subEmitters = [];
  61328. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  61329. var cell = _a[_i];
  61330. var cellArray = [];
  61331. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  61332. var sub = cell_1[_b];
  61333. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  61334. }
  61335. particleSystem.subEmitters.push(cellArray);
  61336. }
  61337. }
  61338. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  61339. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  61340. // Auto start
  61341. if (parsedParticleSystem.preventAutoStart) {
  61342. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  61343. }
  61344. if (!doNotStart && !particleSystem.preventAutoStart) {
  61345. particleSystem.start();
  61346. }
  61347. return particleSystem;
  61348. };
  61349. /**
  61350. * Billboard mode will only apply to Y axis
  61351. */
  61352. ParticleSystem.BILLBOARDMODE_Y = 2;
  61353. /**
  61354. * Billboard mode will apply to all axes
  61355. */
  61356. ParticleSystem.BILLBOARDMODE_ALL = 7;
  61357. /**
  61358. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  61359. */
  61360. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  61361. return ParticleSystem;
  61362. }(BABYLON.BaseParticleSystem));
  61363. BABYLON.ParticleSystem = ParticleSystem;
  61364. })(BABYLON || (BABYLON = {}));
  61365. //# sourceMappingURL=babylon.particleSystem.js.map
  61366. var BABYLON;
  61367. (function (BABYLON) {
  61368. /**
  61369. * Particle emitter emitting particles from the inside of a box.
  61370. * It emits the particles randomly between 2 given directions.
  61371. */
  61372. var BoxParticleEmitter = /** @class */ (function () {
  61373. /**
  61374. * Creates a new instance BoxParticleEmitter
  61375. */
  61376. function BoxParticleEmitter() {
  61377. /**
  61378. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61379. */
  61380. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  61381. /**
  61382. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61383. */
  61384. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  61385. /**
  61386. * 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.
  61387. */
  61388. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  61389. /**
  61390. * 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.
  61391. */
  61392. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  61393. }
  61394. /**
  61395. * Called by the particle System when the direction is computed for the created particle.
  61396. * @param worldMatrix is the world matrix of the particle system
  61397. * @param directionToUpdate is the direction vector to update with the result
  61398. * @param particle is the particle we are computed the direction for
  61399. */
  61400. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61401. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61402. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61403. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61404. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61405. };
  61406. /**
  61407. * Called by the particle System when the position is computed for the created particle.
  61408. * @param worldMatrix is the world matrix of the particle system
  61409. * @param positionToUpdate is the position vector to update with the result
  61410. * @param particle is the particle we are computed the position for
  61411. */
  61412. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61413. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  61414. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  61415. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  61416. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61417. };
  61418. /**
  61419. * Clones the current emitter and returns a copy of it
  61420. * @returns the new emitter
  61421. */
  61422. BoxParticleEmitter.prototype.clone = function () {
  61423. var newOne = new BoxParticleEmitter();
  61424. BABYLON.Tools.DeepCopy(this, newOne);
  61425. return newOne;
  61426. };
  61427. /**
  61428. * Called by the GPUParticleSystem to setup the update shader
  61429. * @param effect defines the update shader
  61430. */
  61431. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  61432. effect.setVector3("direction1", this.direction1);
  61433. effect.setVector3("direction2", this.direction2);
  61434. effect.setVector3("minEmitBox", this.minEmitBox);
  61435. effect.setVector3("maxEmitBox", this.maxEmitBox);
  61436. };
  61437. /**
  61438. * Returns a string to use to update the GPU particles update shader
  61439. * @returns a string containng the defines string
  61440. */
  61441. BoxParticleEmitter.prototype.getEffectDefines = function () {
  61442. return "#define BOXEMITTER";
  61443. };
  61444. /**
  61445. * Returns the string "BoxParticleEmitter"
  61446. * @returns a string containing the class name
  61447. */
  61448. BoxParticleEmitter.prototype.getClassName = function () {
  61449. return "BoxParticleEmitter";
  61450. };
  61451. /**
  61452. * Serializes the particle system to a JSON object.
  61453. * @returns the JSON object
  61454. */
  61455. BoxParticleEmitter.prototype.serialize = function () {
  61456. var serializationObject = {};
  61457. serializationObject.type = this.getClassName();
  61458. serializationObject.direction1 = this.direction1.asArray();
  61459. serializationObject.direction2 = this.direction2.asArray();
  61460. serializationObject.minEmitBox = this.minEmitBox.asArray();
  61461. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  61462. return serializationObject;
  61463. };
  61464. /**
  61465. * Parse properties from a JSON object
  61466. * @param serializationObject defines the JSON object
  61467. */
  61468. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  61469. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  61470. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  61471. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  61472. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  61473. };
  61474. return BoxParticleEmitter;
  61475. }());
  61476. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  61477. })(BABYLON || (BABYLON = {}));
  61478. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  61479. var BABYLON;
  61480. (function (BABYLON) {
  61481. /**
  61482. * Particle emitter emitting particles from the inside of a cylinder.
  61483. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  61484. */
  61485. var CylinderParticleEmitter = /** @class */ (function () {
  61486. /**
  61487. * Creates a new instance CylinderParticleEmitter
  61488. * @param radius the radius of the emission cylinder (1 by default)
  61489. * @param height the height of the emission cylinder (1 by default)
  61490. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61491. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61492. */
  61493. function CylinderParticleEmitter(
  61494. /**
  61495. * The radius of the emission cylinder.
  61496. */
  61497. radius,
  61498. /**
  61499. * The height of the emission cylinder.
  61500. */
  61501. height,
  61502. /**
  61503. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61504. */
  61505. radiusRange,
  61506. /**
  61507. * How much to randomize the particle direction [0-1].
  61508. */
  61509. directionRandomizer) {
  61510. if (radius === void 0) { radius = 1; }
  61511. if (height === void 0) { height = 1; }
  61512. if (radiusRange === void 0) { radiusRange = 1; }
  61513. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61514. this.radius = radius;
  61515. this.height = height;
  61516. this.radiusRange = radiusRange;
  61517. this.directionRandomizer = directionRandomizer;
  61518. }
  61519. /**
  61520. * Called by the particle System when the direction is computed for the created particle.
  61521. * @param worldMatrix is the world matrix of the particle system
  61522. * @param directionToUpdate is the direction vector to update with the result
  61523. * @param particle is the particle we are computed the direction for
  61524. */
  61525. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61526. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61527. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  61528. var angle = Math.atan2(direction.x, direction.z);
  61529. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  61530. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  61531. direction.x = Math.sin(angle);
  61532. direction.z = Math.cos(angle);
  61533. direction.normalize();
  61534. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61535. };
  61536. /**
  61537. * Called by the particle System when the position is computed for the created particle.
  61538. * @param worldMatrix is the world matrix of the particle system
  61539. * @param positionToUpdate is the position vector to update with the result
  61540. * @param particle is the particle we are computed the position for
  61541. */
  61542. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61543. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  61544. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61545. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  61546. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  61547. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  61548. var xPos = positionRadius * Math.cos(angle);
  61549. var zPos = positionRadius * Math.sin(angle);
  61550. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  61551. };
  61552. /**
  61553. * Clones the current emitter and returns a copy of it
  61554. * @returns the new emitter
  61555. */
  61556. CylinderParticleEmitter.prototype.clone = function () {
  61557. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  61558. BABYLON.Tools.DeepCopy(this, newOne);
  61559. return newOne;
  61560. };
  61561. /**
  61562. * Called by the GPUParticleSystem to setup the update shader
  61563. * @param effect defines the update shader
  61564. */
  61565. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  61566. effect.setFloat("radius", this.radius);
  61567. effect.setFloat("height", this.height);
  61568. effect.setFloat("radiusRange", this.radiusRange);
  61569. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61570. };
  61571. /**
  61572. * Returns a string to use to update the GPU particles update shader
  61573. * @returns a string containng the defines string
  61574. */
  61575. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  61576. return "#define CYLINDEREMITTER";
  61577. };
  61578. /**
  61579. * Returns the string "CylinderParticleEmitter"
  61580. * @returns a string containing the class name
  61581. */
  61582. CylinderParticleEmitter.prototype.getClassName = function () {
  61583. return "CylinderParticleEmitter";
  61584. };
  61585. /**
  61586. * Serializes the particle system to a JSON object.
  61587. * @returns the JSON object
  61588. */
  61589. CylinderParticleEmitter.prototype.serialize = function () {
  61590. var serializationObject = {};
  61591. serializationObject.type = this.getClassName();
  61592. serializationObject.radius = this.radius;
  61593. serializationObject.height = this.height;
  61594. serializationObject.radiusRange = this.radiusRange;
  61595. serializationObject.directionRandomizer = this.directionRandomizer;
  61596. return serializationObject;
  61597. };
  61598. /**
  61599. * Parse properties from a JSON object
  61600. * @param serializationObject defines the JSON object
  61601. */
  61602. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  61603. this.radius = serializationObject.radius;
  61604. this.height = serializationObject.height;
  61605. this.radiusRange = serializationObject.radiusRange;
  61606. this.directionRandomizer = serializationObject.directionRandomizer;
  61607. };
  61608. return CylinderParticleEmitter;
  61609. }());
  61610. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  61611. /**
  61612. * Particle emitter emitting particles from the inside of a cylinder.
  61613. * It emits the particles randomly between two vectors.
  61614. */
  61615. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  61616. __extends(CylinderDirectedParticleEmitter, _super);
  61617. /**
  61618. * Creates a new instance CylinderDirectedParticleEmitter
  61619. * @param radius the radius of the emission cylinder (1 by default)
  61620. * @param height the height of the emission cylinder (1 by default)
  61621. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61622. * @param direction1 the min limit of the emission direction (up vector by default)
  61623. * @param direction2 the max limit of the emission direction (up vector by default)
  61624. */
  61625. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  61626. /**
  61627. * The min limit of the emission direction.
  61628. */
  61629. direction1,
  61630. /**
  61631. * The max limit of the emission direction.
  61632. */
  61633. direction2) {
  61634. if (radius === void 0) { radius = 1; }
  61635. if (height === void 0) { height = 1; }
  61636. if (radiusRange === void 0) { radiusRange = 1; }
  61637. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  61638. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  61639. var _this = _super.call(this, radius, height, radiusRange) || this;
  61640. _this.direction1 = direction1;
  61641. _this.direction2 = direction2;
  61642. return _this;
  61643. }
  61644. /**
  61645. * Called by the particle System when the direction is computed for the created particle.
  61646. * @param worldMatrix is the world matrix of the particle system
  61647. * @param directionToUpdate is the direction vector to update with the result
  61648. * @param particle is the particle we are computed the direction for
  61649. */
  61650. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61651. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61652. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61653. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61654. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61655. };
  61656. /**
  61657. * Clones the current emitter and returns a copy of it
  61658. * @returns the new emitter
  61659. */
  61660. CylinderDirectedParticleEmitter.prototype.clone = function () {
  61661. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  61662. BABYLON.Tools.DeepCopy(this, newOne);
  61663. return newOne;
  61664. };
  61665. /**
  61666. * Called by the GPUParticleSystem to setup the update shader
  61667. * @param effect defines the update shader
  61668. */
  61669. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  61670. effect.setFloat("radius", this.radius);
  61671. effect.setFloat("height", this.height);
  61672. effect.setFloat("radiusRange", this.radiusRange);
  61673. effect.setVector3("direction1", this.direction1);
  61674. effect.setVector3("direction2", this.direction2);
  61675. };
  61676. /**
  61677. * Returns a string to use to update the GPU particles update shader
  61678. * @returns a string containng the defines string
  61679. */
  61680. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  61681. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  61682. };
  61683. /**
  61684. * Returns the string "CylinderDirectedParticleEmitter"
  61685. * @returns a string containing the class name
  61686. */
  61687. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  61688. return "CylinderDirectedParticleEmitter";
  61689. };
  61690. /**
  61691. * Serializes the particle system to a JSON object.
  61692. * @returns the JSON object
  61693. */
  61694. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  61695. var serializationObject = _super.prototype.serialize.call(this);
  61696. serializationObject.direction1 = this.direction1.asArray();
  61697. serializationObject.direction2 = this.direction2.asArray();
  61698. return serializationObject;
  61699. };
  61700. /**
  61701. * Parse properties from a JSON object
  61702. * @param serializationObject defines the JSON object
  61703. */
  61704. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  61705. _super.prototype.parse.call(this, serializationObject);
  61706. this.direction1.copyFrom(serializationObject.direction1);
  61707. this.direction2.copyFrom(serializationObject.direction2);
  61708. };
  61709. return CylinderDirectedParticleEmitter;
  61710. }(CylinderParticleEmitter));
  61711. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  61712. })(BABYLON || (BABYLON = {}));
  61713. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  61714. var BABYLON;
  61715. (function (BABYLON) {
  61716. /**
  61717. * Particle emitter emitting particles from the inside of a cone.
  61718. * It emits the particles alongside the cone volume from the base to the particle.
  61719. * The emission direction might be randomized.
  61720. */
  61721. var ConeParticleEmitter = /** @class */ (function () {
  61722. /**
  61723. * Creates a new instance ConeParticleEmitter
  61724. * @param radius the radius of the emission cone (1 by default)
  61725. * @param angles the cone base angle (PI by default)
  61726. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  61727. */
  61728. function ConeParticleEmitter(radius, angle,
  61729. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  61730. directionRandomizer) {
  61731. if (radius === void 0) { radius = 1; }
  61732. if (angle === void 0) { angle = Math.PI; }
  61733. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61734. this.directionRandomizer = directionRandomizer;
  61735. /**
  61736. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  61737. */
  61738. this.radiusRange = 1;
  61739. /**
  61740. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  61741. */
  61742. this.heightRange = 1;
  61743. /**
  61744. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  61745. */
  61746. this.emitFromSpawnPointOnly = false;
  61747. this.angle = angle;
  61748. this.radius = radius;
  61749. }
  61750. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  61751. /**
  61752. * Gets or sets the radius of the emission cone
  61753. */
  61754. get: function () {
  61755. return this._radius;
  61756. },
  61757. set: function (value) {
  61758. this._radius = value;
  61759. this._buildHeight();
  61760. },
  61761. enumerable: true,
  61762. configurable: true
  61763. });
  61764. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  61765. /**
  61766. * Gets or sets the angle of the emission cone
  61767. */
  61768. get: function () {
  61769. return this._angle;
  61770. },
  61771. set: function (value) {
  61772. this._angle = value;
  61773. this._buildHeight();
  61774. },
  61775. enumerable: true,
  61776. configurable: true
  61777. });
  61778. ConeParticleEmitter.prototype._buildHeight = function () {
  61779. if (this._angle !== 0) {
  61780. this._height = this._radius / Math.tan(this._angle / 2);
  61781. }
  61782. else {
  61783. this._height = 1;
  61784. }
  61785. };
  61786. /**
  61787. * Called by the particle System when the direction is computed for the created particle.
  61788. * @param worldMatrix is the world matrix of the particle system
  61789. * @param directionToUpdate is the direction vector to update with the result
  61790. * @param particle is the particle we are computed the direction for
  61791. */
  61792. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61793. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  61794. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  61795. }
  61796. else {
  61797. // measure the direction Vector from the emitter to the particle.
  61798. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61799. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61800. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61801. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61802. direction.x += randX;
  61803. direction.y += randY;
  61804. direction.z += randZ;
  61805. direction.normalize();
  61806. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61807. }
  61808. };
  61809. /**
  61810. * Called by the particle System when the position is computed for the created particle.
  61811. * @param worldMatrix is the world matrix of the particle system
  61812. * @param positionToUpdate is the position vector to update with the result
  61813. * @param particle is the particle we are computed the position for
  61814. */
  61815. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61816. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  61817. var h;
  61818. if (!this.emitFromSpawnPointOnly) {
  61819. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  61820. // Better distribution in a cone at normal angles.
  61821. h = 1 - h * h;
  61822. }
  61823. else {
  61824. h = 0.0001;
  61825. }
  61826. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  61827. radius = radius * h;
  61828. var randX = radius * Math.sin(s);
  61829. var randZ = radius * Math.cos(s);
  61830. var randY = h * this._height;
  61831. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61832. };
  61833. /**
  61834. * Clones the current emitter and returns a copy of it
  61835. * @returns the new emitter
  61836. */
  61837. ConeParticleEmitter.prototype.clone = function () {
  61838. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  61839. BABYLON.Tools.DeepCopy(this, newOne);
  61840. return newOne;
  61841. };
  61842. /**
  61843. * Called by the GPUParticleSystem to setup the update shader
  61844. * @param effect defines the update shader
  61845. */
  61846. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  61847. effect.setFloat2("radius", this._radius, this.radiusRange);
  61848. effect.setFloat("coneAngle", this._angle);
  61849. effect.setFloat2("height", this._height, this.heightRange);
  61850. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61851. };
  61852. /**
  61853. * Returns a string to use to update the GPU particles update shader
  61854. * @returns a string containng the defines string
  61855. */
  61856. ConeParticleEmitter.prototype.getEffectDefines = function () {
  61857. var defines = "#define CONEEMITTER";
  61858. if (this.emitFromSpawnPointOnly) {
  61859. defines += "\n#define CONEEMITTERSPAWNPOINT";
  61860. }
  61861. return defines;
  61862. };
  61863. /**
  61864. * Returns the string "ConeParticleEmitter"
  61865. * @returns a string containing the class name
  61866. */
  61867. ConeParticleEmitter.prototype.getClassName = function () {
  61868. return "ConeParticleEmitter";
  61869. };
  61870. /**
  61871. * Serializes the particle system to a JSON object.
  61872. * @returns the JSON object
  61873. */
  61874. ConeParticleEmitter.prototype.serialize = function () {
  61875. var serializationObject = {};
  61876. serializationObject.type = this.getClassName();
  61877. serializationObject.radius = this._radius;
  61878. serializationObject.angle = this._angle;
  61879. serializationObject.directionRandomizer = this.directionRandomizer;
  61880. return serializationObject;
  61881. };
  61882. /**
  61883. * Parse properties from a JSON object
  61884. * @param serializationObject defines the JSON object
  61885. */
  61886. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  61887. this.radius = serializationObject.radius;
  61888. this.angle = serializationObject.angle;
  61889. this.directionRandomizer = serializationObject.directionRandomizer;
  61890. };
  61891. return ConeParticleEmitter;
  61892. }());
  61893. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  61894. })(BABYLON || (BABYLON = {}));
  61895. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  61896. var BABYLON;
  61897. (function (BABYLON) {
  61898. /**
  61899. * Particle emitter emitting particles from the inside of a sphere.
  61900. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  61901. */
  61902. var SphereParticleEmitter = /** @class */ (function () {
  61903. /**
  61904. * Creates a new instance SphereParticleEmitter
  61905. * @param radius the radius of the emission sphere (1 by default)
  61906. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61907. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61908. */
  61909. function SphereParticleEmitter(
  61910. /**
  61911. * The radius of the emission sphere.
  61912. */
  61913. radius,
  61914. /**
  61915. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61916. */
  61917. radiusRange,
  61918. /**
  61919. * How much to randomize the particle direction [0-1].
  61920. */
  61921. directionRandomizer) {
  61922. if (radius === void 0) { radius = 1; }
  61923. if (radiusRange === void 0) { radiusRange = 1; }
  61924. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61925. this.radius = radius;
  61926. this.radiusRange = radiusRange;
  61927. this.directionRandomizer = directionRandomizer;
  61928. }
  61929. /**
  61930. * Called by the particle System when the direction is computed for the created particle.
  61931. * @param worldMatrix is the world matrix of the particle system
  61932. * @param directionToUpdate is the direction vector to update with the result
  61933. * @param particle is the particle we are computed the direction for
  61934. */
  61935. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61936. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61937. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61938. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61939. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61940. direction.x += randX;
  61941. direction.y += randY;
  61942. direction.z += randZ;
  61943. direction.normalize();
  61944. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61945. };
  61946. /**
  61947. * Called by the particle System when the position is computed for the created particle.
  61948. * @param worldMatrix is the world matrix of the particle system
  61949. * @param positionToUpdate is the position vector to update with the result
  61950. * @param particle is the particle we are computed the position for
  61951. */
  61952. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61953. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  61954. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  61955. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61956. var theta = Math.acos(2 * v - 1);
  61957. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  61958. var randY = randRadius * Math.cos(theta);
  61959. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  61960. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61961. };
  61962. /**
  61963. * Clones the current emitter and returns a copy of it
  61964. * @returns the new emitter
  61965. */
  61966. SphereParticleEmitter.prototype.clone = function () {
  61967. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  61968. BABYLON.Tools.DeepCopy(this, newOne);
  61969. return newOne;
  61970. };
  61971. /**
  61972. * Called by the GPUParticleSystem to setup the update shader
  61973. * @param effect defines the update shader
  61974. */
  61975. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  61976. effect.setFloat("radius", this.radius);
  61977. effect.setFloat("radiusRange", this.radiusRange);
  61978. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61979. };
  61980. /**
  61981. * Returns a string to use to update the GPU particles update shader
  61982. * @returns a string containng the defines string
  61983. */
  61984. SphereParticleEmitter.prototype.getEffectDefines = function () {
  61985. return "#define SPHEREEMITTER";
  61986. };
  61987. /**
  61988. * Returns the string "SphereParticleEmitter"
  61989. * @returns a string containing the class name
  61990. */
  61991. SphereParticleEmitter.prototype.getClassName = function () {
  61992. return "SphereParticleEmitter";
  61993. };
  61994. /**
  61995. * Serializes the particle system to a JSON object.
  61996. * @returns the JSON object
  61997. */
  61998. SphereParticleEmitter.prototype.serialize = function () {
  61999. var serializationObject = {};
  62000. serializationObject.type = this.getClassName();
  62001. serializationObject.radius = this.radius;
  62002. serializationObject.radiusRange = this.radiusRange;
  62003. serializationObject.directionRandomizer = this.directionRandomizer;
  62004. return serializationObject;
  62005. };
  62006. /**
  62007. * Parse properties from a JSON object
  62008. * @param serializationObject defines the JSON object
  62009. */
  62010. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  62011. this.radius = serializationObject.radius;
  62012. this.radiusRange = serializationObject.radiusRange;
  62013. this.directionRandomizer = serializationObject.directionRandomizer;
  62014. };
  62015. return SphereParticleEmitter;
  62016. }());
  62017. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  62018. /**
  62019. * Particle emitter emitting particles from the inside of a sphere.
  62020. * It emits the particles randomly between two vectors.
  62021. */
  62022. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  62023. __extends(SphereDirectedParticleEmitter, _super);
  62024. /**
  62025. * Creates a new instance SphereDirectedParticleEmitter
  62026. * @param radius the radius of the emission sphere (1 by default)
  62027. * @param direction1 the min limit of the emission direction (up vector by default)
  62028. * @param direction2 the max limit of the emission direction (up vector by default)
  62029. */
  62030. function SphereDirectedParticleEmitter(radius,
  62031. /**
  62032. * The min limit of the emission direction.
  62033. */
  62034. direction1,
  62035. /**
  62036. * The max limit of the emission direction.
  62037. */
  62038. direction2) {
  62039. if (radius === void 0) { radius = 1; }
  62040. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  62041. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  62042. var _this = _super.call(this, radius) || this;
  62043. _this.direction1 = direction1;
  62044. _this.direction2 = direction2;
  62045. return _this;
  62046. }
  62047. /**
  62048. * Called by the particle System when the direction is computed for the created particle.
  62049. * @param worldMatrix is the world matrix of the particle system
  62050. * @param directionToUpdate is the direction vector to update with the result
  62051. * @param particle is the particle we are computed the direction for
  62052. */
  62053. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62054. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  62055. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  62056. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  62057. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  62058. };
  62059. /**
  62060. * Clones the current emitter and returns a copy of it
  62061. * @returns the new emitter
  62062. */
  62063. SphereDirectedParticleEmitter.prototype.clone = function () {
  62064. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  62065. BABYLON.Tools.DeepCopy(this, newOne);
  62066. return newOne;
  62067. };
  62068. /**
  62069. * Called by the GPUParticleSystem to setup the update shader
  62070. * @param effect defines the update shader
  62071. */
  62072. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  62073. effect.setFloat("radius", this.radius);
  62074. effect.setFloat("radiusRange", this.radiusRange);
  62075. effect.setVector3("direction1", this.direction1);
  62076. effect.setVector3("direction2", this.direction2);
  62077. };
  62078. /**
  62079. * Returns a string to use to update the GPU particles update shader
  62080. * @returns a string containng the defines string
  62081. */
  62082. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  62083. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  62084. };
  62085. /**
  62086. * Returns the string "SphereDirectedParticleEmitter"
  62087. * @returns a string containing the class name
  62088. */
  62089. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  62090. return "SphereDirectedParticleEmitter";
  62091. };
  62092. /**
  62093. * Serializes the particle system to a JSON object.
  62094. * @returns the JSON object
  62095. */
  62096. SphereDirectedParticleEmitter.prototype.serialize = function () {
  62097. var serializationObject = _super.prototype.serialize.call(this);
  62098. serializationObject.direction1 = this.direction1.asArray();
  62099. serializationObject.direction2 = this.direction2.asArray();
  62100. return serializationObject;
  62101. };
  62102. /**
  62103. * Parse properties from a JSON object
  62104. * @param serializationObject defines the JSON object
  62105. */
  62106. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  62107. _super.prototype.parse.call(this, serializationObject);
  62108. this.direction1.copyFrom(serializationObject.direction1);
  62109. this.direction2.copyFrom(serializationObject.direction2);
  62110. };
  62111. return SphereDirectedParticleEmitter;
  62112. }(SphereParticleEmitter));
  62113. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  62114. })(BABYLON || (BABYLON = {}));
  62115. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  62116. var BABYLON;
  62117. (function (BABYLON) {
  62118. /**
  62119. * Particle emitter emitting particles from the inside of a hemisphere.
  62120. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  62121. */
  62122. var HemisphericParticleEmitter = /** @class */ (function () {
  62123. /**
  62124. * Creates a new instance HemisphericParticleEmitter
  62125. * @param radius the radius of the emission hemisphere (1 by default)
  62126. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  62127. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  62128. */
  62129. function HemisphericParticleEmitter(
  62130. /**
  62131. * The radius of the emission hemisphere.
  62132. */
  62133. radius,
  62134. /**
  62135. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  62136. */
  62137. radiusRange,
  62138. /**
  62139. * How much to randomize the particle direction [0-1].
  62140. */
  62141. directionRandomizer) {
  62142. if (radius === void 0) { radius = 1; }
  62143. if (radiusRange === void 0) { radiusRange = 1; }
  62144. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  62145. this.radius = radius;
  62146. this.radiusRange = radiusRange;
  62147. this.directionRandomizer = directionRandomizer;
  62148. }
  62149. /**
  62150. * Called by the particle System when the direction is computed for the created particle.
  62151. * @param worldMatrix is the world matrix of the particle system
  62152. * @param directionToUpdate is the direction vector to update with the result
  62153. * @param particle is the particle we are computed the direction for
  62154. */
  62155. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62156. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  62157. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  62158. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  62159. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  62160. direction.x += randX;
  62161. direction.y += randY;
  62162. direction.z += randZ;
  62163. direction.normalize();
  62164. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  62165. };
  62166. /**
  62167. * Called by the particle System when the position is computed for the created particle.
  62168. * @param worldMatrix is the world matrix of the particle system
  62169. * @param positionToUpdate is the position vector to update with the result
  62170. * @param particle is the particle we are computed the position for
  62171. */
  62172. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  62173. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  62174. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  62175. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  62176. var theta = Math.acos(2 * v - 1);
  62177. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  62178. var randY = randRadius * Math.cos(theta);
  62179. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  62180. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  62181. };
  62182. /**
  62183. * Clones the current emitter and returns a copy of it
  62184. * @returns the new emitter
  62185. */
  62186. HemisphericParticleEmitter.prototype.clone = function () {
  62187. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  62188. BABYLON.Tools.DeepCopy(this, newOne);
  62189. return newOne;
  62190. };
  62191. /**
  62192. * Called by the GPUParticleSystem to setup the update shader
  62193. * @param effect defines the update shader
  62194. */
  62195. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  62196. effect.setFloat("radius", this.radius);
  62197. effect.setFloat("radiusRange", this.radiusRange);
  62198. effect.setFloat("directionRandomizer", this.directionRandomizer);
  62199. };
  62200. /**
  62201. * Returns a string to use to update the GPU particles update shader
  62202. * @returns a string containng the defines string
  62203. */
  62204. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  62205. return "#define HEMISPHERICEMITTER";
  62206. };
  62207. /**
  62208. * Returns the string "HemisphericParticleEmitter"
  62209. * @returns a string containing the class name
  62210. */
  62211. HemisphericParticleEmitter.prototype.getClassName = function () {
  62212. return "HemisphericParticleEmitter";
  62213. };
  62214. /**
  62215. * Serializes the particle system to a JSON object.
  62216. * @returns the JSON object
  62217. */
  62218. HemisphericParticleEmitter.prototype.serialize = function () {
  62219. var serializationObject = {};
  62220. serializationObject.type = this.getClassName();
  62221. serializationObject.radius = this.radius;
  62222. serializationObject.radiusRange = this.radiusRange;
  62223. serializationObject.directionRandomizer = this.directionRandomizer;
  62224. return serializationObject;
  62225. };
  62226. /**
  62227. * Parse properties from a JSON object
  62228. * @param serializationObject defines the JSON object
  62229. */
  62230. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  62231. this.radius = serializationObject.radius;
  62232. this.radiusRange = serializationObject.radiusRange;
  62233. this.directionRandomizer = serializationObject.directionRandomizer;
  62234. };
  62235. return HemisphericParticleEmitter;
  62236. }());
  62237. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  62238. })(BABYLON || (BABYLON = {}));
  62239. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  62240. var BABYLON;
  62241. (function (BABYLON) {
  62242. /**
  62243. * Particle emitter emitting particles from a point.
  62244. * It emits the particles randomly between 2 given directions.
  62245. */
  62246. var PointParticleEmitter = /** @class */ (function () {
  62247. /**
  62248. * Creates a new instance PointParticleEmitter
  62249. */
  62250. function PointParticleEmitter() {
  62251. /**
  62252. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  62253. */
  62254. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  62255. /**
  62256. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  62257. */
  62258. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  62259. }
  62260. /**
  62261. * Called by the particle System when the direction is computed for the created particle.
  62262. * @param worldMatrix is the world matrix of the particle system
  62263. * @param directionToUpdate is the direction vector to update with the result
  62264. * @param particle is the particle we are computed the direction for
  62265. */
  62266. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62267. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  62268. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  62269. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  62270. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  62271. };
  62272. /**
  62273. * Called by the particle System when the position is computed for the created particle.
  62274. * @param worldMatrix is the world matrix of the particle system
  62275. * @param positionToUpdate is the position vector to update with the result
  62276. * @param particle is the particle we are computed the position for
  62277. */
  62278. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  62279. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  62280. };
  62281. /**
  62282. * Clones the current emitter and returns a copy of it
  62283. * @returns the new emitter
  62284. */
  62285. PointParticleEmitter.prototype.clone = function () {
  62286. var newOne = new PointParticleEmitter();
  62287. BABYLON.Tools.DeepCopy(this, newOne);
  62288. return newOne;
  62289. };
  62290. /**
  62291. * Called by the GPUParticleSystem to setup the update shader
  62292. * @param effect defines the update shader
  62293. */
  62294. PointParticleEmitter.prototype.applyToShader = function (effect) {
  62295. effect.setVector3("direction1", this.direction1);
  62296. effect.setVector3("direction2", this.direction2);
  62297. };
  62298. /**
  62299. * Returns a string to use to update the GPU particles update shader
  62300. * @returns a string containng the defines string
  62301. */
  62302. PointParticleEmitter.prototype.getEffectDefines = function () {
  62303. return "#define POINTEMITTER";
  62304. };
  62305. /**
  62306. * Returns the string "PointParticleEmitter"
  62307. * @returns a string containing the class name
  62308. */
  62309. PointParticleEmitter.prototype.getClassName = function () {
  62310. return "PointParticleEmitter";
  62311. };
  62312. /**
  62313. * Serializes the particle system to a JSON object.
  62314. * @returns the JSON object
  62315. */
  62316. PointParticleEmitter.prototype.serialize = function () {
  62317. var serializationObject = {};
  62318. serializationObject.type = this.getClassName();
  62319. serializationObject.direction1 = this.direction1.asArray();
  62320. serializationObject.direction2 = this.direction2.asArray();
  62321. return serializationObject;
  62322. };
  62323. /**
  62324. * Parse properties from a JSON object
  62325. * @param serializationObject defines the JSON object
  62326. */
  62327. PointParticleEmitter.prototype.parse = function (serializationObject) {
  62328. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  62329. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  62330. };
  62331. return PointParticleEmitter;
  62332. }());
  62333. BABYLON.PointParticleEmitter = PointParticleEmitter;
  62334. })(BABYLON || (BABYLON = {}));
  62335. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  62336. var BABYLON;
  62337. (function (BABYLON) {
  62338. // Adds the parsers to the scene parsers.
  62339. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  62340. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  62341. if (!individualParser) {
  62342. return;
  62343. }
  62344. // Particles Systems
  62345. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62346. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62347. var parsedParticleSystem = parsedData.particleSystems[index];
  62348. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  62349. }
  62350. }
  62351. });
  62352. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  62353. if (parsedParticleSystem.activeParticleCount) {
  62354. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62355. return ps;
  62356. }
  62357. else {
  62358. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62359. return ps;
  62360. }
  62361. });
  62362. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  62363. if (uniformsNames === void 0) { uniformsNames = []; }
  62364. if (samplers === void 0) { samplers = []; }
  62365. if (defines === void 0) { defines = ""; }
  62366. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  62367. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  62368. if (defines.indexOf(" BILLBOARD") === -1) {
  62369. defines += "\n#define BILLBOARD\n";
  62370. }
  62371. if (samplers.indexOf("diffuseSampler") === -1) {
  62372. samplers.push("diffuseSampler");
  62373. }
  62374. return this.createEffect({
  62375. vertex: "particles",
  62376. fragmentElement: fragmentName
  62377. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  62378. };
  62379. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  62380. var results = new Array();
  62381. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  62382. var particleSystem = this.getScene().particleSystems[index];
  62383. if (particleSystem.emitter === this) {
  62384. results.push(particleSystem);
  62385. }
  62386. }
  62387. return results;
  62388. };
  62389. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  62390. var results = new Array();
  62391. var descendants = this.getDescendants();
  62392. descendants.push(this);
  62393. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  62394. var particleSystem = this.getScene().particleSystems[index];
  62395. var emitter = particleSystem.emitter;
  62396. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  62397. results.push(particleSystem);
  62398. }
  62399. }
  62400. return results;
  62401. };
  62402. })(BABYLON || (BABYLON = {}));
  62403. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  62404. var BABYLON;
  62405. (function (BABYLON) {
  62406. /**
  62407. * Type of sub emitter
  62408. */
  62409. var SubEmitterType;
  62410. (function (SubEmitterType) {
  62411. /**
  62412. * Attached to the particle over it's lifetime
  62413. */
  62414. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  62415. /**
  62416. * Created when the particle dies
  62417. */
  62418. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  62419. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  62420. /**
  62421. * Sub emitter class used to emit particles from an existing particle
  62422. */
  62423. var SubEmitter = /** @class */ (function () {
  62424. /**
  62425. * Creates a sub emitter
  62426. * @param particleSystem the particle system to be used by the sub emitter
  62427. */
  62428. function SubEmitter(
  62429. /**
  62430. * the particle system to be used by the sub emitter
  62431. */
  62432. particleSystem) {
  62433. this.particleSystem = particleSystem;
  62434. /**
  62435. * Type of the submitter (Default: END)
  62436. */
  62437. this.type = SubEmitterType.END;
  62438. /**
  62439. * If the particle should inherit the direction from the particle it's attached to. (+Y will face the direction the particle is moving) (Default: false)
  62440. * Note: This only is supported when using an emitter of type Mesh
  62441. */
  62442. this.inheritDirection = false;
  62443. /**
  62444. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  62445. */
  62446. this.inheritedVelocityAmount = 0;
  62447. // Create mesh as emitter to support rotation
  62448. if (!particleSystem.emitter || !particleSystem.emitter.dispose) {
  62449. particleSystem.emitter = new BABYLON.AbstractMesh("SubemitterSystemEmitter", particleSystem.getScene());
  62450. }
  62451. // Automatically dispose of subemitter when system is disposed
  62452. particleSystem.onDisposeObservable.add(function () {
  62453. if (particleSystem.emitter && particleSystem.emitter.dispose) {
  62454. particleSystem.emitter.dispose();
  62455. }
  62456. });
  62457. }
  62458. /**
  62459. * Clones the sub emitter
  62460. * @returns the cloned sub emitter
  62461. */
  62462. SubEmitter.prototype.clone = function () {
  62463. // Clone particle system
  62464. var emitter = this.particleSystem.emitter;
  62465. if (!emitter) {
  62466. emitter = new BABYLON.Vector3();
  62467. }
  62468. else if (emitter instanceof BABYLON.Vector3) {
  62469. emitter = emitter.clone();
  62470. }
  62471. else if (emitter instanceof BABYLON.AbstractMesh) {
  62472. emitter = new BABYLON.Mesh("", emitter.getScene());
  62473. emitter.isVisible = false;
  62474. }
  62475. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  62476. // Clone properties
  62477. clone.type = this.type;
  62478. clone.inheritDirection = this.inheritDirection;
  62479. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  62480. clone.particleSystem._disposeEmitterOnDispose = true;
  62481. clone.particleSystem.disposeOnStop = true;
  62482. return clone;
  62483. };
  62484. /**
  62485. * Serialize current object to a JSON object
  62486. * @returns the serialized object
  62487. */
  62488. SubEmitter.prototype.serialize = function () {
  62489. var serializationObject = {};
  62490. serializationObject.type = this.type;
  62491. serializationObject.inheritDirection = this.inheritDirection;
  62492. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  62493. serializationObject.particleSystem = this.particleSystem.serialize();
  62494. return serializationObject;
  62495. };
  62496. /**
  62497. * Creates a new SubEmitter from a serialized JSON version
  62498. * @param serializationObject defines the JSON object to read from
  62499. * @param scene defines the hosting scene
  62500. * @param rootUrl defines the rootUrl for data loading
  62501. * @returns a new SubEmitter
  62502. */
  62503. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  62504. var system = serializationObject.particleSystem;
  62505. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  62506. subEmitter.type = serializationObject.type;
  62507. subEmitter.inheritDirection = serializationObject.inheritDirection;
  62508. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  62509. subEmitter.particleSystem._isSubEmitter = true;
  62510. return subEmitter;
  62511. };
  62512. /** Release associated resources */
  62513. SubEmitter.prototype.dispose = function () {
  62514. this.particleSystem.dispose();
  62515. };
  62516. return SubEmitter;
  62517. }());
  62518. BABYLON.SubEmitter = SubEmitter;
  62519. })(BABYLON || (BABYLON = {}));
  62520. //# sourceMappingURL=babylon.subEmitter.js.map
  62521. var BABYLON;
  62522. (function (BABYLON) {
  62523. /**
  62524. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
  62525. *
  62526. * This returned material effects how the mesh will look based on the code in the shaders.
  62527. *
  62528. * @see http://doc.babylonjs.com/how_to/shader_material
  62529. */
  62530. var ShaderMaterial = /** @class */ (function (_super) {
  62531. __extends(ShaderMaterial, _super);
  62532. /**
  62533. * Instantiate a new shader material.
  62534. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
  62535. * This returned material effects how the mesh will look based on the code in the shaders.
  62536. * @see http://doc.babylonjs.com/how_to/shader_material
  62537. * @param name Define the name of the material in the scene
  62538. * @param scene Define the scene the material belongs to
  62539. * @param shaderPath Defines the route to the shader code in one of three ways:
  62540. * - object - { vertex: "custom", fragment: "custom" }, used with BABYLON.Effect.ShadersStore["customVertexShader"] and BABYLON.Effect.ShadersStore["customFragmentShader"]
  62541. * - object - { vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" }, used with shader code in <script> tags
  62542. * - string - "./COMMON_NAME", used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder.
  62543. * @param options Define the options used to create the shader
  62544. */
  62545. function ShaderMaterial(name, scene, shaderPath, options) {
  62546. if (options === void 0) { options = {}; }
  62547. var _this = _super.call(this, name, scene) || this;
  62548. _this._textures = {};
  62549. _this._textureArrays = {};
  62550. _this._floats = {};
  62551. _this._ints = {};
  62552. _this._floatsArrays = {};
  62553. _this._colors3 = {};
  62554. _this._colors3Arrays = {};
  62555. _this._colors4 = {};
  62556. _this._vectors2 = {};
  62557. _this._vectors3 = {};
  62558. _this._vectors4 = {};
  62559. _this._matrices = {};
  62560. _this._matrices3x3 = {};
  62561. _this._matrices2x2 = {};
  62562. _this._vectors2Arrays = {};
  62563. _this._vectors3Arrays = {};
  62564. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  62565. _this._shaderPath = shaderPath;
  62566. _this._options = __assign({ needAlphaBlending: false, needAlphaTesting: false, attributes: ["position", "normal", "uv"], uniforms: ["worldViewProjection"], uniformBuffers: [], samplers: [], defines: [] }, options);
  62567. return _this;
  62568. }
  62569. /**
  62570. * Gets the current class name of the material e.g. "ShaderMaterial"
  62571. * Mainly use in serialization.
  62572. * @returns the class name
  62573. */
  62574. ShaderMaterial.prototype.getClassName = function () {
  62575. return "ShaderMaterial";
  62576. };
  62577. /**
  62578. * Specifies if the material will require alpha blending
  62579. * @returns a boolean specifying if alpha blending is needed
  62580. */
  62581. ShaderMaterial.prototype.needAlphaBlending = function () {
  62582. return (this.alpha < 1.0) || this._options.needAlphaBlending;
  62583. };
  62584. /**
  62585. * Specifies if this material should be rendered in alpha test mode
  62586. * @returns a boolean specifying if an alpha test is needed.
  62587. */
  62588. ShaderMaterial.prototype.needAlphaTesting = function () {
  62589. return this._options.needAlphaTesting;
  62590. };
  62591. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  62592. if (this._options.uniforms.indexOf(uniformName) === -1) {
  62593. this._options.uniforms.push(uniformName);
  62594. }
  62595. };
  62596. /**
  62597. * Set a texture in the shader.
  62598. * @param name Define the name of the uniform samplers as defined in the shader
  62599. * @param texture Define the texture to bind to this sampler
  62600. * @return the material itself allowing "fluent" like uniform updates
  62601. */
  62602. ShaderMaterial.prototype.setTexture = function (name, texture) {
  62603. if (this._options.samplers.indexOf(name) === -1) {
  62604. this._options.samplers.push(name);
  62605. }
  62606. this._textures[name] = texture;
  62607. return this;
  62608. };
  62609. /**
  62610. * Set a texture array in the shader.
  62611. * @param name Define the name of the uniform sampler array as defined in the shader
  62612. * @param textures Define the list of textures to bind to this sampler
  62613. * @return the material itself allowing "fluent" like uniform updates
  62614. */
  62615. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  62616. if (this._options.samplers.indexOf(name) === -1) {
  62617. this._options.samplers.push(name);
  62618. }
  62619. this._checkUniform(name);
  62620. this._textureArrays[name] = textures;
  62621. return this;
  62622. };
  62623. /**
  62624. * Set a float in the shader.
  62625. * @param name Define the name of the uniform as defined in the shader
  62626. * @param value Define the value to give to the uniform
  62627. * @return the material itself allowing "fluent" like uniform updates
  62628. */
  62629. ShaderMaterial.prototype.setFloat = function (name, value) {
  62630. this._checkUniform(name);
  62631. this._floats[name] = value;
  62632. return this;
  62633. };
  62634. /**
  62635. * Set a int in the shader.
  62636. * @param name Define the name of the uniform as defined in the shader
  62637. * @param value Define the value to give to the uniform
  62638. * @return the material itself allowing "fluent" like uniform updates
  62639. */
  62640. ShaderMaterial.prototype.setInt = function (name, value) {
  62641. this._checkUniform(name);
  62642. this._ints[name] = value;
  62643. return this;
  62644. };
  62645. /**
  62646. * Set an array of floats in the shader.
  62647. * @param name Define the name of the uniform as defined in the shader
  62648. * @param value Define the value to give to the uniform
  62649. * @return the material itself allowing "fluent" like uniform updates
  62650. */
  62651. ShaderMaterial.prototype.setFloats = function (name, value) {
  62652. this._checkUniform(name);
  62653. this._floatsArrays[name] = value;
  62654. return this;
  62655. };
  62656. /**
  62657. * Set a vec3 in the shader from a Color3.
  62658. * @param name Define the name of the uniform as defined in the shader
  62659. * @param value Define the value to give to the uniform
  62660. * @return the material itself allowing "fluent" like uniform updates
  62661. */
  62662. ShaderMaterial.prototype.setColor3 = function (name, value) {
  62663. this._checkUniform(name);
  62664. this._colors3[name] = value;
  62665. return this;
  62666. };
  62667. /**
  62668. * Set a vec3 array in the shader from a Color3 array.
  62669. * @param name Define the name of the uniform as defined in the shader
  62670. * @param value Define the value to give to the uniform
  62671. * @return the material itself allowing "fluent" like uniform updates
  62672. */
  62673. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  62674. this._checkUniform(name);
  62675. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  62676. color.toArray(arr, arr.length);
  62677. return arr;
  62678. }, []);
  62679. return this;
  62680. };
  62681. /**
  62682. * Set a vec4 in the shader from a Color4.
  62683. * @param name Define the name of the uniform as defined in the shader
  62684. * @param value Define the value to give to the uniform
  62685. * @return the material itself allowing "fluent" like uniform updates
  62686. */
  62687. ShaderMaterial.prototype.setColor4 = function (name, value) {
  62688. this._checkUniform(name);
  62689. this._colors4[name] = value;
  62690. return this;
  62691. };
  62692. /**
  62693. * Set a vec2 in the shader from a Vector2.
  62694. * @param name Define the name of the uniform as defined in the shader
  62695. * @param value Define the value to give to the uniform
  62696. * @return the material itself allowing "fluent" like uniform updates
  62697. */
  62698. ShaderMaterial.prototype.setVector2 = function (name, value) {
  62699. this._checkUniform(name);
  62700. this._vectors2[name] = value;
  62701. return this;
  62702. };
  62703. /**
  62704. * Set a vec3 in the shader from a Vector3.
  62705. * @param name Define the name of the uniform as defined in the shader
  62706. * @param value Define the value to give to the uniform
  62707. * @return the material itself allowing "fluent" like uniform updates
  62708. */
  62709. ShaderMaterial.prototype.setVector3 = function (name, value) {
  62710. this._checkUniform(name);
  62711. this._vectors3[name] = value;
  62712. return this;
  62713. };
  62714. /**
  62715. * Set a vec4 in the shader from a Vector4.
  62716. * @param name Define the name of the uniform as defined in the shader
  62717. * @param value Define the value to give to the uniform
  62718. * @return the material itself allowing "fluent" like uniform updates
  62719. */
  62720. ShaderMaterial.prototype.setVector4 = function (name, value) {
  62721. this._checkUniform(name);
  62722. this._vectors4[name] = value;
  62723. return this;
  62724. };
  62725. /**
  62726. * Set a mat4 in the shader from a Matrix.
  62727. * @param name Define the name of the uniform as defined in the shader
  62728. * @param value Define the value to give to the uniform
  62729. * @return the material itself allowing "fluent" like uniform updates
  62730. */
  62731. ShaderMaterial.prototype.setMatrix = function (name, value) {
  62732. this._checkUniform(name);
  62733. this._matrices[name] = value;
  62734. return this;
  62735. };
  62736. /**
  62737. * Set a mat3 in the shader from a Float32Array.
  62738. * @param name Define the name of the uniform as defined in the shader
  62739. * @param value Define the value to give to the uniform
  62740. * @return the material itself allowing "fluent" like uniform updates
  62741. */
  62742. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  62743. this._checkUniform(name);
  62744. this._matrices3x3[name] = value;
  62745. return this;
  62746. };
  62747. /**
  62748. * Set a mat2 in the shader from a Float32Array.
  62749. * @param name Define the name of the uniform as defined in the shader
  62750. * @param value Define the value to give to the uniform
  62751. * @return the material itself allowing "fluent" like uniform updates
  62752. */
  62753. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  62754. this._checkUniform(name);
  62755. this._matrices2x2[name] = value;
  62756. return this;
  62757. };
  62758. /**
  62759. * Set a vec2 array in the shader from a number array.
  62760. * @param name Define the name of the uniform as defined in the shader
  62761. * @param value Define the value to give to the uniform
  62762. * @return the material itself allowing "fluent" like uniform updates
  62763. */
  62764. ShaderMaterial.prototype.setArray2 = function (name, value) {
  62765. this._checkUniform(name);
  62766. this._vectors2Arrays[name] = value;
  62767. return this;
  62768. };
  62769. /**
  62770. * Set a vec3 array in the shader from a number array.
  62771. * @param name Define the name of the uniform as defined in the shader
  62772. * @param value Define the value to give to the uniform
  62773. * @return the material itself allowing "fluent" like uniform updates
  62774. */
  62775. ShaderMaterial.prototype.setArray3 = function (name, value) {
  62776. this._checkUniform(name);
  62777. this._vectors3Arrays[name] = value;
  62778. return this;
  62779. };
  62780. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  62781. if (!mesh) {
  62782. return true;
  62783. }
  62784. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  62785. return false;
  62786. }
  62787. return false;
  62788. };
  62789. /**
  62790. * Checks if the material is ready to render the requested mesh
  62791. * @param mesh Define the mesh to render
  62792. * @param useInstances Define whether or not the material is used with instances
  62793. * @returns true if ready, otherwise false
  62794. */
  62795. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  62796. var scene = this.getScene();
  62797. var engine = scene.getEngine();
  62798. if (!this.checkReadyOnEveryCall) {
  62799. if (this._renderId === scene.getRenderId()) {
  62800. if (this._checkCache(scene, mesh, useInstances)) {
  62801. return true;
  62802. }
  62803. }
  62804. }
  62805. // Instances
  62806. var defines = [];
  62807. var attribs = [];
  62808. var fallbacks = new BABYLON.EffectFallbacks();
  62809. for (var index = 0; index < this._options.defines.length; index++) {
  62810. defines.push(this._options.defines[index]);
  62811. }
  62812. for (var index = 0; index < this._options.attributes.length; index++) {
  62813. attribs.push(this._options.attributes[index]);
  62814. }
  62815. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  62816. attribs.push(BABYLON.VertexBuffer.ColorKind);
  62817. defines.push("#define VERTEXCOLOR");
  62818. }
  62819. if (useInstances) {
  62820. defines.push("#define INSTANCES");
  62821. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  62822. }
  62823. // Bones
  62824. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  62825. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62826. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62827. if (mesh.numBoneInfluencers > 4) {
  62828. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  62829. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  62830. }
  62831. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62832. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  62833. fallbacks.addCPUSkinningFallback(0, mesh);
  62834. if (this._options.uniforms.indexOf("mBones") === -1) {
  62835. this._options.uniforms.push("mBones");
  62836. }
  62837. }
  62838. else {
  62839. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62840. }
  62841. // Textures
  62842. for (var name in this._textures) {
  62843. if (!this._textures[name].isReady()) {
  62844. return false;
  62845. }
  62846. }
  62847. // Alpha test
  62848. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  62849. defines.push("#define ALPHATEST");
  62850. }
  62851. var previousEffect = this._effect;
  62852. var join = defines.join("\n");
  62853. this._effect = engine.createEffect(this._shaderPath, {
  62854. attributes: attribs,
  62855. uniformsNames: this._options.uniforms,
  62856. uniformBuffersNames: this._options.uniformBuffers,
  62857. samplers: this._options.samplers,
  62858. defines: join,
  62859. fallbacks: fallbacks,
  62860. onCompiled: this.onCompiled,
  62861. onError: this.onError
  62862. }, engine);
  62863. if (!this._effect.isReady()) {
  62864. return false;
  62865. }
  62866. if (previousEffect !== this._effect) {
  62867. scene.resetCachedMaterial();
  62868. }
  62869. this._renderId = scene.getRenderId();
  62870. return true;
  62871. };
  62872. /**
  62873. * Binds the world matrix to the material
  62874. * @param world defines the world transformation matrix
  62875. */
  62876. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  62877. var scene = this.getScene();
  62878. if (!this._effect) {
  62879. return;
  62880. }
  62881. if (this._options.uniforms.indexOf("world") !== -1) {
  62882. this._effect.setMatrix("world", world);
  62883. }
  62884. if (this._options.uniforms.indexOf("worldView") !== -1) {
  62885. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  62886. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  62887. }
  62888. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  62889. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  62890. }
  62891. };
  62892. /**
  62893. * Binds the material to the mesh
  62894. * @param world defines the world transformation matrix
  62895. * @param mesh defines the mesh to bind the material to
  62896. */
  62897. ShaderMaterial.prototype.bind = function (world, mesh) {
  62898. // Std values
  62899. this.bindOnlyWorldMatrix(world);
  62900. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  62901. if (this._options.uniforms.indexOf("view") !== -1) {
  62902. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  62903. }
  62904. if (this._options.uniforms.indexOf("projection") !== -1) {
  62905. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  62906. }
  62907. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  62908. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  62909. }
  62910. // Bones
  62911. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  62912. var name;
  62913. // Texture
  62914. for (name in this._textures) {
  62915. this._effect.setTexture(name, this._textures[name]);
  62916. }
  62917. // Texture arrays
  62918. for (name in this._textureArrays) {
  62919. this._effect.setTextureArray(name, this._textureArrays[name]);
  62920. }
  62921. // Int
  62922. for (name in this._ints) {
  62923. this._effect.setInt(name, this._ints[name]);
  62924. }
  62925. // Float
  62926. for (name in this._floats) {
  62927. this._effect.setFloat(name, this._floats[name]);
  62928. }
  62929. // Floats
  62930. for (name in this._floatsArrays) {
  62931. this._effect.setArray(name, this._floatsArrays[name]);
  62932. }
  62933. // Color3
  62934. for (name in this._colors3) {
  62935. this._effect.setColor3(name, this._colors3[name]);
  62936. }
  62937. for (name in this._colors3Arrays) {
  62938. this._effect.setArray3(name, this._colors3Arrays[name]);
  62939. }
  62940. // Color4
  62941. for (name in this._colors4) {
  62942. var color = this._colors4[name];
  62943. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  62944. }
  62945. // Vector2
  62946. for (name in this._vectors2) {
  62947. this._effect.setVector2(name, this._vectors2[name]);
  62948. }
  62949. // Vector3
  62950. for (name in this._vectors3) {
  62951. this._effect.setVector3(name, this._vectors3[name]);
  62952. }
  62953. // Vector4
  62954. for (name in this._vectors4) {
  62955. this._effect.setVector4(name, this._vectors4[name]);
  62956. }
  62957. // Matrix
  62958. for (name in this._matrices) {
  62959. this._effect.setMatrix(name, this._matrices[name]);
  62960. }
  62961. // Matrix 3x3
  62962. for (name in this._matrices3x3) {
  62963. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  62964. }
  62965. // Matrix 2x2
  62966. for (name in this._matrices2x2) {
  62967. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  62968. }
  62969. // Vector2Array
  62970. for (name in this._vectors2Arrays) {
  62971. this._effect.setArray2(name, this._vectors2Arrays[name]);
  62972. }
  62973. // Vector3Array
  62974. for (name in this._vectors3Arrays) {
  62975. this._effect.setArray3(name, this._vectors3Arrays[name]);
  62976. }
  62977. }
  62978. this._afterBind(mesh);
  62979. };
  62980. /**
  62981. * Gets the active textures from the material
  62982. * @returns an array of textures
  62983. */
  62984. ShaderMaterial.prototype.getActiveTextures = function () {
  62985. var activeTextures = _super.prototype.getActiveTextures.call(this);
  62986. for (var name in this._textures) {
  62987. activeTextures.push(this._textures[name]);
  62988. }
  62989. for (var name in this._textureArrays) {
  62990. var array = this._textureArrays[name];
  62991. for (var index = 0; index < array.length; index++) {
  62992. activeTextures.push(array[index]);
  62993. }
  62994. }
  62995. return activeTextures;
  62996. };
  62997. /**
  62998. * Specifies if the material uses a texture
  62999. * @param texture defines the texture to check against the material
  63000. * @returns a boolean specifying if the material uses the texture
  63001. */
  63002. ShaderMaterial.prototype.hasTexture = function (texture) {
  63003. if (_super.prototype.hasTexture.call(this, texture)) {
  63004. return true;
  63005. }
  63006. for (var name in this._textures) {
  63007. if (this._textures[name] === texture) {
  63008. return true;
  63009. }
  63010. }
  63011. for (var name in this._textureArrays) {
  63012. var array = this._textureArrays[name];
  63013. for (var index = 0; index < array.length; index++) {
  63014. if (array[index] === texture) {
  63015. return true;
  63016. }
  63017. }
  63018. }
  63019. return false;
  63020. };
  63021. /**
  63022. * Makes a duplicate of the material, and gives it a new name
  63023. * @param name defines the new name for the duplicated material
  63024. * @returns the cloned material
  63025. */
  63026. ShaderMaterial.prototype.clone = function (name) {
  63027. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  63028. return newShaderMaterial;
  63029. };
  63030. /**
  63031. * Disposes the material
  63032. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  63033. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  63034. */
  63035. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  63036. if (forceDisposeTextures) {
  63037. var name;
  63038. for (name in this._textures) {
  63039. this._textures[name].dispose();
  63040. }
  63041. for (name in this._textureArrays) {
  63042. var array = this._textureArrays[name];
  63043. for (var index = 0; index < array.length; index++) {
  63044. array[index].dispose();
  63045. }
  63046. }
  63047. }
  63048. this._textures = {};
  63049. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  63050. };
  63051. /**
  63052. * Serializes this material in a JSON representation
  63053. * @returns the serialized material object
  63054. */
  63055. ShaderMaterial.prototype.serialize = function () {
  63056. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  63057. serializationObject.customType = "BABYLON.ShaderMaterial";
  63058. serializationObject.options = this._options;
  63059. serializationObject.shaderPath = this._shaderPath;
  63060. var name;
  63061. // Texture
  63062. serializationObject.textures = {};
  63063. for (name in this._textures) {
  63064. serializationObject.textures[name] = this._textures[name].serialize();
  63065. }
  63066. // Texture arrays
  63067. serializationObject.textureArrays = {};
  63068. for (name in this._textureArrays) {
  63069. serializationObject.textureArrays[name] = [];
  63070. var array = this._textureArrays[name];
  63071. for (var index = 0; index < array.length; index++) {
  63072. serializationObject.textureArrays[name].push(array[index].serialize());
  63073. }
  63074. }
  63075. // Float
  63076. serializationObject.floats = {};
  63077. for (name in this._floats) {
  63078. serializationObject.floats[name] = this._floats[name];
  63079. }
  63080. // Float s
  63081. serializationObject.FloatArrays = {};
  63082. for (name in this._floatsArrays) {
  63083. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  63084. }
  63085. // Color3
  63086. serializationObject.colors3 = {};
  63087. for (name in this._colors3) {
  63088. serializationObject.colors3[name] = this._colors3[name].asArray();
  63089. }
  63090. // Color3 array
  63091. serializationObject.colors3Arrays = {};
  63092. for (name in this._colors3Arrays) {
  63093. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  63094. }
  63095. // Color4
  63096. serializationObject.colors4 = {};
  63097. for (name in this._colors4) {
  63098. serializationObject.colors4[name] = this._colors4[name].asArray();
  63099. }
  63100. // Vector2
  63101. serializationObject.vectors2 = {};
  63102. for (name in this._vectors2) {
  63103. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  63104. }
  63105. // Vector3
  63106. serializationObject.vectors3 = {};
  63107. for (name in this._vectors3) {
  63108. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  63109. }
  63110. // Vector4
  63111. serializationObject.vectors4 = {};
  63112. for (name in this._vectors4) {
  63113. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  63114. }
  63115. // Matrix
  63116. serializationObject.matrices = {};
  63117. for (name in this._matrices) {
  63118. serializationObject.matrices[name] = this._matrices[name].asArray();
  63119. }
  63120. // Matrix 3x3
  63121. serializationObject.matrices3x3 = {};
  63122. for (name in this._matrices3x3) {
  63123. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  63124. }
  63125. // Matrix 2x2
  63126. serializationObject.matrices2x2 = {};
  63127. for (name in this._matrices2x2) {
  63128. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  63129. }
  63130. // Vector2Array
  63131. serializationObject.vectors2Arrays = {};
  63132. for (name in this._vectors2Arrays) {
  63133. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  63134. }
  63135. // Vector3Array
  63136. serializationObject.vectors3Arrays = {};
  63137. for (name in this._vectors3Arrays) {
  63138. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  63139. }
  63140. return serializationObject;
  63141. };
  63142. /**
  63143. * Creates a shader material from parsed shader material data
  63144. * @param source defines the JSON represnetation of the material
  63145. * @param scene defines the hosting scene
  63146. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  63147. * @returns a new material
  63148. */
  63149. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  63150. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  63151. var name;
  63152. // Texture
  63153. for (name in source.textures) {
  63154. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  63155. }
  63156. // Texture arrays
  63157. for (name in source.textureArrays) {
  63158. var array = source.textureArrays[name];
  63159. var textureArray = new Array();
  63160. for (var index = 0; index < array.length; index++) {
  63161. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  63162. }
  63163. material.setTextureArray(name, textureArray);
  63164. }
  63165. // Float
  63166. for (name in source.floats) {
  63167. material.setFloat(name, source.floats[name]);
  63168. }
  63169. // Float s
  63170. for (name in source.floatsArrays) {
  63171. material.setFloats(name, source.floatsArrays[name]);
  63172. }
  63173. // Color3
  63174. for (name in source.colors3) {
  63175. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  63176. }
  63177. // Color3 arrays
  63178. for (name in source.colors3Arrays) {
  63179. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  63180. if (i % 3 === 0) {
  63181. arr.push([num]);
  63182. }
  63183. else {
  63184. arr[arr.length - 1].push(num);
  63185. }
  63186. return arr;
  63187. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  63188. material.setColor3Array(name, colors);
  63189. }
  63190. // Color4
  63191. for (name in source.colors4) {
  63192. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  63193. }
  63194. // Vector2
  63195. for (name in source.vectors2) {
  63196. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  63197. }
  63198. // Vector3
  63199. for (name in source.vectors3) {
  63200. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  63201. }
  63202. // Vector4
  63203. for (name in source.vectors4) {
  63204. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  63205. }
  63206. // Matrix
  63207. for (name in source.matrices) {
  63208. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  63209. }
  63210. // Matrix 3x3
  63211. for (name in source.matrices3x3) {
  63212. material.setMatrix3x3(name, source.matrices3x3[name]);
  63213. }
  63214. // Matrix 2x2
  63215. for (name in source.matrices2x2) {
  63216. material.setMatrix2x2(name, source.matrices2x2[name]);
  63217. }
  63218. // Vector2Array
  63219. for (name in source.vectors2Arrays) {
  63220. material.setArray2(name, source.vectors2Arrays[name]);
  63221. }
  63222. // Vector3Array
  63223. for (name in source.vectors3Arrays) {
  63224. material.setArray3(name, source.vectors3Arrays[name]);
  63225. }
  63226. return material;
  63227. };
  63228. return ShaderMaterial;
  63229. }(BABYLON.Material));
  63230. BABYLON.ShaderMaterial = ShaderMaterial;
  63231. })(BABYLON || (BABYLON = {}));
  63232. //# sourceMappingURL=babylon.shaderMaterial.js.map
  63233. var BABYLON;
  63234. (function (BABYLON) {
  63235. /**
  63236. * Mesh representing the gorund
  63237. */
  63238. var GroundMesh = /** @class */ (function (_super) {
  63239. __extends(GroundMesh, _super);
  63240. function GroundMesh(name, scene) {
  63241. var _this = _super.call(this, name, scene) || this;
  63242. /** If octree should be generated */
  63243. _this.generateOctree = false;
  63244. return _this;
  63245. }
  63246. /**
  63247. * "GroundMesh"
  63248. * @returns "GroundMesh"
  63249. */
  63250. GroundMesh.prototype.getClassName = function () {
  63251. return "GroundMesh";
  63252. };
  63253. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  63254. /**
  63255. * The minimum of x and y subdivisions
  63256. */
  63257. get: function () {
  63258. return Math.min(this._subdivisionsX, this._subdivisionsY);
  63259. },
  63260. enumerable: true,
  63261. configurable: true
  63262. });
  63263. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  63264. /**
  63265. * X subdivisions
  63266. */
  63267. get: function () {
  63268. return this._subdivisionsX;
  63269. },
  63270. enumerable: true,
  63271. configurable: true
  63272. });
  63273. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  63274. /**
  63275. * Y subdivisions
  63276. */
  63277. get: function () {
  63278. return this._subdivisionsY;
  63279. },
  63280. enumerable: true,
  63281. configurable: true
  63282. });
  63283. /**
  63284. * This function will update an octree to help to select the right submeshes for rendering, picking and collision computations.
  63285. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  63286. * @param chunksCount the number of subdivisions for x and y
  63287. * @param octreeBlocksSize (Default: 32)
  63288. */
  63289. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  63290. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  63291. this._subdivisionsX = chunksCount;
  63292. this._subdivisionsY = chunksCount;
  63293. this.subdivide(chunksCount);
  63294. // Call the octree system optimization if it is defined.
  63295. var thisAsAny = this;
  63296. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  63297. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  63298. }
  63299. };
  63300. /**
  63301. * Returns a height (y) value in the Worl system :
  63302. * the ground altitude at the coordinates (x, z) expressed in the World system.
  63303. * @param x x coordinate
  63304. * @param z z coordinate
  63305. * @returns the ground y position if (x, z) are outside the ground surface.
  63306. */
  63307. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  63308. var world = this.getWorldMatrix();
  63309. var invMat = BABYLON.Tmp.Matrix[5];
  63310. world.invertToRef(invMat);
  63311. var tmpVect = BABYLON.Tmp.Vector3[8];
  63312. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  63313. x = tmpVect.x;
  63314. z = tmpVect.z;
  63315. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  63316. return this.position.y;
  63317. }
  63318. if (!this._heightQuads || this._heightQuads.length == 0) {
  63319. this._initHeightQuads();
  63320. this._computeHeightQuads();
  63321. }
  63322. var facet = this._getFacetAt(x, z);
  63323. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  63324. // return y in the World system
  63325. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  63326. return tmpVect.y;
  63327. };
  63328. /**
  63329. * Returns a normalized vector (Vector3) orthogonal to the ground
  63330. * at the ground coordinates (x, z) expressed in the World system.
  63331. * @param x x coordinate
  63332. * @param z z coordinate
  63333. * @returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  63334. */
  63335. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  63336. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  63337. this.getNormalAtCoordinatesToRef(x, z, normal);
  63338. return normal;
  63339. };
  63340. /**
  63341. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  63342. * at the ground coordinates (x, z) expressed in the World system.
  63343. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  63344. * @param x x coordinate
  63345. * @param z z coordinate
  63346. * @param ref vector to store the result
  63347. * @returns the GroundMesh.
  63348. */
  63349. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  63350. var world = this.getWorldMatrix();
  63351. var tmpMat = BABYLON.Tmp.Matrix[5];
  63352. world.invertToRef(tmpMat);
  63353. var tmpVect = BABYLON.Tmp.Vector3[8];
  63354. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  63355. x = tmpVect.x;
  63356. z = tmpVect.z;
  63357. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  63358. return this;
  63359. }
  63360. if (!this._heightQuads || this._heightQuads.length == 0) {
  63361. this._initHeightQuads();
  63362. this._computeHeightQuads();
  63363. }
  63364. var facet = this._getFacetAt(x, z);
  63365. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  63366. return this;
  63367. };
  63368. /**
  63369. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  63370. * if the ground has been updated.
  63371. * This can be used in the render loop.
  63372. * @returns the GroundMesh.
  63373. */
  63374. GroundMesh.prototype.updateCoordinateHeights = function () {
  63375. if (!this._heightQuads || this._heightQuads.length == 0) {
  63376. this._initHeightQuads();
  63377. }
  63378. this._computeHeightQuads();
  63379. return this;
  63380. };
  63381. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  63382. GroundMesh.prototype._getFacetAt = function (x, z) {
  63383. // retrieve col and row from x, z coordinates in the ground local system
  63384. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  63385. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  63386. var quad = this._heightQuads[row * this._subdivisionsX + col];
  63387. var facet;
  63388. if (z < quad.slope.x * x + quad.slope.y) {
  63389. facet = quad.facet1;
  63390. }
  63391. else {
  63392. facet = quad.facet2;
  63393. }
  63394. return facet;
  63395. };
  63396. // Creates and populates the heightMap array with "facet" elements :
  63397. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  63398. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  63399. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  63400. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  63401. // Returns the GroundMesh.
  63402. GroundMesh.prototype._initHeightQuads = function () {
  63403. var subdivisionsX = this._subdivisionsX;
  63404. var subdivisionsY = this._subdivisionsY;
  63405. this._heightQuads = new Array();
  63406. for (var row = 0; row < subdivisionsY; row++) {
  63407. for (var col = 0; col < subdivisionsX; col++) {
  63408. 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) };
  63409. this._heightQuads[row * subdivisionsX + col] = quad;
  63410. }
  63411. }
  63412. return this;
  63413. };
  63414. // Compute each quad element values and update the the heightMap array :
  63415. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  63416. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  63417. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  63418. // Returns the GroundMesh.
  63419. GroundMesh.prototype._computeHeightQuads = function () {
  63420. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63421. if (!positions) {
  63422. return this;
  63423. }
  63424. var v1 = BABYLON.Tmp.Vector3[3];
  63425. var v2 = BABYLON.Tmp.Vector3[2];
  63426. var v3 = BABYLON.Tmp.Vector3[1];
  63427. var v4 = BABYLON.Tmp.Vector3[0];
  63428. var v1v2 = BABYLON.Tmp.Vector3[4];
  63429. var v1v3 = BABYLON.Tmp.Vector3[5];
  63430. var v1v4 = BABYLON.Tmp.Vector3[6];
  63431. var norm1 = BABYLON.Tmp.Vector3[7];
  63432. var norm2 = BABYLON.Tmp.Vector3[8];
  63433. var i = 0;
  63434. var j = 0;
  63435. var k = 0;
  63436. var cd = 0; // 2D slope coefficient : z = cd * x + h
  63437. var h = 0;
  63438. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  63439. var d2 = 0;
  63440. var subdivisionsX = this._subdivisionsX;
  63441. var subdivisionsY = this._subdivisionsY;
  63442. for (var row = 0; row < subdivisionsY; row++) {
  63443. for (var col = 0; col < subdivisionsX; col++) {
  63444. i = col * 3;
  63445. j = row * (subdivisionsX + 1) * 3;
  63446. k = (row + 1) * (subdivisionsX + 1) * 3;
  63447. v1.x = positions[j + i];
  63448. v1.y = positions[j + i + 1];
  63449. v1.z = positions[j + i + 2];
  63450. v2.x = positions[j + i + 3];
  63451. v2.y = positions[j + i + 4];
  63452. v2.z = positions[j + i + 5];
  63453. v3.x = positions[k + i];
  63454. v3.y = positions[k + i + 1];
  63455. v3.z = positions[k + i + 2];
  63456. v4.x = positions[k + i + 3];
  63457. v4.y = positions[k + i + 4];
  63458. v4.z = positions[k + i + 5];
  63459. // 2D slope V1V4
  63460. cd = (v4.z - v1.z) / (v4.x - v1.x);
  63461. h = v1.z - cd * v1.x; // v1 belongs to the slope
  63462. // facet equations :
  63463. // we compute each facet normal vector
  63464. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  63465. // we compute the value d by applying the equation to v1 which belongs to the plane
  63466. // then we store the facet equation in a Vector4
  63467. v2.subtractToRef(v1, v1v2);
  63468. v3.subtractToRef(v1, v1v3);
  63469. v4.subtractToRef(v1, v1v4);
  63470. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  63471. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  63472. norm1.normalize();
  63473. norm2.normalize();
  63474. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  63475. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  63476. var quad = this._heightQuads[row * subdivisionsX + col];
  63477. quad.slope.copyFromFloats(cd, h);
  63478. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  63479. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  63480. }
  63481. }
  63482. return this;
  63483. };
  63484. /**
  63485. * Serializes this ground mesh
  63486. * @param serializationObject object to write serialization to
  63487. */
  63488. GroundMesh.prototype.serialize = function (serializationObject) {
  63489. _super.prototype.serialize.call(this, serializationObject);
  63490. serializationObject.subdivisionsX = this._subdivisionsX;
  63491. serializationObject.subdivisionsY = this._subdivisionsY;
  63492. serializationObject.minX = this._minX;
  63493. serializationObject.maxX = this._maxX;
  63494. serializationObject.minZ = this._minZ;
  63495. serializationObject.maxZ = this._maxZ;
  63496. serializationObject.width = this._width;
  63497. serializationObject.height = this._height;
  63498. };
  63499. /**
  63500. * Parses a serialized ground mesh
  63501. * @param parsedMesh the serialized mesh
  63502. * @param scene the scene to create the ground mesh in
  63503. * @returns the created ground mesh
  63504. */
  63505. GroundMesh.Parse = function (parsedMesh, scene) {
  63506. var result = new GroundMesh(parsedMesh.name, scene);
  63507. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  63508. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  63509. result._minX = parsedMesh.minX;
  63510. result._maxX = parsedMesh.maxX;
  63511. result._minZ = parsedMesh.minZ;
  63512. result._maxZ = parsedMesh.maxZ;
  63513. result._width = parsedMesh.width;
  63514. result._height = parsedMesh.height;
  63515. return result;
  63516. };
  63517. return GroundMesh;
  63518. }(BABYLON.Mesh));
  63519. BABYLON.GroundMesh = GroundMesh;
  63520. })(BABYLON || (BABYLON = {}));
  63521. //# sourceMappingURL=babylon.groundMesh.js.map
  63522. var BABYLON;
  63523. (function (BABYLON) {
  63524. /**
  63525. * Creates an instance based on a source mesh.
  63526. */
  63527. var InstancedMesh = /** @class */ (function (_super) {
  63528. __extends(InstancedMesh, _super);
  63529. function InstancedMesh(name, source) {
  63530. var _this = _super.call(this, name, source.getScene()) || this;
  63531. source.instances.push(_this);
  63532. _this._sourceMesh = source;
  63533. _this.position.copyFrom(source.position);
  63534. _this.rotation.copyFrom(source.rotation);
  63535. _this.scaling.copyFrom(source.scaling);
  63536. if (source.rotationQuaternion) {
  63537. _this.rotationQuaternion = source.rotationQuaternion.clone();
  63538. }
  63539. _this.infiniteDistance = source.infiniteDistance;
  63540. _this.setPivotMatrix(source.getPivotMatrix());
  63541. _this.refreshBoundingInfo();
  63542. _this._syncSubMeshes();
  63543. return _this;
  63544. }
  63545. /**
  63546. * Returns the string "InstancedMesh".
  63547. */
  63548. InstancedMesh.prototype.getClassName = function () {
  63549. return "InstancedMesh";
  63550. };
  63551. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  63552. // Methods
  63553. /**
  63554. * If the source mesh receives shadows
  63555. */
  63556. get: function () {
  63557. return this._sourceMesh.receiveShadows;
  63558. },
  63559. enumerable: true,
  63560. configurable: true
  63561. });
  63562. Object.defineProperty(InstancedMesh.prototype, "material", {
  63563. /**
  63564. * The material of the source mesh
  63565. */
  63566. get: function () {
  63567. return this._sourceMesh.material;
  63568. },
  63569. enumerable: true,
  63570. configurable: true
  63571. });
  63572. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  63573. /**
  63574. * Visibility of the source mesh
  63575. */
  63576. get: function () {
  63577. return this._sourceMesh.visibility;
  63578. },
  63579. enumerable: true,
  63580. configurable: true
  63581. });
  63582. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  63583. /**
  63584. * Skeleton of the source mesh
  63585. */
  63586. get: function () {
  63587. return this._sourceMesh.skeleton;
  63588. },
  63589. enumerable: true,
  63590. configurable: true
  63591. });
  63592. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  63593. /**
  63594. * Rendering ground id of the source mesh
  63595. */
  63596. get: function () {
  63597. return this._sourceMesh.renderingGroupId;
  63598. },
  63599. set: function (value) {
  63600. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  63601. return;
  63602. }
  63603. //no-op with warning
  63604. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  63605. },
  63606. enumerable: true,
  63607. configurable: true
  63608. });
  63609. /**
  63610. * Returns the total number of vertices (integer).
  63611. */
  63612. InstancedMesh.prototype.getTotalVertices = function () {
  63613. return this._sourceMesh.getTotalVertices();
  63614. };
  63615. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  63616. /**
  63617. * The source mesh of the instance
  63618. */
  63619. get: function () {
  63620. return this._sourceMesh;
  63621. },
  63622. enumerable: true,
  63623. configurable: true
  63624. });
  63625. /**
  63626. * Is this node ready to be used/rendered
  63627. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  63628. * @return {boolean} is it ready
  63629. */
  63630. InstancedMesh.prototype.isReady = function (completeCheck) {
  63631. if (completeCheck === void 0) { completeCheck = false; }
  63632. return this._sourceMesh.isReady(completeCheck, true);
  63633. };
  63634. /**
  63635. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  63636. * @param kind kind of verticies to retreive (eg. positons, normals, uvs, etc.)
  63637. * @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.
  63638. * @returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  63639. */
  63640. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  63641. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  63642. };
  63643. /**
  63644. * Sets the vertex data of the mesh geometry for the requested `kind`.
  63645. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  63646. * The `data` are either a numeric array either a Float32Array.
  63647. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  63648. * 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).
  63649. * Note that a new underlying VertexBuffer object is created each call.
  63650. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  63651. *
  63652. * Possible `kind` values :
  63653. * - BABYLON.VertexBuffer.PositionKind
  63654. * - BABYLON.VertexBuffer.UVKind
  63655. * - BABYLON.VertexBuffer.UV2Kind
  63656. * - BABYLON.VertexBuffer.UV3Kind
  63657. * - BABYLON.VertexBuffer.UV4Kind
  63658. * - BABYLON.VertexBuffer.UV5Kind
  63659. * - BABYLON.VertexBuffer.UV6Kind
  63660. * - BABYLON.VertexBuffer.ColorKind
  63661. * - BABYLON.VertexBuffer.MatricesIndicesKind
  63662. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  63663. * - BABYLON.VertexBuffer.MatricesWeightsKind
  63664. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  63665. *
  63666. * Returns the Mesh.
  63667. */
  63668. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  63669. if (this.sourceMesh) {
  63670. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  63671. }
  63672. return this.sourceMesh;
  63673. };
  63674. /**
  63675. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  63676. * If the mesh has no geometry, it is simply returned as it is.
  63677. * The `data` are either a numeric array either a Float32Array.
  63678. * No new underlying VertexBuffer object is created.
  63679. * 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.
  63680. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  63681. *
  63682. * Possible `kind` values :
  63683. * - BABYLON.VertexBuffer.PositionKind
  63684. * - BABYLON.VertexBuffer.UVKind
  63685. * - BABYLON.VertexBuffer.UV2Kind
  63686. * - BABYLON.VertexBuffer.UV3Kind
  63687. * - BABYLON.VertexBuffer.UV4Kind
  63688. * - BABYLON.VertexBuffer.UV5Kind
  63689. * - BABYLON.VertexBuffer.UV6Kind
  63690. * - BABYLON.VertexBuffer.ColorKind
  63691. * - BABYLON.VertexBuffer.MatricesIndicesKind
  63692. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  63693. * - BABYLON.VertexBuffer.MatricesWeightsKind
  63694. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  63695. *
  63696. * Returns the Mesh.
  63697. */
  63698. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  63699. if (this.sourceMesh) {
  63700. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  63701. }
  63702. return this.sourceMesh;
  63703. };
  63704. /**
  63705. * Sets the mesh indices.
  63706. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  63707. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  63708. * This method creates a new index buffer each call.
  63709. * Returns the Mesh.
  63710. */
  63711. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  63712. if (totalVertices === void 0) { totalVertices = null; }
  63713. if (this.sourceMesh) {
  63714. this.sourceMesh.setIndices(indices, totalVertices);
  63715. }
  63716. return this.sourceMesh;
  63717. };
  63718. /**
  63719. * Boolean : True if the mesh owns the requested kind of data.
  63720. */
  63721. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  63722. return this._sourceMesh.isVerticesDataPresent(kind);
  63723. };
  63724. /**
  63725. * Returns an array of indices (IndicesArray).
  63726. */
  63727. InstancedMesh.prototype.getIndices = function () {
  63728. return this._sourceMesh.getIndices();
  63729. };
  63730. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  63731. get: function () {
  63732. return this._sourceMesh._positions;
  63733. },
  63734. enumerable: true,
  63735. configurable: true
  63736. });
  63737. /**
  63738. * Sets a new updated BoundingInfo to the mesh.
  63739. * @returns the mesh.
  63740. */
  63741. InstancedMesh.prototype.refreshBoundingInfo = function () {
  63742. var meshBB = this._sourceMesh.getBoundingInfo();
  63743. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  63744. this._updateBoundingInfo();
  63745. return this;
  63746. };
  63747. /** @hidden */
  63748. InstancedMesh.prototype._preActivate = function () {
  63749. if (this._currentLOD) {
  63750. this._currentLOD._preActivate();
  63751. }
  63752. return this;
  63753. };
  63754. /** @hidden */
  63755. InstancedMesh.prototype._activate = function (renderId) {
  63756. if (this._currentLOD) {
  63757. this._currentLOD._registerInstanceForRenderId(this, renderId);
  63758. }
  63759. return this;
  63760. };
  63761. /**
  63762. * Returns the current associated LOD AbstractMesh.
  63763. */
  63764. InstancedMesh.prototype.getLOD = function (camera) {
  63765. if (!camera) {
  63766. return this;
  63767. }
  63768. var boundingInfo = this.getBoundingInfo();
  63769. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  63770. if (this._currentLOD === this.sourceMesh) {
  63771. return this;
  63772. }
  63773. return this._currentLOD;
  63774. };
  63775. /** @hidden */
  63776. InstancedMesh.prototype._syncSubMeshes = function () {
  63777. this.releaseSubMeshes();
  63778. if (this._sourceMesh.subMeshes) {
  63779. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  63780. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  63781. }
  63782. }
  63783. return this;
  63784. };
  63785. /** @hidden */
  63786. InstancedMesh.prototype._generatePointsArray = function () {
  63787. return this._sourceMesh._generatePointsArray();
  63788. };
  63789. /**
  63790. * Creates a new InstancedMesh from the current mesh.
  63791. * - name (string) : the cloned mesh name
  63792. * - newParent (optional Node) : the optional Node to parent the clone to.
  63793. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  63794. *
  63795. * Returns the clone.
  63796. */
  63797. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  63798. var result = this._sourceMesh.createInstance(name);
  63799. // Deep copy
  63800. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  63801. // Bounding info
  63802. this.refreshBoundingInfo();
  63803. // Parent
  63804. if (newParent) {
  63805. result.parent = newParent;
  63806. }
  63807. if (!doNotCloneChildren) {
  63808. // Children
  63809. for (var index = 0; index < this.getScene().meshes.length; index++) {
  63810. var mesh = this.getScene().meshes[index];
  63811. if (mesh.parent === this) {
  63812. mesh.clone(mesh.name, result);
  63813. }
  63814. }
  63815. }
  63816. result.computeWorldMatrix(true);
  63817. return result;
  63818. };
  63819. /**
  63820. * Disposes the InstancedMesh.
  63821. * Returns nothing.
  63822. */
  63823. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  63824. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  63825. // Remove from mesh
  63826. var index = this._sourceMesh.instances.indexOf(this);
  63827. this._sourceMesh.instances.splice(index, 1);
  63828. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  63829. };
  63830. return InstancedMesh;
  63831. }(BABYLON.AbstractMesh));
  63832. BABYLON.InstancedMesh = InstancedMesh;
  63833. })(BABYLON || (BABYLON = {}));
  63834. //# sourceMappingURL=babylon.instancedMesh.js.map
  63835. var BABYLON;
  63836. (function (BABYLON) {
  63837. /**
  63838. * Line mesh
  63839. * @see https://doc.babylonjs.com/babylon101/parametric_shapes
  63840. */
  63841. var LinesMesh = /** @class */ (function (_super) {
  63842. __extends(LinesMesh, _super);
  63843. /**
  63844. * Creates a new LinesMesh
  63845. * @param name defines the name
  63846. * @param scene defines the hosting scene
  63847. * @param parent defines the parent mesh if any
  63848. * @param source defines the optional source LinesMesh used to clone data from
  63849. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  63850. * When false, achieved by calling a clone(), also passing False.
  63851. * This will make creation of children, recursive.
  63852. * @param useVertexColor defines if this LinesMesh supports vertex color
  63853. * @param useVertexAlpha defines if this LinesMesh supports vertex alpha
  63854. */
  63855. function LinesMesh(name, scene, parent, source, doNotCloneChildren,
  63856. /**
  63857. * If vertex color should be applied to the mesh
  63858. */
  63859. useVertexColor,
  63860. /**
  63861. * If vertex alpha should be applied to the mesh
  63862. */
  63863. useVertexAlpha) {
  63864. if (scene === void 0) { scene = null; }
  63865. if (parent === void 0) { parent = null; }
  63866. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  63867. _this.useVertexColor = useVertexColor;
  63868. _this.useVertexAlpha = useVertexAlpha;
  63869. /**
  63870. * Color of the line (Default: White)
  63871. */
  63872. _this.color = new BABYLON.Color3(1, 1, 1);
  63873. /**
  63874. * Alpha of the line (Default: 1)
  63875. */
  63876. _this.alpha = 1;
  63877. if (source) {
  63878. _this.color = source.color.clone();
  63879. _this.alpha = source.alpha;
  63880. _this.useVertexColor = source.useVertexColor;
  63881. _this.useVertexAlpha = source.useVertexAlpha;
  63882. }
  63883. _this._intersectionThreshold = 0.1;
  63884. var defines = [];
  63885. var options = {
  63886. attributes: [BABYLON.VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"],
  63887. uniforms: ["world", "viewProjection"],
  63888. needAlphaBlending: true,
  63889. defines: defines
  63890. };
  63891. if (useVertexAlpha === false) {
  63892. options.needAlphaBlending = false;
  63893. }
  63894. if (!useVertexColor) {
  63895. options.uniforms.push("color");
  63896. }
  63897. else {
  63898. options.defines.push("#define VERTEXCOLOR");
  63899. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  63900. }
  63901. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  63902. return _this;
  63903. }
  63904. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  63905. /**
  63906. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  63907. * This margin is expressed in world space coordinates, so its value may vary.
  63908. * Default value is 0.1
  63909. * @returns the intersection Threshold value.
  63910. */
  63911. get: function () {
  63912. return this._intersectionThreshold;
  63913. },
  63914. /**
  63915. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  63916. * This margin is expressed in world space coordinates, so its value may vary.
  63917. */
  63918. set: function (value) {
  63919. if (this._intersectionThreshold === value) {
  63920. return;
  63921. }
  63922. this._intersectionThreshold = value;
  63923. if (this.geometry) {
  63924. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  63925. }
  63926. },
  63927. enumerable: true,
  63928. configurable: true
  63929. });
  63930. /**
  63931. * Returns the string "LineMesh"
  63932. */
  63933. LinesMesh.prototype.getClassName = function () {
  63934. return "LinesMesh";
  63935. };
  63936. Object.defineProperty(LinesMesh.prototype, "material", {
  63937. /**
  63938. * @hidden
  63939. */
  63940. get: function () {
  63941. return this._colorShader;
  63942. },
  63943. /**
  63944. * @hidden
  63945. */
  63946. set: function (value) {
  63947. // Do nothing
  63948. },
  63949. enumerable: true,
  63950. configurable: true
  63951. });
  63952. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  63953. /**
  63954. * @hidden
  63955. */
  63956. get: function () {
  63957. return false;
  63958. },
  63959. enumerable: true,
  63960. configurable: true
  63961. });
  63962. /** @hidden */
  63963. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  63964. if (!this._geometry) {
  63965. return this;
  63966. }
  63967. // VBOs
  63968. this._geometry._bind(this._colorShader.getEffect());
  63969. // Color
  63970. if (!this.useVertexColor) {
  63971. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  63972. }
  63973. return this;
  63974. };
  63975. /** @hidden */
  63976. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  63977. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  63978. return this;
  63979. }
  63980. var engine = this.getScene().getEngine();
  63981. // Draw order
  63982. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  63983. return this;
  63984. };
  63985. /**
  63986. * Disposes of the line mesh
  63987. * @param doNotRecurse If children should be disposed
  63988. */
  63989. LinesMesh.prototype.dispose = function (doNotRecurse) {
  63990. this._colorShader.dispose();
  63991. _super.prototype.dispose.call(this, doNotRecurse);
  63992. };
  63993. /**
  63994. * Returns a new LineMesh object cloned from the current one.
  63995. */
  63996. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  63997. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  63998. };
  63999. return LinesMesh;
  64000. }(BABYLON.Mesh));
  64001. BABYLON.LinesMesh = LinesMesh;
  64002. })(BABYLON || (BABYLON = {}));
  64003. //# sourceMappingURL=babylon.linesMesh.js.map
  64004. var BABYLON;
  64005. (function (BABYLON) {
  64006. /**
  64007. * This class implement a typical dictionary using a string as key and the generic type T as value.
  64008. * The underlying implementation relies on an associative array to ensure the best performances.
  64009. * The value can be anything including 'null' but except 'undefined'
  64010. */
  64011. var StringDictionary = /** @class */ (function () {
  64012. function StringDictionary() {
  64013. this._count = 0;
  64014. this._data = {};
  64015. }
  64016. /**
  64017. * This will clear this dictionary and copy the content from the 'source' one.
  64018. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  64019. * @param source the dictionary to take the content from and copy to this dictionary
  64020. */
  64021. StringDictionary.prototype.copyFrom = function (source) {
  64022. var _this = this;
  64023. this.clear();
  64024. source.forEach(function (t, v) { return _this.add(t, v); });
  64025. };
  64026. /**
  64027. * Get a value based from its key
  64028. * @param key the given key to get the matching value from
  64029. * @return the value if found, otherwise undefined is returned
  64030. */
  64031. StringDictionary.prototype.get = function (key) {
  64032. var val = this._data[key];
  64033. if (val !== undefined) {
  64034. return val;
  64035. }
  64036. return undefined;
  64037. };
  64038. /**
  64039. * Get a value from its key or add it if it doesn't exist.
  64040. * This method will ensure you that a given key/data will be present in the dictionary.
  64041. * @param key the given key to get the matching value from
  64042. * @param factory the factory that will create the value if the key is not present in the dictionary.
  64043. * The factory will only be invoked if there's no data for the given key.
  64044. * @return the value corresponding to the key.
  64045. */
  64046. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  64047. var val = this.get(key);
  64048. if (val !== undefined) {
  64049. return val;
  64050. }
  64051. val = factory(key);
  64052. if (val) {
  64053. this.add(key, val);
  64054. }
  64055. return val;
  64056. };
  64057. /**
  64058. * Get a value from its key if present in the dictionary otherwise add it
  64059. * @param key the key to get the value from
  64060. * @param val if there's no such key/value pair in the dictionary add it with this value
  64061. * @return the value corresponding to the key
  64062. */
  64063. StringDictionary.prototype.getOrAdd = function (key, val) {
  64064. var curVal = this.get(key);
  64065. if (curVal !== undefined) {
  64066. return curVal;
  64067. }
  64068. this.add(key, val);
  64069. return val;
  64070. };
  64071. /**
  64072. * Check if there's a given key in the dictionary
  64073. * @param key the key to check for
  64074. * @return true if the key is present, false otherwise
  64075. */
  64076. StringDictionary.prototype.contains = function (key) {
  64077. return this._data[key] !== undefined;
  64078. };
  64079. /**
  64080. * Add a new key and its corresponding value
  64081. * @param key the key to add
  64082. * @param value the value corresponding to the key
  64083. * @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
  64084. */
  64085. StringDictionary.prototype.add = function (key, value) {
  64086. if (this._data[key] !== undefined) {
  64087. return false;
  64088. }
  64089. this._data[key] = value;
  64090. ++this._count;
  64091. return true;
  64092. };
  64093. /**
  64094. * Update a specific value associated to a key
  64095. * @param key defines the key to use
  64096. * @param value defines the value to store
  64097. * @returns true if the value was updated (or false if the key was not found)
  64098. */
  64099. StringDictionary.prototype.set = function (key, value) {
  64100. if (this._data[key] === undefined) {
  64101. return false;
  64102. }
  64103. this._data[key] = value;
  64104. return true;
  64105. };
  64106. /**
  64107. * Get the element of the given key and remove it from the dictionary
  64108. * @param key defines the key to search
  64109. * @returns the value associated with the key or null if not found
  64110. */
  64111. StringDictionary.prototype.getAndRemove = function (key) {
  64112. var val = this.get(key);
  64113. if (val !== undefined) {
  64114. delete this._data[key];
  64115. --this._count;
  64116. return val;
  64117. }
  64118. return null;
  64119. };
  64120. /**
  64121. * Remove a key/value from the dictionary.
  64122. * @param key the key to remove
  64123. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  64124. */
  64125. StringDictionary.prototype.remove = function (key) {
  64126. if (this.contains(key)) {
  64127. delete this._data[key];
  64128. --this._count;
  64129. return true;
  64130. }
  64131. return false;
  64132. };
  64133. /**
  64134. * Clear the whole content of the dictionary
  64135. */
  64136. StringDictionary.prototype.clear = function () {
  64137. this._data = {};
  64138. this._count = 0;
  64139. };
  64140. Object.defineProperty(StringDictionary.prototype, "count", {
  64141. /**
  64142. * Gets the current count
  64143. */
  64144. get: function () {
  64145. return this._count;
  64146. },
  64147. enumerable: true,
  64148. configurable: true
  64149. });
  64150. /**
  64151. * Execute a callback on each key/val of the dictionary.
  64152. * Note that you can remove any element in this dictionary in the callback implementation
  64153. * @param callback the callback to execute on a given key/value pair
  64154. */
  64155. StringDictionary.prototype.forEach = function (callback) {
  64156. for (var cur in this._data) {
  64157. var val = this._data[cur];
  64158. callback(cur, val);
  64159. }
  64160. };
  64161. /**
  64162. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  64163. * If the callback returns null or undefined the method will iterate to the next key/value pair
  64164. * Note that you can remove any element in this dictionary in the callback implementation
  64165. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  64166. * @returns the first item
  64167. */
  64168. StringDictionary.prototype.first = function (callback) {
  64169. for (var cur in this._data) {
  64170. var val = this._data[cur];
  64171. var res = callback(cur, val);
  64172. if (res) {
  64173. return res;
  64174. }
  64175. }
  64176. return null;
  64177. };
  64178. return StringDictionary;
  64179. }());
  64180. BABYLON.StringDictionary = StringDictionary;
  64181. })(BABYLON || (BABYLON = {}));
  64182. //# sourceMappingURL=babylon.stringDictionary.js.map
  64183. var BABYLON;
  64184. (function (BABYLON) {
  64185. var Debug;
  64186. (function (Debug) {
  64187. /**
  64188. * Class used to render a debug view of a given skeleton
  64189. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  64190. */
  64191. var SkeletonViewer = /** @class */ (function () {
  64192. /**
  64193. * Creates a new SkeletonViewer
  64194. * @param skeleton defines the skeleton to render
  64195. * @param mesh defines the mesh attached to the skeleton
  64196. * @param scene defines the hosting scene
  64197. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  64198. * @param renderingGroupId defines the rendering group id to use with the viewer
  64199. */
  64200. function SkeletonViewer(
  64201. /** defines the skeleton to render */
  64202. skeleton,
  64203. /** defines the mesh attached to the skeleton */
  64204. mesh, scene,
  64205. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  64206. autoUpdateBonesMatrices,
  64207. /** defines the rendering group id to use with the viewer */
  64208. renderingGroupId) {
  64209. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  64210. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  64211. this.skeleton = skeleton;
  64212. this.mesh = mesh;
  64213. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  64214. this.renderingGroupId = renderingGroupId;
  64215. /** Gets or sets the color used to render the skeleton */
  64216. this.color = BABYLON.Color3.White();
  64217. this._debugLines = new Array();
  64218. this._isEnabled = false;
  64219. this._scene = scene;
  64220. this.update();
  64221. this._renderFunction = this.update.bind(this);
  64222. }
  64223. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  64224. get: function () {
  64225. return this._isEnabled;
  64226. },
  64227. /** Gets or sets a boolean indicating if the viewer is enabled */
  64228. set: function (value) {
  64229. if (this._isEnabled === value) {
  64230. return;
  64231. }
  64232. this._isEnabled = value;
  64233. if (value) {
  64234. this._scene.registerBeforeRender(this._renderFunction);
  64235. }
  64236. else {
  64237. this._scene.unregisterBeforeRender(this._renderFunction);
  64238. }
  64239. },
  64240. enumerable: true,
  64241. configurable: true
  64242. });
  64243. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  64244. if (x === void 0) { x = 0; }
  64245. if (y === void 0) { y = 0; }
  64246. if (z === void 0) { z = 0; }
  64247. var tmat = BABYLON.Tmp.Matrix[0];
  64248. var parentBone = bone.getParent();
  64249. tmat.copyFrom(bone.getLocalMatrix());
  64250. if (x !== 0 || y !== 0 || z !== 0) {
  64251. var tmat2 = BABYLON.Tmp.Matrix[1];
  64252. BABYLON.Matrix.IdentityToRef(tmat2);
  64253. tmat2.m[12] = x;
  64254. tmat2.m[13] = y;
  64255. tmat2.m[14] = z;
  64256. tmat2.multiplyToRef(tmat, tmat);
  64257. }
  64258. if (parentBone) {
  64259. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  64260. }
  64261. tmat.multiplyToRef(meshMat, tmat);
  64262. position.x = tmat.m[12];
  64263. position.y = tmat.m[13];
  64264. position.z = tmat.m[14];
  64265. };
  64266. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  64267. var len = bones.length;
  64268. var meshPos = this.mesh.position;
  64269. for (var i = 0; i < len; i++) {
  64270. var bone = bones[i];
  64271. var points = this._debugLines[i];
  64272. if (!points) {
  64273. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64274. this._debugLines[i] = points;
  64275. }
  64276. this._getBonePosition(points[0], bone, meshMat);
  64277. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  64278. points[0].subtractInPlace(meshPos);
  64279. points[1].subtractInPlace(meshPos);
  64280. }
  64281. };
  64282. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  64283. var len = bones.length;
  64284. var boneNum = 0;
  64285. var meshPos = this.mesh.position;
  64286. for (var i = len - 1; i >= 0; i--) {
  64287. var childBone = bones[i];
  64288. var parentBone = childBone.getParent();
  64289. if (!parentBone) {
  64290. continue;
  64291. }
  64292. var points = this._debugLines[boneNum];
  64293. if (!points) {
  64294. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64295. this._debugLines[boneNum] = points;
  64296. }
  64297. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  64298. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  64299. points[0].subtractInPlace(meshPos);
  64300. points[1].subtractInPlace(meshPos);
  64301. boneNum++;
  64302. }
  64303. };
  64304. /** Update the viewer to sync with current skeleton state */
  64305. SkeletonViewer.prototype.update = function () {
  64306. if (this.autoUpdateBonesMatrices) {
  64307. this.skeleton.computeAbsoluteTransforms();
  64308. }
  64309. if (this.skeleton.bones[0].length === undefined) {
  64310. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  64311. }
  64312. else {
  64313. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  64314. }
  64315. if (!this._debugMesh) {
  64316. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  64317. this._debugMesh.renderingGroupId = this.renderingGroupId;
  64318. }
  64319. else {
  64320. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  64321. }
  64322. this._debugMesh.position.copyFrom(this.mesh.position);
  64323. this._debugMesh.color = this.color;
  64324. };
  64325. /** Release associated resources */
  64326. SkeletonViewer.prototype.dispose = function () {
  64327. if (this._debugMesh) {
  64328. this.isEnabled = false;
  64329. this._debugMesh.dispose();
  64330. this._debugMesh = null;
  64331. }
  64332. };
  64333. return SkeletonViewer;
  64334. }());
  64335. Debug.SkeletonViewer = SkeletonViewer;
  64336. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64337. })(BABYLON || (BABYLON = {}));
  64338. //# sourceMappingURL=babylon.skeletonViewer.js.map
  64339. /**
  64340. * Module Debug contains the (visual) components to debug a scene correctly
  64341. */
  64342. var BABYLON;
  64343. (function (BABYLON) {
  64344. var Debug;
  64345. (function (Debug) {
  64346. /**
  64347. * The Axes viewer will show 3 axes in a specific point in space
  64348. */
  64349. var AxesViewer = /** @class */ (function () {
  64350. /**
  64351. * Creates a new AxesViewer
  64352. * @param scene defines the hosting scene
  64353. * @param scaleLines defines a number used to scale line length (1 by default)
  64354. */
  64355. function AxesViewer(scene, scaleLines) {
  64356. if (scaleLines === void 0) { scaleLines = 1; }
  64357. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64358. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64359. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64360. /**
  64361. * Gets or sets a number used to scale line length
  64362. */
  64363. this.scaleLines = 1;
  64364. this.scaleLines = scaleLines;
  64365. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  64366. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  64367. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  64368. this._xmesh.renderingGroupId = 2;
  64369. this._ymesh.renderingGroupId = 2;
  64370. this._zmesh.renderingGroupId = 2;
  64371. this._xmesh.material.checkReadyOnlyOnce = true;
  64372. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  64373. this._ymesh.material.checkReadyOnlyOnce = true;
  64374. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  64375. this._zmesh.material.checkReadyOnlyOnce = true;
  64376. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  64377. this.scene = scene;
  64378. }
  64379. /**
  64380. * Force the viewer to update
  64381. * @param position defines the position of the viewer
  64382. * @param xaxis defines the x axis of the viewer
  64383. * @param yaxis defines the y axis of the viewer
  64384. * @param zaxis defines the z axis of the viewer
  64385. */
  64386. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  64387. var scaleLines = this.scaleLines;
  64388. if (this._xmesh) {
  64389. this._xmesh.position.copyFrom(position);
  64390. }
  64391. if (this._ymesh) {
  64392. this._ymesh.position.copyFrom(position);
  64393. }
  64394. if (this._zmesh) {
  64395. this._zmesh.position.copyFrom(position);
  64396. }
  64397. var point2 = this._xline[1];
  64398. point2.x = xaxis.x * scaleLines;
  64399. point2.y = xaxis.y * scaleLines;
  64400. point2.z = xaxis.z * scaleLines;
  64401. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  64402. point2 = this._yline[1];
  64403. point2.x = yaxis.x * scaleLines;
  64404. point2.y = yaxis.y * scaleLines;
  64405. point2.z = yaxis.z * scaleLines;
  64406. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  64407. point2 = this._zline[1];
  64408. point2.x = zaxis.x * scaleLines;
  64409. point2.y = zaxis.y * scaleLines;
  64410. point2.z = zaxis.z * scaleLines;
  64411. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  64412. };
  64413. /** Releases resources */
  64414. AxesViewer.prototype.dispose = function () {
  64415. if (this._xmesh) {
  64416. this._xmesh.dispose();
  64417. }
  64418. if (this._ymesh) {
  64419. this._ymesh.dispose();
  64420. }
  64421. if (this._zmesh) {
  64422. this._zmesh.dispose();
  64423. }
  64424. this._xmesh = null;
  64425. this._ymesh = null;
  64426. this._zmesh = null;
  64427. this.scene = null;
  64428. };
  64429. return AxesViewer;
  64430. }());
  64431. Debug.AxesViewer = AxesViewer;
  64432. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64433. })(BABYLON || (BABYLON = {}));
  64434. //# sourceMappingURL=babylon.axesViewer.js.map
  64435. var BABYLON;
  64436. (function (BABYLON) {
  64437. var Debug;
  64438. (function (Debug) {
  64439. /**
  64440. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  64441. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  64442. */
  64443. var BoneAxesViewer = /** @class */ (function (_super) {
  64444. __extends(BoneAxesViewer, _super);
  64445. /**
  64446. * Creates a new BoneAxesViewer
  64447. * @param scene defines the hosting scene
  64448. * @param bone defines the target bone
  64449. * @param mesh defines the target mesh
  64450. * @param scaleLines defines a scaling factor for line length (1 by default)
  64451. */
  64452. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  64453. if (scaleLines === void 0) { scaleLines = 1; }
  64454. var _this = _super.call(this, scene, scaleLines) || this;
  64455. /** Gets current position */
  64456. _this.pos = BABYLON.Vector3.Zero();
  64457. /** Gets direction of X axis */
  64458. _this.xaxis = BABYLON.Vector3.Zero();
  64459. /** Gets direction of Y axis */
  64460. _this.yaxis = BABYLON.Vector3.Zero();
  64461. /** Gets direction of Z axis */
  64462. _this.zaxis = BABYLON.Vector3.Zero();
  64463. _this.mesh = mesh;
  64464. _this.bone = bone;
  64465. return _this;
  64466. }
  64467. /**
  64468. * Force the viewer to update
  64469. */
  64470. BoneAxesViewer.prototype.update = function () {
  64471. if (!this.mesh || !this.bone) {
  64472. return;
  64473. }
  64474. var bone = this.bone;
  64475. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  64476. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  64477. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  64478. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  64479. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  64480. };
  64481. /** Releases resources */
  64482. BoneAxesViewer.prototype.dispose = function () {
  64483. if (this.mesh) {
  64484. this.mesh = null;
  64485. this.bone = null;
  64486. _super.prototype.dispose.call(this);
  64487. }
  64488. };
  64489. return BoneAxesViewer;
  64490. }(Debug.AxesViewer));
  64491. Debug.BoneAxesViewer = BoneAxesViewer;
  64492. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64493. })(BABYLON || (BABYLON = {}));
  64494. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  64495. var BABYLON;
  64496. (function (BABYLON) {
  64497. /**
  64498. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  64499. * in order to better appreciate the issue one might have.
  64500. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  64501. */
  64502. var RayHelper = /** @class */ (function () {
  64503. /**
  64504. * Instantiate a new ray helper.
  64505. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  64506. * in order to better appreciate the issue one might have.
  64507. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  64508. * @param ray Defines the ray we are currently tryin to visualize
  64509. */
  64510. function RayHelper(ray) {
  64511. this.ray = ray;
  64512. }
  64513. /**
  64514. * Helper function to create a colored helper in a scene in one line.
  64515. * @param ray Defines the ray we are currently tryin to visualize
  64516. * @param scene Defines the scene the ray is used in
  64517. * @param color Defines the color we want to see the ray in
  64518. * @returns The newly created ray helper.
  64519. */
  64520. RayHelper.CreateAndShow = function (ray, scene, color) {
  64521. var helper = new RayHelper(ray);
  64522. helper.show(scene, color);
  64523. return helper;
  64524. };
  64525. /**
  64526. * Shows the ray we are willing to debug.
  64527. * @param scene Defines the scene the ray needs to be rendered in
  64528. * @param color Defines the color the ray needs to be rendered in
  64529. */
  64530. RayHelper.prototype.show = function (scene, color) {
  64531. if (!this._renderFunction && this.ray) {
  64532. var ray = this.ray;
  64533. this._renderFunction = this._render.bind(this);
  64534. this._scene = scene;
  64535. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  64536. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  64537. if (this._renderFunction) {
  64538. this._scene.registerBeforeRender(this._renderFunction);
  64539. }
  64540. }
  64541. if (color && this._renderLine) {
  64542. this._renderLine.color.copyFrom(color);
  64543. }
  64544. };
  64545. /**
  64546. * Hides the ray we are debugging.
  64547. */
  64548. RayHelper.prototype.hide = function () {
  64549. if (this._renderFunction && this._scene) {
  64550. this._scene.unregisterBeforeRender(this._renderFunction);
  64551. this._scene = null;
  64552. this._renderFunction = null;
  64553. if (this._renderLine) {
  64554. this._renderLine.dispose();
  64555. this._renderLine = null;
  64556. }
  64557. this._renderPoints = [];
  64558. }
  64559. };
  64560. RayHelper.prototype._render = function () {
  64561. var ray = this.ray;
  64562. if (!ray) {
  64563. return;
  64564. }
  64565. var point = this._renderPoints[1];
  64566. var len = Math.min(ray.length, 1000000);
  64567. point.copyFrom(ray.direction);
  64568. point.scaleInPlace(len);
  64569. point.addInPlace(ray.origin);
  64570. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  64571. };
  64572. /**
  64573. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  64574. * @param mesh Defines the mesh we want the helper attached to
  64575. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  64576. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  64577. * @param length Defines the length of the ray
  64578. */
  64579. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  64580. this._attachedToMesh = mesh;
  64581. var ray = this.ray;
  64582. if (!ray) {
  64583. return;
  64584. }
  64585. if (!ray.direction) {
  64586. ray.direction = BABYLON.Vector3.Zero();
  64587. }
  64588. if (!ray.origin) {
  64589. ray.origin = BABYLON.Vector3.Zero();
  64590. }
  64591. if (length) {
  64592. ray.length = length;
  64593. }
  64594. if (!meshSpaceOrigin) {
  64595. meshSpaceOrigin = BABYLON.Vector3.Zero();
  64596. }
  64597. if (!meshSpaceDirection) {
  64598. // -1 so that this will work with Mesh.lookAt
  64599. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  64600. }
  64601. if (!this._meshSpaceDirection) {
  64602. this._meshSpaceDirection = meshSpaceDirection.clone();
  64603. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  64604. }
  64605. else {
  64606. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  64607. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  64608. }
  64609. if (!this._updateToMeshFunction) {
  64610. this._updateToMeshFunction = this._updateToMesh.bind(this);
  64611. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  64612. }
  64613. this._updateToMesh();
  64614. };
  64615. /**
  64616. * Detach the ray helper from the mesh it has previously been attached to.
  64617. */
  64618. RayHelper.prototype.detachFromMesh = function () {
  64619. if (this._attachedToMesh) {
  64620. if (this._updateToMeshFunction) {
  64621. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  64622. }
  64623. this._attachedToMesh = null;
  64624. this._updateToMeshFunction = null;
  64625. }
  64626. };
  64627. RayHelper.prototype._updateToMesh = function () {
  64628. var ray = this.ray;
  64629. if (!this._attachedToMesh || !ray) {
  64630. return;
  64631. }
  64632. if (this._attachedToMesh._isDisposed) {
  64633. this.detachFromMesh();
  64634. return;
  64635. }
  64636. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  64637. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  64638. };
  64639. /**
  64640. * Dispose the helper and release its associated resources.
  64641. */
  64642. RayHelper.prototype.dispose = function () {
  64643. this.hide();
  64644. this.detachFromMesh();
  64645. this.ray = null;
  64646. };
  64647. return RayHelper;
  64648. }());
  64649. BABYLON.RayHelper = RayHelper;
  64650. })(BABYLON || (BABYLON = {}));
  64651. //# sourceMappingURL=babylon.rayHelper.js.map
  64652. var BABYLON;
  64653. (function (BABYLON) {
  64654. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  64655. get: function () {
  64656. if (!this._debugLayer) {
  64657. this._debugLayer = new DebugLayer(this);
  64658. }
  64659. return this._debugLayer;
  64660. },
  64661. enumerable: true,
  64662. configurable: true
  64663. });
  64664. /**
  64665. * The debug layer (aka Inspector) is the go to tool in order to better understand
  64666. * what is happening in your scene
  64667. * @see http://doc.babylonjs.com/features/playground_debuglayer
  64668. */
  64669. var DebugLayer = /** @class */ (function () {
  64670. /**
  64671. * Instantiates a new debug layer.
  64672. * The debug layer (aka Inspector) is the go to tool in order to better understand
  64673. * what is happening in your scene
  64674. * @see http://doc.babylonjs.com/features/playground_debuglayer
  64675. * @param scene Defines the scene to inspect
  64676. */
  64677. function DebugLayer(scene) {
  64678. var _this = this;
  64679. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  64680. /**
  64681. * Observable triggered when a property is changed through the inspector.
  64682. */
  64683. this.onPropertyChangedObservable = new BABYLON.Observable();
  64684. this._scene = scene;
  64685. this._scene.onDisposeObservable.add(function () {
  64686. // Debug layer
  64687. if (_this._scene._debugLayer) {
  64688. _this._scene._debugLayer.hide();
  64689. }
  64690. });
  64691. }
  64692. /** Creates the inspector window. */
  64693. DebugLayer.prototype._createInspector = function (config) {
  64694. if (config === void 0) { config = {}; }
  64695. var popup = config.popup || false;
  64696. var initialTab = config.initialTab || 0;
  64697. var parentElement = config.parentElement || null;
  64698. if (!this._inspector) {
  64699. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  64700. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  64701. } // else nothing to do as instance is already created
  64702. };
  64703. /**
  64704. * Get if the inspector is visible or not.
  64705. * @returns true if visible otherwise, false
  64706. */
  64707. DebugLayer.prototype.isVisible = function () {
  64708. if (!this._inspector) {
  64709. return false;
  64710. }
  64711. return true;
  64712. };
  64713. /**
  64714. * Hide the inspector and close its window.
  64715. */
  64716. DebugLayer.prototype.hide = function () {
  64717. if (this._inspector) {
  64718. try {
  64719. this._inspector.dispose();
  64720. }
  64721. catch (e) {
  64722. // If the inspector has been removed directly from the inspector tool
  64723. }
  64724. this.onPropertyChangedObservable.clear();
  64725. this._inspector = null;
  64726. }
  64727. };
  64728. /**
  64729. *
  64730. * Launch the debugLayer.
  64731. *
  64732. * initialTab:
  64733. * | Value | Tab Name |
  64734. * | --- | --- |
  64735. * | 0 | Scene |
  64736. * | 1 | Console |
  64737. * | 2 | Stats |
  64738. * | 3 | Textures |
  64739. * | 4 | Mesh |
  64740. * | 5 | Light |
  64741. * | 6 | Material |
  64742. * | 7 | GLTF |
  64743. * | 8 | GUI |
  64744. * | 9 | Physics |
  64745. * | 10 | Camera |
  64746. * | 11 | Audio |
  64747. *
  64748. * @param config Define the configuration of the inspector
  64749. */
  64750. DebugLayer.prototype.show = function (config) {
  64751. if (config === void 0) { config = {}; }
  64752. if (typeof this.BJSINSPECTOR == 'undefined') {
  64753. // Load inspector and add it to the DOM
  64754. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  64755. }
  64756. else {
  64757. // Otherwise creates the inspector
  64758. this._createInspector(config);
  64759. }
  64760. };
  64761. /**
  64762. * Gets the active tab
  64763. * @return the index of the active tab or -1 if the inspector is hidden
  64764. */
  64765. DebugLayer.prototype.getActiveTab = function () {
  64766. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  64767. };
  64768. /**
  64769. * Define the url to get the inspector script from.
  64770. * By default it uses the babylonjs CDN.
  64771. * @ignoreNaming
  64772. */
  64773. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  64774. return DebugLayer;
  64775. }());
  64776. BABYLON.DebugLayer = DebugLayer;
  64777. })(BABYLON || (BABYLON = {}));
  64778. //# sourceMappingURL=babylon.debugLayer.js.map
  64779. var BABYLON;
  64780. (function (BABYLON) {
  64781. var Debug;
  64782. (function (Debug) {
  64783. /**
  64784. * Used to show the physics impostor around the specific mesh
  64785. */
  64786. var PhysicsViewer = /** @class */ (function () {
  64787. /**
  64788. * Creates a new PhysicsViewer
  64789. * @param scene defines the hosting scene
  64790. */
  64791. function PhysicsViewer(scene) {
  64792. /** @hidden */
  64793. this._impostors = [];
  64794. /** @hidden */
  64795. this._meshes = [];
  64796. /** @hidden */
  64797. this._numMeshes = 0;
  64798. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64799. var physicEngine = this._scene.getPhysicsEngine();
  64800. if (physicEngine) {
  64801. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  64802. }
  64803. }
  64804. /** @hidden */
  64805. PhysicsViewer.prototype._updateDebugMeshes = function () {
  64806. var plugin = this._physicsEnginePlugin;
  64807. for (var i = 0; i < this._numMeshes; i++) {
  64808. var impostor = this._impostors[i];
  64809. if (!impostor) {
  64810. continue;
  64811. }
  64812. if (impostor.isDisposed) {
  64813. this.hideImpostor(this._impostors[i--]);
  64814. }
  64815. else {
  64816. var mesh = this._meshes[i];
  64817. if (mesh && plugin) {
  64818. plugin.syncMeshWithImpostor(mesh, impostor);
  64819. }
  64820. }
  64821. }
  64822. };
  64823. /**
  64824. * Renders a specified physic impostor
  64825. * @param impostor defines the impostor to render
  64826. */
  64827. PhysicsViewer.prototype.showImpostor = function (impostor) {
  64828. if (!this._scene) {
  64829. return;
  64830. }
  64831. for (var i = 0; i < this._numMeshes; i++) {
  64832. if (this._impostors[i] == impostor) {
  64833. return;
  64834. }
  64835. }
  64836. var debugMesh = this._getDebugMesh(impostor, this._scene);
  64837. if (debugMesh) {
  64838. this._impostors[this._numMeshes] = impostor;
  64839. this._meshes[this._numMeshes] = debugMesh;
  64840. if (this._numMeshes === 0) {
  64841. this._renderFunction = this._updateDebugMeshes.bind(this);
  64842. this._scene.registerBeforeRender(this._renderFunction);
  64843. }
  64844. this._numMeshes++;
  64845. }
  64846. };
  64847. /**
  64848. * Hides a specified physic impostor
  64849. * @param impostor defines the impostor to hide
  64850. */
  64851. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  64852. if (!impostor || !this._scene) {
  64853. return;
  64854. }
  64855. var removed = false;
  64856. for (var i = 0; i < this._numMeshes; i++) {
  64857. if (this._impostors[i] == impostor) {
  64858. var mesh = this._meshes[i];
  64859. if (!mesh) {
  64860. continue;
  64861. }
  64862. this._scene.removeMesh(mesh);
  64863. mesh.dispose();
  64864. this._numMeshes--;
  64865. if (this._numMeshes > 0) {
  64866. this._meshes[i] = this._meshes[this._numMeshes];
  64867. this._impostors[i] = this._impostors[this._numMeshes];
  64868. this._meshes[this._numMeshes] = null;
  64869. this._impostors[this._numMeshes] = null;
  64870. }
  64871. else {
  64872. this._meshes[0] = null;
  64873. this._impostors[0] = null;
  64874. }
  64875. removed = true;
  64876. break;
  64877. }
  64878. }
  64879. if (removed && this._numMeshes === 0) {
  64880. this._scene.unregisterBeforeRender(this._renderFunction);
  64881. }
  64882. };
  64883. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  64884. if (!this._debugMaterial) {
  64885. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  64886. this._debugMaterial.wireframe = true;
  64887. }
  64888. return this._debugMaterial;
  64889. };
  64890. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  64891. if (!this._debugBoxMesh) {
  64892. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  64893. this._debugBoxMesh.renderingGroupId = 1;
  64894. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  64895. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  64896. scene.removeMesh(this._debugBoxMesh);
  64897. }
  64898. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  64899. };
  64900. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  64901. if (!this._debugSphereMesh) {
  64902. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  64903. this._debugSphereMesh.renderingGroupId = 1;
  64904. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  64905. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  64906. scene.removeMesh(this._debugSphereMesh);
  64907. }
  64908. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  64909. };
  64910. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  64911. var mesh = null;
  64912. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  64913. mesh = this._getDebugBoxMesh(scene);
  64914. impostor.getBoxSizeToRef(mesh.scaling);
  64915. }
  64916. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  64917. mesh = this._getDebugSphereMesh(scene);
  64918. var radius = impostor.getRadius();
  64919. mesh.scaling.x = radius * 2;
  64920. mesh.scaling.y = radius * 2;
  64921. mesh.scaling.z = radius * 2;
  64922. }
  64923. return mesh;
  64924. };
  64925. /** Releases all resources */
  64926. PhysicsViewer.prototype.dispose = function () {
  64927. for (var i = 0; i < this._numMeshes; i++) {
  64928. this.hideImpostor(this._impostors[i]);
  64929. }
  64930. if (this._debugBoxMesh) {
  64931. this._debugBoxMesh.dispose();
  64932. }
  64933. if (this._debugSphereMesh) {
  64934. this._debugSphereMesh.dispose();
  64935. }
  64936. if (this._debugMaterial) {
  64937. this._debugMaterial.dispose();
  64938. }
  64939. this._impostors.length = 0;
  64940. this._scene = null;
  64941. this._physicsEnginePlugin = null;
  64942. };
  64943. return PhysicsViewer;
  64944. }());
  64945. Debug.PhysicsViewer = PhysicsViewer;
  64946. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64947. })(BABYLON || (BABYLON = {}));
  64948. //# sourceMappingURL=babylon.physicsViewer.js.map
  64949. var BABYLON;
  64950. (function (BABYLON) {
  64951. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  64952. get: function () {
  64953. return this._forceShowBoundingBoxes || false;
  64954. },
  64955. set: function (value) {
  64956. this._forceShowBoundingBoxes = value;
  64957. // Lazyly creates a BB renderer if needed.
  64958. if (value) {
  64959. this.getBoundingBoxRenderer();
  64960. }
  64961. },
  64962. enumerable: true,
  64963. configurable: true
  64964. });
  64965. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  64966. if (!this._boundingBoxRenderer) {
  64967. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  64968. }
  64969. return this._boundingBoxRenderer;
  64970. };
  64971. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  64972. get: function () {
  64973. return this._showBoundingBox || false;
  64974. },
  64975. set: function (value) {
  64976. this._showBoundingBox = value;
  64977. // Lazyly creates a BB renderer if needed.
  64978. if (value) {
  64979. this.getScene().getBoundingBoxRenderer();
  64980. }
  64981. },
  64982. enumerable: true,
  64983. configurable: true
  64984. });
  64985. /**
  64986. * Component responsible of rendering the bounding box of the meshes in a scene.
  64987. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  64988. */
  64989. var BoundingBoxRenderer = /** @class */ (function () {
  64990. /**
  64991. * Instantiates a new bounding box renderer in a scene.
  64992. * @param scene the scene the renderer renders in
  64993. */
  64994. function BoundingBoxRenderer(scene) {
  64995. /**
  64996. * The component name helpfull to identify the component in the list of scene components.
  64997. */
  64998. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  64999. /**
  65000. * Color of the bounding box lines placed in front of an object
  65001. */
  65002. this.frontColor = new BABYLON.Color3(1, 1, 1);
  65003. /**
  65004. * Color of the bounding box lines placed behind an object
  65005. */
  65006. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  65007. /**
  65008. * Defines if the renderer should show the back lines or not
  65009. */
  65010. this.showBackLines = true;
  65011. /**
  65012. * @hidden
  65013. */
  65014. this.renderList = new BABYLON.SmartArray(32);
  65015. this._vertexBuffers = {};
  65016. this.scene = scene;
  65017. scene._addComponent(this);
  65018. }
  65019. /**
  65020. * Registers the component in a given scene
  65021. */
  65022. BoundingBoxRenderer.prototype.register = function () {
  65023. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  65024. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  65025. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  65026. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  65027. };
  65028. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  65029. if (mesh.showSubMeshesBoundingBox) {
  65030. var boundingInfo = subMesh.getBoundingInfo();
  65031. if (boundingInfo !== null && boundingInfo !== undefined) {
  65032. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  65033. this.renderList.push(boundingInfo.boundingBox);
  65034. }
  65035. }
  65036. };
  65037. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  65038. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  65039. var boundingInfo = sourceMesh.getBoundingInfo();
  65040. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  65041. this.renderList.push(boundingInfo.boundingBox);
  65042. }
  65043. };
  65044. BoundingBoxRenderer.prototype._prepareRessources = function () {
  65045. if (this._colorShader) {
  65046. return;
  65047. }
  65048. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  65049. attributes: [BABYLON.VertexBuffer.PositionKind],
  65050. uniforms: ["world", "viewProjection", "color"]
  65051. });
  65052. var engine = this.scene.getEngine();
  65053. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  65054. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  65055. this._createIndexBuffer();
  65056. };
  65057. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  65058. var engine = this.scene.getEngine();
  65059. 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]);
  65060. };
  65061. /**
  65062. * Rebuilds the elements related to this component in case of
  65063. * context lost for instance.
  65064. */
  65065. BoundingBoxRenderer.prototype.rebuild = function () {
  65066. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65067. if (vb) {
  65068. vb._rebuild();
  65069. }
  65070. this._createIndexBuffer();
  65071. };
  65072. /**
  65073. * @hidden
  65074. */
  65075. BoundingBoxRenderer.prototype.reset = function () {
  65076. this.renderList.reset();
  65077. };
  65078. /**
  65079. * Render the bounding boxes of a specific rendering group
  65080. * @param renderingGroupId defines the rendering group to render
  65081. */
  65082. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  65083. if (this.renderList.length === 0) {
  65084. return;
  65085. }
  65086. this._prepareRessources();
  65087. if (!this._colorShader.isReady()) {
  65088. return;
  65089. }
  65090. var engine = this.scene.getEngine();
  65091. engine.setDepthWrite(false);
  65092. this._colorShader._preBind();
  65093. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  65094. var boundingBox = this.renderList.data[boundingBoxIndex];
  65095. if (boundingBox._tag !== renderingGroupId) {
  65096. continue;
  65097. }
  65098. var min = boundingBox.minimum;
  65099. var max = boundingBox.maximum;
  65100. var diff = max.subtract(min);
  65101. var median = min.add(diff.scale(0.5));
  65102. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  65103. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  65104. .multiply(boundingBox.getWorldMatrix());
  65105. // VBOs
  65106. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  65107. if (this.showBackLines) {
  65108. // Back
  65109. engine.setDepthFunctionToGreaterOrEqual();
  65110. this.scene.resetCachedMaterial();
  65111. this._colorShader.setColor4("color", this.backColor.toColor4());
  65112. this._colorShader.bind(worldMatrix);
  65113. // Draw order
  65114. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  65115. }
  65116. // Front
  65117. engine.setDepthFunctionToLess();
  65118. this.scene.resetCachedMaterial();
  65119. this._colorShader.setColor4("color", this.frontColor.toColor4());
  65120. this._colorShader.bind(worldMatrix);
  65121. // Draw order
  65122. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  65123. }
  65124. this._colorShader.unbind();
  65125. engine.setDepthFunctionToLessOrEqual();
  65126. engine.setDepthWrite(true);
  65127. };
  65128. /**
  65129. * In case of occlusion queries, we can render the occlusion bounding box through this method
  65130. * @param mesh Define the mesh to render the occlusion bounding box for
  65131. */
  65132. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  65133. this._prepareRessources();
  65134. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  65135. return;
  65136. }
  65137. var engine = this.scene.getEngine();
  65138. engine.setDepthWrite(false);
  65139. engine.setColorWrite(false);
  65140. this._colorShader._preBind();
  65141. var boundingBox = mesh._boundingInfo.boundingBox;
  65142. var min = boundingBox.minimum;
  65143. var max = boundingBox.maximum;
  65144. var diff = max.subtract(min);
  65145. var median = min.add(diff.scale(0.5));
  65146. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  65147. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  65148. .multiply(boundingBox.getWorldMatrix());
  65149. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  65150. engine.setDepthFunctionToLess();
  65151. this.scene.resetCachedMaterial();
  65152. this._colorShader.bind(worldMatrix);
  65153. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  65154. this._colorShader.unbind();
  65155. engine.setDepthFunctionToLessOrEqual();
  65156. engine.setDepthWrite(true);
  65157. engine.setColorWrite(true);
  65158. };
  65159. /**
  65160. * Dispose and release the resources attached to this renderer.
  65161. */
  65162. BoundingBoxRenderer.prototype.dispose = function () {
  65163. if (!this._colorShader) {
  65164. return;
  65165. }
  65166. this.renderList.dispose();
  65167. this._colorShader.dispose();
  65168. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65169. if (buffer) {
  65170. buffer.dispose();
  65171. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65172. }
  65173. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  65174. };
  65175. return BoundingBoxRenderer;
  65176. }());
  65177. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  65178. })(BABYLON || (BABYLON = {}));
  65179. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  65180. var BABYLON;
  65181. (function (BABYLON) {
  65182. BABYLON.Engine.prototype.createTransformFeedback = function () {
  65183. return this._gl.createTransformFeedback();
  65184. };
  65185. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  65186. this._gl.deleteTransformFeedback(value);
  65187. };
  65188. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  65189. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  65190. };
  65191. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  65192. if (usePoints === void 0) { usePoints = true; }
  65193. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  65194. };
  65195. BABYLON.Engine.prototype.endTransformFeedback = function () {
  65196. this._gl.endTransformFeedback();
  65197. };
  65198. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  65199. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  65200. };
  65201. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  65202. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  65203. };
  65204. })(BABYLON || (BABYLON = {}));
  65205. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  65206. var BABYLON;
  65207. (function (BABYLON) {
  65208. /**
  65209. * This represents a GPU particle system in Babylon
  65210. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  65211. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  65212. */
  65213. var GPUParticleSystem = /** @class */ (function (_super) {
  65214. __extends(GPUParticleSystem, _super);
  65215. /**
  65216. * Instantiates a GPU particle system.
  65217. * 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.
  65218. * @param name The name of the particle system
  65219. * @param options The options used to create the system
  65220. * @param scene The scene the particle system belongs to
  65221. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  65222. */
  65223. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  65224. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  65225. var _this = _super.call(this, name) || this;
  65226. /**
  65227. * The layer mask we are rendering the particles through.
  65228. */
  65229. _this.layerMask = 0x0FFFFFFF;
  65230. _this._accumulatedCount = 0;
  65231. _this._targetIndex = 0;
  65232. _this._currentRenderId = -1;
  65233. _this._started = false;
  65234. _this._stopped = false;
  65235. _this._timeDelta = 0;
  65236. _this._attributesStrideSize = 21;
  65237. _this._actualFrame = 0;
  65238. _this._rawTextureWidth = 256;
  65239. /**
  65240. * An event triggered when the system is disposed.
  65241. */
  65242. _this.onDisposeObservable = new BABYLON.Observable();
  65243. /**
  65244. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  65245. * to override the particles.
  65246. */
  65247. _this.forceDepthWrite = false;
  65248. _this._preWarmDone = false;
  65249. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65250. // Setup the default processing configuration to the scene.
  65251. _this._attachImageProcessingConfiguration(null);
  65252. _this._engine = _this._scene.getEngine();
  65253. if (!options.randomTextureSize) {
  65254. delete options.randomTextureSize;
  65255. }
  65256. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  65257. var optionsAsNumber = options;
  65258. if (isFinite(optionsAsNumber)) {
  65259. fullOptions.capacity = optionsAsNumber;
  65260. }
  65261. _this._capacity = fullOptions.capacity;
  65262. _this._activeCount = fullOptions.capacity;
  65263. _this._currentActiveCount = 0;
  65264. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  65265. _this._scene.particleSystems.push(_this);
  65266. _this._updateEffectOptions = {
  65267. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  65268. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  65269. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  65270. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  65271. uniformBuffersNames: [],
  65272. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  65273. defines: "",
  65274. fallbacks: null,
  65275. onCompiled: null,
  65276. onError: null,
  65277. indexParameters: null,
  65278. maxSimultaneousLights: 0,
  65279. transformFeedbackVaryings: []
  65280. };
  65281. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  65282. // Random data
  65283. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  65284. var d = [];
  65285. for (var i = 0; i < maxTextureSize; ++i) {
  65286. d.push(Math.random());
  65287. d.push(Math.random());
  65288. d.push(Math.random());
  65289. d.push(Math.random());
  65290. }
  65291. _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);
  65292. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65293. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65294. d = [];
  65295. for (var i = 0; i < maxTextureSize; ++i) {
  65296. d.push(Math.random());
  65297. d.push(Math.random());
  65298. d.push(Math.random());
  65299. d.push(Math.random());
  65300. }
  65301. _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);
  65302. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65303. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65304. _this._randomTextureSize = maxTextureSize;
  65305. return _this;
  65306. }
  65307. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  65308. /**
  65309. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  65310. */
  65311. get: function () {
  65312. if (!BABYLON.Engine.LastCreatedEngine) {
  65313. return false;
  65314. }
  65315. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  65316. },
  65317. enumerable: true,
  65318. configurable: true
  65319. });
  65320. /**
  65321. * Gets the maximum number of particles active at the same time.
  65322. * @returns The max number of active particles.
  65323. */
  65324. GPUParticleSystem.prototype.getCapacity = function () {
  65325. return this._capacity;
  65326. };
  65327. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  65328. /**
  65329. * Gets or set the number of active particles
  65330. */
  65331. get: function () {
  65332. return this._activeCount;
  65333. },
  65334. set: function (value) {
  65335. this._activeCount = Math.min(value, this._capacity);
  65336. },
  65337. enumerable: true,
  65338. configurable: true
  65339. });
  65340. /**
  65341. * Is this system ready to be used/rendered
  65342. * @return true if the system is ready
  65343. */
  65344. GPUParticleSystem.prototype.isReady = function () {
  65345. if (!this._updateEffect) {
  65346. this._recreateUpdateEffect();
  65347. this._recreateRenderEffect();
  65348. return false;
  65349. }
  65350. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  65351. return false;
  65352. }
  65353. return true;
  65354. };
  65355. /**
  65356. * Gets if the system has been started. (Note: this will still be true after stop is called)
  65357. * @returns True if it has been started, otherwise false.
  65358. */
  65359. GPUParticleSystem.prototype.isStarted = function () {
  65360. return this._started;
  65361. };
  65362. /**
  65363. * Starts the particle system and begins to emit
  65364. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  65365. */
  65366. GPUParticleSystem.prototype.start = function (delay) {
  65367. var _this = this;
  65368. if (delay === void 0) { delay = this.startDelay; }
  65369. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  65370. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  65371. }
  65372. if (delay) {
  65373. setTimeout(function () {
  65374. _this.start(0);
  65375. }, delay);
  65376. return;
  65377. }
  65378. this._started = true;
  65379. this._stopped = false;
  65380. this._preWarmDone = false;
  65381. // Animations
  65382. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  65383. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  65384. }
  65385. };
  65386. /**
  65387. * Stops the particle system.
  65388. */
  65389. GPUParticleSystem.prototype.stop = function () {
  65390. this._stopped = true;
  65391. };
  65392. /**
  65393. * Remove all active particles
  65394. */
  65395. GPUParticleSystem.prototype.reset = function () {
  65396. this._releaseBuffers();
  65397. this._releaseVAOs();
  65398. this._currentActiveCount = 0;
  65399. this._targetIndex = 0;
  65400. };
  65401. /**
  65402. * Returns the string "GPUParticleSystem"
  65403. * @returns a string containing the class name
  65404. */
  65405. GPUParticleSystem.prototype.getClassName = function () {
  65406. return "GPUParticleSystem";
  65407. };
  65408. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  65409. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  65410. this._releaseBuffers();
  65411. return this;
  65412. };
  65413. /**
  65414. * Adds a new color gradient
  65415. * @param gradient defines the gradient to use (between 0 and 1)
  65416. * @param color1 defines the color to affect to the specified gradient
  65417. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  65418. * @returns the current particle system
  65419. */
  65420. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  65421. if (!this._colorGradients) {
  65422. this._colorGradients = [];
  65423. }
  65424. var colorGradient = new BABYLON.ColorGradient();
  65425. colorGradient.gradient = gradient;
  65426. colorGradient.color1 = color1;
  65427. this._colorGradients.push(colorGradient);
  65428. this._colorGradients.sort(function (a, b) {
  65429. if (a.gradient < b.gradient) {
  65430. return -1;
  65431. }
  65432. else if (a.gradient > b.gradient) {
  65433. return 1;
  65434. }
  65435. return 0;
  65436. });
  65437. if (this._colorGradientsTexture) {
  65438. this._colorGradientsTexture.dispose();
  65439. this._colorGradientsTexture = null;
  65440. }
  65441. this._releaseBuffers();
  65442. return this;
  65443. };
  65444. /**
  65445. * Remove a specific color gradient
  65446. * @param gradient defines the gradient to remove
  65447. * @returns the current particle system
  65448. */
  65449. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  65450. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  65451. this._colorGradientsTexture = null;
  65452. return this;
  65453. };
  65454. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  65455. var valueGradient = new BABYLON.FactorGradient();
  65456. valueGradient.gradient = gradient;
  65457. valueGradient.factor1 = factor;
  65458. factorGradients.push(valueGradient);
  65459. factorGradients.sort(function (a, b) {
  65460. if (a.gradient < b.gradient) {
  65461. return -1;
  65462. }
  65463. else if (a.gradient > b.gradient) {
  65464. return 1;
  65465. }
  65466. return 0;
  65467. });
  65468. this._releaseBuffers();
  65469. };
  65470. /**
  65471. * Adds a new size gradient
  65472. * @param gradient defines the gradient to use (between 0 and 1)
  65473. * @param factor defines the size factor to affect to the specified gradient
  65474. * @returns the current particle system
  65475. */
  65476. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  65477. if (!this._sizeGradients) {
  65478. this._sizeGradients = [];
  65479. }
  65480. this._addFactorGradient(this._sizeGradients, gradient, factor);
  65481. if (this._sizeGradientsTexture) {
  65482. this._sizeGradientsTexture.dispose();
  65483. this._sizeGradientsTexture = null;
  65484. }
  65485. this._releaseBuffers();
  65486. return this;
  65487. };
  65488. /**
  65489. * Remove a specific size gradient
  65490. * @param gradient defines the gradient to remove
  65491. * @returns the current particle system
  65492. */
  65493. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  65494. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  65495. this._sizeGradientsTexture = null;
  65496. return this;
  65497. };
  65498. /**
  65499. * Adds a new angular speed gradient
  65500. * @param gradient defines the gradient to use (between 0 and 1)
  65501. * @param factor defines the angular speed to affect to the specified gradient
  65502. * @returns the current particle system
  65503. */
  65504. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  65505. if (!this._angularSpeedGradients) {
  65506. this._angularSpeedGradients = [];
  65507. }
  65508. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  65509. if (this._angularSpeedGradientsTexture) {
  65510. this._angularSpeedGradientsTexture.dispose();
  65511. this._angularSpeedGradientsTexture = null;
  65512. }
  65513. this._releaseBuffers();
  65514. return this;
  65515. };
  65516. /**
  65517. * Remove a specific angular speed gradient
  65518. * @param gradient defines the gradient to remove
  65519. * @returns the current particle system
  65520. */
  65521. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  65522. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  65523. this._angularSpeedGradientsTexture = null;
  65524. return this;
  65525. };
  65526. /**
  65527. * Adds a new velocity gradient
  65528. * @param gradient defines the gradient to use (between 0 and 1)
  65529. * @param factor defines the velocity to affect to the specified gradient
  65530. * @returns the current particle system
  65531. */
  65532. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  65533. if (!this._velocityGradients) {
  65534. this._velocityGradients = [];
  65535. }
  65536. this._addFactorGradient(this._velocityGradients, gradient, factor);
  65537. if (this._velocityGradientsTexture) {
  65538. this._velocityGradientsTexture.dispose();
  65539. this._velocityGradientsTexture = null;
  65540. }
  65541. this._releaseBuffers();
  65542. return this;
  65543. };
  65544. /**
  65545. * Remove a specific velocity gradient
  65546. * @param gradient defines the gradient to remove
  65547. * @returns the current particle system
  65548. */
  65549. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  65550. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  65551. this._velocityGradientsTexture = null;
  65552. return this;
  65553. };
  65554. /**
  65555. * Adds a new limit velocity gradient
  65556. * @param gradient defines the gradient to use (between 0 and 1)
  65557. * @param factor defines the limit velocity value to affect to the specified gradient
  65558. * @returns the current particle system
  65559. */
  65560. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  65561. if (!this._limitVelocityGradients) {
  65562. this._limitVelocityGradients = [];
  65563. }
  65564. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  65565. if (this._limitVelocityGradientsTexture) {
  65566. this._limitVelocityGradientsTexture.dispose();
  65567. this._limitVelocityGradientsTexture = null;
  65568. }
  65569. this._releaseBuffers();
  65570. return this;
  65571. };
  65572. /**
  65573. * Remove a specific limit velocity gradient
  65574. * @param gradient defines the gradient to remove
  65575. * @returns the current particle system
  65576. */
  65577. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  65578. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  65579. this._limitVelocityGradientsTexture = null;
  65580. return this;
  65581. };
  65582. /**
  65583. * Adds a new drag gradient
  65584. * @param gradient defines the gradient to use (between 0 and 1)
  65585. * @param factor defines the drag value to affect to the specified gradient
  65586. * @returns the current particle system
  65587. */
  65588. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  65589. if (!this._dragGradients) {
  65590. this._dragGradients = [];
  65591. }
  65592. this._addFactorGradient(this._dragGradients, gradient, factor);
  65593. if (this._dragGradientsTexture) {
  65594. this._dragGradientsTexture.dispose();
  65595. this._dragGradientsTexture = null;
  65596. }
  65597. this._releaseBuffers();
  65598. return this;
  65599. };
  65600. /**
  65601. * Remove a specific drag gradient
  65602. * @param gradient defines the gradient to remove
  65603. * @returns the current particle system
  65604. */
  65605. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  65606. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  65607. this._dragGradientsTexture = null;
  65608. return this;
  65609. };
  65610. /**
  65611. * Not supported by GPUParticleSystem
  65612. * @param gradient defines the gradient to use (between 0 and 1)
  65613. * @param factor defines the emit rate value to affect to the specified gradient
  65614. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  65615. * @returns the current particle system
  65616. */
  65617. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  65618. // Do nothing as emit rate is not supported by GPUParticleSystem
  65619. return this;
  65620. };
  65621. /**
  65622. * Not supported by GPUParticleSystem
  65623. * @param gradient defines the gradient to remove
  65624. * @returns the current particle system
  65625. */
  65626. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  65627. // Do nothing as emit rate is not supported by GPUParticleSystem
  65628. return this;
  65629. };
  65630. /**
  65631. * Not supported by GPUParticleSystem
  65632. * @param gradient defines the gradient to use (between 0 and 1)
  65633. * @param factor defines the start size value to affect to the specified gradient
  65634. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  65635. * @returns the current particle system
  65636. */
  65637. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  65638. // Do nothing as start size is not supported by GPUParticleSystem
  65639. return this;
  65640. };
  65641. /**
  65642. * Not supported by GPUParticleSystem
  65643. * @param gradient defines the gradient to remove
  65644. * @returns the current particle system
  65645. */
  65646. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  65647. // Do nothing as start size is not supported by GPUParticleSystem
  65648. return this;
  65649. };
  65650. /**
  65651. * Not supported by GPUParticleSystem
  65652. * @param gradient defines the gradient to use (between 0 and 1)
  65653. * @param min defines the color remap minimal range
  65654. * @param max defines the color remap maximal range
  65655. * @returns the current particle system
  65656. */
  65657. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  65658. // Do nothing as start size is not supported by GPUParticleSystem
  65659. return this;
  65660. };
  65661. /**
  65662. * Not supported by GPUParticleSystem
  65663. * @param gradient defines the gradient to remove
  65664. * @returns the current particle system
  65665. */
  65666. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  65667. // Do nothing as start size is not supported by GPUParticleSystem
  65668. return this;
  65669. };
  65670. /**
  65671. * Not supported by GPUParticleSystem
  65672. * @param gradient defines the gradient to use (between 0 and 1)
  65673. * @param min defines the alpha remap minimal range
  65674. * @param max defines the alpha remap maximal range
  65675. * @returns the current particle system
  65676. */
  65677. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  65678. // Do nothing as start size is not supported by GPUParticleSystem
  65679. return this;
  65680. };
  65681. /**
  65682. * Not supported by GPUParticleSystem
  65683. * @param gradient defines the gradient to remove
  65684. * @returns the current particle system
  65685. */
  65686. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  65687. // Do nothing as start size is not supported by GPUParticleSystem
  65688. return this;
  65689. };
  65690. /**
  65691. * Not supported by GPUParticleSystem
  65692. * @param gradient defines the gradient to use (between 0 and 1)
  65693. * @param color defines the color to affect to the specified gradient
  65694. * @returns the current particle system
  65695. */
  65696. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  65697. //Not supported by GPUParticleSystem
  65698. return this;
  65699. };
  65700. /**
  65701. * Not supported by GPUParticleSystem
  65702. * @param gradient defines the gradient to remove
  65703. * @returns the current particle system
  65704. */
  65705. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  65706. //Not supported by GPUParticleSystem
  65707. return this;
  65708. };
  65709. /**
  65710. * Not supported by GPUParticleSystem
  65711. * @returns the list of ramp gradients
  65712. */
  65713. GPUParticleSystem.prototype.getRampGradients = function () {
  65714. return null;
  65715. };
  65716. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  65717. /**
  65718. * Not supported by GPUParticleSystem
  65719. * Gets or sets a boolean indicating that ramp gradients must be used
  65720. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  65721. */
  65722. get: function () {
  65723. //Not supported by GPUParticleSystem
  65724. return false;
  65725. },
  65726. set: function (value) {
  65727. //Not supported by GPUParticleSystem
  65728. },
  65729. enumerable: true,
  65730. configurable: true
  65731. });
  65732. /**
  65733. * Not supported by GPUParticleSystem
  65734. * @param gradient defines the gradient to use (between 0 and 1)
  65735. * @param factor defines the life time factor to affect to the specified gradient
  65736. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  65737. * @returns the current particle system
  65738. */
  65739. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  65740. //Not supported by GPUParticleSystem
  65741. return this;
  65742. };
  65743. /**
  65744. * Not supported by GPUParticleSystem
  65745. * @param gradient defines the gradient to remove
  65746. * @returns the current particle system
  65747. */
  65748. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  65749. //Not supported by GPUParticleSystem
  65750. return this;
  65751. };
  65752. GPUParticleSystem.prototype._reset = function () {
  65753. this._releaseBuffers();
  65754. };
  65755. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  65756. var updateVertexBuffers = {};
  65757. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  65758. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  65759. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  65760. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  65761. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  65762. var offset = 12;
  65763. if (!this._colorGradientsTexture) {
  65764. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  65765. offset += 4;
  65766. }
  65767. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  65768. offset += 3;
  65769. if (!this._isBillboardBased) {
  65770. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  65771. offset += 3;
  65772. }
  65773. if (this._angularSpeedGradientsTexture) {
  65774. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  65775. offset += 1;
  65776. }
  65777. else {
  65778. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  65779. offset += 2;
  65780. }
  65781. if (this._isAnimationSheetEnabled) {
  65782. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  65783. offset += 1;
  65784. if (this.spriteRandomStartCell) {
  65785. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  65786. offset += 1;
  65787. }
  65788. }
  65789. if (this.noiseTexture) {
  65790. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  65791. offset += 3;
  65792. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  65793. offset += 3;
  65794. }
  65795. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  65796. this._engine.bindArrayBuffer(null);
  65797. return vao;
  65798. };
  65799. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  65800. var renderVertexBuffers = {};
  65801. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  65802. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  65803. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  65804. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  65805. var offset = 12;
  65806. if (!this._colorGradientsTexture) {
  65807. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  65808. offset += 4;
  65809. }
  65810. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  65811. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  65812. }
  65813. offset += 3; // Direction
  65814. if (!this._isBillboardBased) {
  65815. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  65816. offset += 3;
  65817. }
  65818. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  65819. if (this._angularSpeedGradientsTexture) {
  65820. offset++;
  65821. }
  65822. else {
  65823. offset += 2;
  65824. }
  65825. if (this._isAnimationSheetEnabled) {
  65826. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  65827. offset += 1;
  65828. if (this.spriteRandomStartCell) {
  65829. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  65830. offset += 1;
  65831. }
  65832. }
  65833. if (this.noiseTexture) {
  65834. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  65835. offset += 3;
  65836. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  65837. offset += 3;
  65838. }
  65839. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  65840. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  65841. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  65842. this._engine.bindArrayBuffer(null);
  65843. return vao;
  65844. };
  65845. GPUParticleSystem.prototype._initialize = function (force) {
  65846. if (force === void 0) { force = false; }
  65847. if (this._buffer0 && !force) {
  65848. return;
  65849. }
  65850. var engine = this._scene.getEngine();
  65851. var data = new Array();
  65852. if (!this.isBillboardBased) {
  65853. this._attributesStrideSize += 3;
  65854. }
  65855. if (this._colorGradientsTexture) {
  65856. this._attributesStrideSize -= 4;
  65857. }
  65858. if (this._angularSpeedGradientsTexture) {
  65859. this._attributesStrideSize -= 1;
  65860. }
  65861. if (this._isAnimationSheetEnabled) {
  65862. this._attributesStrideSize += 1;
  65863. if (this.spriteRandomStartCell) {
  65864. this._attributesStrideSize += 1;
  65865. }
  65866. }
  65867. if (this.noiseTexture) {
  65868. this._attributesStrideSize += 6;
  65869. }
  65870. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  65871. // position
  65872. data.push(0.0);
  65873. data.push(0.0);
  65874. data.push(0.0);
  65875. // Age and life
  65876. data.push(0.0); // create the particle as a dead one to create a new one at start
  65877. data.push(0.0);
  65878. // Seed
  65879. data.push(Math.random());
  65880. data.push(Math.random());
  65881. data.push(Math.random());
  65882. data.push(Math.random());
  65883. // Size
  65884. data.push(0.0);
  65885. data.push(0.0);
  65886. data.push(0.0);
  65887. if (!this._colorGradientsTexture) {
  65888. // color
  65889. data.push(0.0);
  65890. data.push(0.0);
  65891. data.push(0.0);
  65892. data.push(0.0);
  65893. }
  65894. // direction
  65895. data.push(0.0);
  65896. data.push(0.0);
  65897. data.push(0.0);
  65898. if (!this.isBillboardBased) {
  65899. // initialDirection
  65900. data.push(0.0);
  65901. data.push(0.0);
  65902. data.push(0.0);
  65903. }
  65904. // angle
  65905. data.push(0.0);
  65906. if (!this._angularSpeedGradientsTexture) {
  65907. data.push(0.0);
  65908. }
  65909. if (this._isAnimationSheetEnabled) {
  65910. data.push(0.0);
  65911. if (this.spriteRandomStartCell) {
  65912. data.push(0.0);
  65913. }
  65914. }
  65915. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  65916. data.push(Math.random());
  65917. data.push(Math.random());
  65918. data.push(Math.random());
  65919. data.push(Math.random());
  65920. data.push(Math.random());
  65921. data.push(Math.random());
  65922. }
  65923. }
  65924. // Sprite data
  65925. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  65926. -0.5, 0.5, 0, 1,
  65927. -0.5, -0.5, 0, 0,
  65928. 0.5, -0.5, 1, 0]);
  65929. // Buffers
  65930. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  65931. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  65932. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  65933. // Update VAO
  65934. this._updateVAO = [];
  65935. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  65936. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  65937. // Render VAO
  65938. this._renderVAO = [];
  65939. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  65940. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  65941. // Links
  65942. this._sourceBuffer = this._buffer0;
  65943. this._targetBuffer = this._buffer1;
  65944. };
  65945. /** @hidden */
  65946. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  65947. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  65948. if (this._isBillboardBased) {
  65949. defines += "\n#define BILLBOARD";
  65950. }
  65951. if (this._colorGradientsTexture) {
  65952. defines += "\n#define COLORGRADIENTS";
  65953. }
  65954. if (this._sizeGradientsTexture) {
  65955. defines += "\n#define SIZEGRADIENTS";
  65956. }
  65957. if (this._angularSpeedGradientsTexture) {
  65958. defines += "\n#define ANGULARSPEEDGRADIENTS";
  65959. }
  65960. if (this._velocityGradientsTexture) {
  65961. defines += "\n#define VELOCITYGRADIENTS";
  65962. }
  65963. if (this._limitVelocityGradientsTexture) {
  65964. defines += "\n#define LIMITVELOCITYGRADIENTS";
  65965. }
  65966. if (this._dragGradientsTexture) {
  65967. defines += "\n#define DRAGGRADIENTS";
  65968. }
  65969. if (this.isAnimationSheetEnabled) {
  65970. defines += "\n#define ANIMATESHEET";
  65971. if (this.spriteRandomStartCell) {
  65972. defines += "\n#define ANIMATESHEETRANDOMSTART";
  65973. }
  65974. }
  65975. if (this.noiseTexture) {
  65976. defines += "\n#define NOISE";
  65977. }
  65978. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  65979. return;
  65980. }
  65981. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  65982. if (!this._colorGradientsTexture) {
  65983. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  65984. }
  65985. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  65986. if (!this._isBillboardBased) {
  65987. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  65988. }
  65989. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  65990. if (this.isAnimationSheetEnabled) {
  65991. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  65992. if (this.spriteRandomStartCell) {
  65993. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  65994. }
  65995. }
  65996. if (this.noiseTexture) {
  65997. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  65998. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  65999. }
  66000. this._updateEffectOptions.defines = defines;
  66001. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  66002. };
  66003. /** @hidden */
  66004. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  66005. var defines = "";
  66006. if (this._scene.clipPlane) {
  66007. defines = "\n#define CLIPPLANE";
  66008. }
  66009. if (this._scene.clipPlane2) {
  66010. defines = "\n#define CLIPPLANE2";
  66011. }
  66012. if (this._scene.clipPlane3) {
  66013. defines = "\n#define CLIPPLANE3";
  66014. }
  66015. if (this._scene.clipPlane4) {
  66016. defines = "\n#define CLIPPLANE4";
  66017. }
  66018. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  66019. defines = "\n#define BLENDMULTIPLYMODE";
  66020. }
  66021. if (this._isBillboardBased) {
  66022. defines += "\n#define BILLBOARD";
  66023. switch (this.billboardMode) {
  66024. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  66025. defines += "\n#define BILLBOARDY";
  66026. break;
  66027. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  66028. defines += "\n#define BILLBOARDSTRETCHED";
  66029. break;
  66030. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  66031. default:
  66032. break;
  66033. }
  66034. }
  66035. if (this._colorGradientsTexture) {
  66036. defines += "\n#define COLORGRADIENTS";
  66037. }
  66038. if (this.isAnimationSheetEnabled) {
  66039. defines += "\n#define ANIMATESHEET";
  66040. }
  66041. if (this._imageProcessingConfiguration) {
  66042. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  66043. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  66044. }
  66045. if (this._renderEffect && this._renderEffect.defines === defines) {
  66046. return;
  66047. }
  66048. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  66049. var samplers = ["textureSampler", "colorGradientSampler"];
  66050. if (BABYLON.ImageProcessingConfiguration) {
  66051. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  66052. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  66053. }
  66054. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  66055. };
  66056. /**
  66057. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  66058. * @param preWarm defines if we are in the pre-warmimg phase
  66059. */
  66060. GPUParticleSystem.prototype.animate = function (preWarm) {
  66061. if (preWarm === void 0) { preWarm = false; }
  66062. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  66063. this._actualFrame += this._timeDelta;
  66064. if (!this._stopped) {
  66065. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  66066. this.stop();
  66067. }
  66068. }
  66069. };
  66070. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  66071. var texture = this[textureName];
  66072. if (!factorGradients || !factorGradients.length || texture) {
  66073. return;
  66074. }
  66075. var data = new Float32Array(this._rawTextureWidth);
  66076. for (var x = 0; x < this._rawTextureWidth; x++) {
  66077. var ratio = x / this._rawTextureWidth;
  66078. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  66079. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  66080. });
  66081. }
  66082. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66083. };
  66084. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  66085. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  66086. };
  66087. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  66088. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  66089. };
  66090. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  66091. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  66092. };
  66093. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  66094. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  66095. };
  66096. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  66097. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  66098. };
  66099. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  66100. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  66101. return;
  66102. }
  66103. var data = new Uint8Array(this._rawTextureWidth * 4);
  66104. var tmpColor = BABYLON.Tmp.Color4[0];
  66105. for (var x = 0; x < this._rawTextureWidth; x++) {
  66106. var ratio = x / this._rawTextureWidth;
  66107. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  66108. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  66109. data[x * 4] = tmpColor.r * 255;
  66110. data[x * 4 + 1] = tmpColor.g * 255;
  66111. data[x * 4 + 2] = tmpColor.b * 255;
  66112. data[x * 4 + 3] = tmpColor.a * 255;
  66113. });
  66114. }
  66115. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66116. };
  66117. /**
  66118. * Renders the particle system in its current state
  66119. * @param preWarm defines if the system should only update the particles but not render them
  66120. * @returns the current number of particles
  66121. */
  66122. GPUParticleSystem.prototype.render = function (preWarm) {
  66123. if (preWarm === void 0) { preWarm = false; }
  66124. if (!this._started) {
  66125. return 0;
  66126. }
  66127. this._createColorGradientTexture();
  66128. this._createSizeGradientTexture();
  66129. this._createAngularSpeedGradientTexture();
  66130. this._createVelocityGradientTexture();
  66131. this._createLimitVelocityGradientTexture();
  66132. this._createDragGradientTexture();
  66133. this._recreateUpdateEffect();
  66134. this._recreateRenderEffect();
  66135. if (!this.isReady()) {
  66136. return 0;
  66137. }
  66138. if (!preWarm) {
  66139. if (!this._preWarmDone && this.preWarmCycles) {
  66140. for (var index = 0; index < this.preWarmCycles; index++) {
  66141. this.animate(true);
  66142. this.render(true);
  66143. }
  66144. this._preWarmDone = true;
  66145. }
  66146. if (this._currentRenderId === this._scene.getRenderId()) {
  66147. return 0;
  66148. }
  66149. this._currentRenderId = this._scene.getRenderId();
  66150. }
  66151. // Get everything ready to render
  66152. this._initialize();
  66153. this._accumulatedCount += this.emitRate * this._timeDelta;
  66154. if (this._accumulatedCount > 1) {
  66155. var intPart = this._accumulatedCount | 0;
  66156. this._accumulatedCount -= intPart;
  66157. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  66158. }
  66159. if (!this._currentActiveCount) {
  66160. return 0;
  66161. }
  66162. // Enable update effect
  66163. this._engine.enableEffect(this._updateEffect);
  66164. this._engine.setState(false);
  66165. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  66166. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  66167. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  66168. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  66169. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  66170. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  66171. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  66172. if (!this._colorGradientsTexture) {
  66173. this._updateEffect.setDirectColor4("color1", this.color1);
  66174. this._updateEffect.setDirectColor4("color2", this.color2);
  66175. }
  66176. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  66177. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  66178. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  66179. this._updateEffect.setVector3("gravity", this.gravity);
  66180. if (this._sizeGradientsTexture) {
  66181. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  66182. }
  66183. if (this._angularSpeedGradientsTexture) {
  66184. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  66185. }
  66186. if (this._velocityGradientsTexture) {
  66187. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  66188. }
  66189. if (this._limitVelocityGradientsTexture) {
  66190. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  66191. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  66192. }
  66193. if (this._dragGradientsTexture) {
  66194. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  66195. }
  66196. if (this.particleEmitterType) {
  66197. this.particleEmitterType.applyToShader(this._updateEffect);
  66198. }
  66199. if (this._isAnimationSheetEnabled) {
  66200. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  66201. }
  66202. if (this.noiseTexture) {
  66203. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  66204. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  66205. }
  66206. var emitterWM;
  66207. if (this.emitter.position) {
  66208. var emitterMesh = this.emitter;
  66209. emitterWM = emitterMesh.getWorldMatrix();
  66210. }
  66211. else {
  66212. var emitterPosition = this.emitter;
  66213. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  66214. }
  66215. this._updateEffect.setMatrix("emitterWM", emitterWM);
  66216. // Bind source VAO
  66217. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  66218. // Update
  66219. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  66220. this._engine.setRasterizerState(false);
  66221. this._engine.beginTransformFeedback(true);
  66222. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  66223. this._engine.endTransformFeedback();
  66224. this._engine.setRasterizerState(true);
  66225. this._engine.bindTransformFeedbackBuffer(null);
  66226. if (!preWarm) {
  66227. // Enable render effect
  66228. this._engine.enableEffect(this._renderEffect);
  66229. var viewMatrix = this._scene.getViewMatrix();
  66230. this._renderEffect.setMatrix("view", viewMatrix);
  66231. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  66232. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  66233. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  66234. if (this._colorGradientsTexture) {
  66235. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  66236. }
  66237. else {
  66238. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  66239. }
  66240. if (this._isAnimationSheetEnabled && this.particleTexture) {
  66241. var baseSize = this.particleTexture.getBaseSize();
  66242. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  66243. }
  66244. if (this._isBillboardBased) {
  66245. var camera = this._scene.activeCamera;
  66246. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  66247. }
  66248. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  66249. var invView = viewMatrix.clone();
  66250. invView.invert();
  66251. this._renderEffect.setMatrix("invView", invView);
  66252. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  66253. }
  66254. // image processing
  66255. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  66256. this._imageProcessingConfiguration.bind(this._renderEffect);
  66257. }
  66258. // Draw order
  66259. switch (this.blendMode) {
  66260. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  66261. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  66262. break;
  66263. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  66264. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  66265. break;
  66266. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  66267. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  66268. break;
  66269. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  66270. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  66271. break;
  66272. }
  66273. if (this.forceDepthWrite) {
  66274. this._engine.setDepthWrite(true);
  66275. }
  66276. // Bind source VAO
  66277. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  66278. // Render
  66279. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  66280. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  66281. }
  66282. // Switch VAOs
  66283. this._targetIndex++;
  66284. if (this._targetIndex === 2) {
  66285. this._targetIndex = 0;
  66286. }
  66287. // Switch buffers
  66288. var tmpBuffer = this._sourceBuffer;
  66289. this._sourceBuffer = this._targetBuffer;
  66290. this._targetBuffer = tmpBuffer;
  66291. return this._currentActiveCount;
  66292. };
  66293. /**
  66294. * Rebuilds the particle system
  66295. */
  66296. GPUParticleSystem.prototype.rebuild = function () {
  66297. this._initialize(true);
  66298. };
  66299. GPUParticleSystem.prototype._releaseBuffers = function () {
  66300. if (this._buffer0) {
  66301. this._buffer0.dispose();
  66302. this._buffer0 = null;
  66303. }
  66304. if (this._buffer1) {
  66305. this._buffer1.dispose();
  66306. this._buffer1 = null;
  66307. }
  66308. if (this._spriteBuffer) {
  66309. this._spriteBuffer.dispose();
  66310. this._spriteBuffer = null;
  66311. }
  66312. };
  66313. GPUParticleSystem.prototype._releaseVAOs = function () {
  66314. if (!this._updateVAO) {
  66315. return;
  66316. }
  66317. for (var index = 0; index < this._updateVAO.length; index++) {
  66318. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  66319. }
  66320. this._updateVAO = [];
  66321. for (var index = 0; index < this._renderVAO.length; index++) {
  66322. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  66323. }
  66324. this._renderVAO = [];
  66325. };
  66326. /**
  66327. * Disposes the particle system and free the associated resources
  66328. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  66329. */
  66330. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  66331. if (disposeTexture === void 0) { disposeTexture = true; }
  66332. var index = this._scene.particleSystems.indexOf(this);
  66333. if (index > -1) {
  66334. this._scene.particleSystems.splice(index, 1);
  66335. }
  66336. this._releaseBuffers();
  66337. this._releaseVAOs();
  66338. if (this._colorGradientsTexture) {
  66339. this._colorGradientsTexture.dispose();
  66340. this._colorGradientsTexture = null;
  66341. }
  66342. if (this._sizeGradientsTexture) {
  66343. this._sizeGradientsTexture.dispose();
  66344. this._sizeGradientsTexture = null;
  66345. }
  66346. if (this._angularSpeedGradientsTexture) {
  66347. this._angularSpeedGradientsTexture.dispose();
  66348. this._angularSpeedGradientsTexture = null;
  66349. }
  66350. if (this._velocityGradientsTexture) {
  66351. this._velocityGradientsTexture.dispose();
  66352. this._velocityGradientsTexture = null;
  66353. }
  66354. if (this._limitVelocityGradientsTexture) {
  66355. this._limitVelocityGradientsTexture.dispose();
  66356. this._limitVelocityGradientsTexture = null;
  66357. }
  66358. if (this._dragGradientsTexture) {
  66359. this._dragGradientsTexture.dispose();
  66360. this._dragGradientsTexture = null;
  66361. }
  66362. if (this._randomTexture) {
  66363. this._randomTexture.dispose();
  66364. this._randomTexture = null;
  66365. }
  66366. if (this._randomTexture2) {
  66367. this._randomTexture2.dispose();
  66368. this._randomTexture2 = null;
  66369. }
  66370. if (disposeTexture && this.particleTexture) {
  66371. this.particleTexture.dispose();
  66372. this.particleTexture = null;
  66373. }
  66374. if (disposeTexture && this.noiseTexture) {
  66375. this.noiseTexture.dispose();
  66376. this.noiseTexture = null;
  66377. }
  66378. // Callback
  66379. this.onDisposeObservable.notifyObservers(this);
  66380. this.onDisposeObservable.clear();
  66381. };
  66382. /**
  66383. * Clones the particle system.
  66384. * @param name The name of the cloned object
  66385. * @param newEmitter The new emitter to use
  66386. * @returns the cloned particle system
  66387. */
  66388. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  66389. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  66390. BABYLON.Tools.DeepCopy(this, result);
  66391. if (newEmitter === undefined) {
  66392. newEmitter = this.emitter;
  66393. }
  66394. result.emitter = newEmitter;
  66395. if (this.particleTexture) {
  66396. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  66397. }
  66398. return result;
  66399. };
  66400. /**
  66401. * Serializes the particle system to a JSON object.
  66402. * @returns the JSON object
  66403. */
  66404. GPUParticleSystem.prototype.serialize = function () {
  66405. var serializationObject = {};
  66406. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  66407. serializationObject.activeParticleCount = this.activeParticleCount;
  66408. return serializationObject;
  66409. };
  66410. /**
  66411. * Parses a JSON object to create a GPU particle system.
  66412. * @param parsedParticleSystem The JSON object to parse
  66413. * @param scene The scene to create the particle system in
  66414. * @param rootUrl The root url to use to load external dependencies like texture
  66415. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  66416. * @returns the parsed GPU particle system
  66417. */
  66418. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  66419. if (doNotStart === void 0) { doNotStart = false; }
  66420. var name = parsedParticleSystem.name;
  66421. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  66422. if (parsedParticleSystem.activeParticleCount) {
  66423. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  66424. }
  66425. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  66426. // Auto start
  66427. if (parsedParticleSystem.preventAutoStart) {
  66428. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  66429. }
  66430. if (!doNotStart && !particleSystem.preventAutoStart) {
  66431. particleSystem.start();
  66432. }
  66433. return particleSystem;
  66434. };
  66435. return GPUParticleSystem;
  66436. }(BABYLON.BaseParticleSystem));
  66437. BABYLON.GPUParticleSystem = GPUParticleSystem;
  66438. })(BABYLON || (BABYLON = {}));
  66439. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  66440. var BABYLON;
  66441. (function (BABYLON) {
  66442. /**
  66443. * Represents one particle of a solid particle system.
  66444. */
  66445. var SolidParticle = /** @class */ (function () {
  66446. /**
  66447. * Creates a Solid Particle object.
  66448. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  66449. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  66450. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  66451. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  66452. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  66453. * @param shapeId (integer) is the model shape identifier in the SPS.
  66454. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  66455. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  66456. */
  66457. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  66458. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  66459. /**
  66460. * particle global index
  66461. */
  66462. this.idx = 0;
  66463. /**
  66464. * The color of the particle
  66465. */
  66466. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66467. /**
  66468. * The world space position of the particle.
  66469. */
  66470. this.position = BABYLON.Vector3.Zero();
  66471. /**
  66472. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  66473. */
  66474. this.rotation = BABYLON.Vector3.Zero();
  66475. /**
  66476. * The scaling of the particle.
  66477. */
  66478. this.scaling = BABYLON.Vector3.One();
  66479. /**
  66480. * The uvs of the particle.
  66481. */
  66482. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  66483. /**
  66484. * The current speed of the particle.
  66485. */
  66486. this.velocity = BABYLON.Vector3.Zero();
  66487. /**
  66488. * The pivot point in the particle local space.
  66489. */
  66490. this.pivot = BABYLON.Vector3.Zero();
  66491. /**
  66492. * Must the particle be translated from its pivot point in its local space ?
  66493. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  66494. * Default : false
  66495. */
  66496. this.translateFromPivot = false;
  66497. /**
  66498. * Is the particle active or not ?
  66499. */
  66500. this.alive = true;
  66501. /**
  66502. * Is the particle visible or not ?
  66503. */
  66504. this.isVisible = true;
  66505. /**
  66506. * Index of this particle in the global "positions" array (Internal use)
  66507. * @hidden
  66508. */
  66509. this._pos = 0;
  66510. /**
  66511. * @hidden Index of this particle in the global "indices" array (Internal use)
  66512. */
  66513. this._ind = 0;
  66514. /**
  66515. * ModelShape id of this particle
  66516. */
  66517. this.shapeId = 0;
  66518. /**
  66519. * Index of the particle in its shape id (Internal use)
  66520. */
  66521. this.idxInShape = 0;
  66522. /**
  66523. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  66524. */
  66525. this._stillInvisible = false;
  66526. /**
  66527. * @hidden Last computed particle rotation matrix
  66528. */
  66529. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  66530. /**
  66531. * Parent particle Id, if any.
  66532. * Default null.
  66533. */
  66534. this.parentId = null;
  66535. /**
  66536. * @hidden Internal global position in the SPS.
  66537. */
  66538. this._globalPosition = BABYLON.Vector3.Zero();
  66539. this.idx = particleIndex;
  66540. this._pos = positionIndex;
  66541. this._ind = indiceIndex;
  66542. this._model = model;
  66543. this.shapeId = shapeId;
  66544. this.idxInShape = idxInShape;
  66545. this._sps = sps;
  66546. if (modelBoundingInfo) {
  66547. this._modelBoundingInfo = modelBoundingInfo;
  66548. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  66549. }
  66550. }
  66551. Object.defineProperty(SolidParticle.prototype, "scale", {
  66552. /**
  66553. * Legacy support, changed scale to scaling
  66554. */
  66555. get: function () {
  66556. return this.scaling;
  66557. },
  66558. /**
  66559. * Legacy support, changed scale to scaling
  66560. */
  66561. set: function (scale) {
  66562. this.scaling = scale;
  66563. },
  66564. enumerable: true,
  66565. configurable: true
  66566. });
  66567. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  66568. /**
  66569. * Legacy support, changed quaternion to rotationQuaternion
  66570. */
  66571. get: function () {
  66572. return this.rotationQuaternion;
  66573. },
  66574. /**
  66575. * Legacy support, changed quaternion to rotationQuaternion
  66576. */
  66577. set: function (q) {
  66578. this.rotationQuaternion = q;
  66579. },
  66580. enumerable: true,
  66581. configurable: true
  66582. });
  66583. /**
  66584. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  66585. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  66586. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  66587. * @returns true if it intersects
  66588. */
  66589. SolidParticle.prototype.intersectsMesh = function (target) {
  66590. if (!this._boundingInfo || !target._boundingInfo) {
  66591. return false;
  66592. }
  66593. if (this._sps._bSphereOnly) {
  66594. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  66595. }
  66596. return this._boundingInfo.intersects(target._boundingInfo, false);
  66597. };
  66598. return SolidParticle;
  66599. }());
  66600. BABYLON.SolidParticle = SolidParticle;
  66601. /**
  66602. * Represents the shape of the model used by one particle of a solid particle system.
  66603. * SPS internal tool, don't use it manually.
  66604. */
  66605. var ModelShape = /** @class */ (function () {
  66606. /**
  66607. * 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.
  66608. * SPS internal tool, don't use it manually.
  66609. * @hidden
  66610. */
  66611. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  66612. /**
  66613. * length of the shape in the model indices array (internal use)
  66614. * @hidden
  66615. */
  66616. this._indicesLength = 0;
  66617. this.shapeID = id;
  66618. this._shape = shape;
  66619. this._indicesLength = indicesLength;
  66620. this._shapeUV = shapeUV;
  66621. this._positionFunction = posFunction;
  66622. this._vertexFunction = vtxFunction;
  66623. }
  66624. return ModelShape;
  66625. }());
  66626. BABYLON.ModelShape = ModelShape;
  66627. /**
  66628. * Represents a Depth Sorted Particle in the solid particle system.
  66629. */
  66630. var DepthSortedParticle = /** @class */ (function () {
  66631. function DepthSortedParticle() {
  66632. /**
  66633. * Index of the particle in the "indices" array
  66634. */
  66635. this.ind = 0;
  66636. /**
  66637. * Length of the particle shape in the "indices" array
  66638. */
  66639. this.indicesLength = 0;
  66640. /**
  66641. * Squared distance from the particle to the camera
  66642. */
  66643. this.sqDistance = 0.0;
  66644. }
  66645. return DepthSortedParticle;
  66646. }());
  66647. BABYLON.DepthSortedParticle = DepthSortedParticle;
  66648. })(BABYLON || (BABYLON = {}));
  66649. //# sourceMappingURL=babylon.solidParticle.js.map
  66650. var BABYLON;
  66651. (function (BABYLON) {
  66652. /**
  66653. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  66654. *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.
  66655. * The SPS is also a particle system. It provides some methods to manage the particles.
  66656. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  66657. *
  66658. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  66659. */
  66660. var SolidParticleSystem = /** @class */ (function () {
  66661. /**
  66662. * Creates a SPS (Solid Particle System) object.
  66663. * @param name (String) is the SPS name, this will be the underlying mesh name.
  66664. * @param scene (Scene) is the scene in which the SPS is added.
  66665. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  66666. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  66667. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  66668. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  66669. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  66670. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  66671. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  66672. */
  66673. function SolidParticleSystem(name, scene, options) {
  66674. /**
  66675. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  66676. * Example : var p = SPS.particles[i];
  66677. */
  66678. this.particles = new Array();
  66679. /**
  66680. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  66681. */
  66682. this.nbParticles = 0;
  66683. /**
  66684. * If the particles must ever face the camera (default false). Useful for planar particles.
  66685. */
  66686. this.billboard = false;
  66687. /**
  66688. * Recompute normals when adding a shape
  66689. */
  66690. this.recomputeNormals = true;
  66691. /**
  66692. * This a counter ofr your own usage. It's not set by any SPS functions.
  66693. */
  66694. this.counter = 0;
  66695. /**
  66696. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  66697. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  66698. */
  66699. this.vars = {};
  66700. /**
  66701. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  66702. * @hidden
  66703. */
  66704. this._bSphereOnly = false;
  66705. /**
  66706. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  66707. * @hidden
  66708. */
  66709. this._bSphereRadiusFactor = 1.0;
  66710. this._positions = new Array();
  66711. this._indices = new Array();
  66712. this._normals = new Array();
  66713. this._colors = new Array();
  66714. this._uvs = new Array();
  66715. this._index = 0; // indices index
  66716. this._updatable = true;
  66717. this._pickable = false;
  66718. this._isVisibilityBoxLocked = false;
  66719. this._alwaysVisible = false;
  66720. this._depthSort = false;
  66721. this._shapeCounter = 0;
  66722. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  66723. this._color = new BABYLON.Color4(0, 0, 0, 0);
  66724. this._computeParticleColor = true;
  66725. this._computeParticleTexture = true;
  66726. this._computeParticleRotation = true;
  66727. this._computeParticleVertex = false;
  66728. this._computeBoundingBox = false;
  66729. this._depthSortParticles = true;
  66730. this._cam_axisZ = BABYLON.Vector3.Zero();
  66731. this._cam_axisY = BABYLON.Vector3.Zero();
  66732. this._cam_axisX = BABYLON.Vector3.Zero();
  66733. this._axisZ = BABYLON.Axis.Z;
  66734. this._camDir = BABYLON.Vector3.Zero();
  66735. this._camInvertedPosition = BABYLON.Vector3.Zero();
  66736. this._rotMatrix = new BABYLON.Matrix();
  66737. this._invertMatrix = new BABYLON.Matrix();
  66738. this._rotated = BABYLON.Vector3.Zero();
  66739. this._quaternion = new BABYLON.Quaternion();
  66740. this._vertex = BABYLON.Vector3.Zero();
  66741. this._normal = BABYLON.Vector3.Zero();
  66742. this._yaw = 0.0;
  66743. this._pitch = 0.0;
  66744. this._roll = 0.0;
  66745. this._halfroll = 0.0;
  66746. this._halfpitch = 0.0;
  66747. this._halfyaw = 0.0;
  66748. this._sinRoll = 0.0;
  66749. this._cosRoll = 0.0;
  66750. this._sinPitch = 0.0;
  66751. this._cosPitch = 0.0;
  66752. this._sinYaw = 0.0;
  66753. this._cosYaw = 0.0;
  66754. this._mustUnrotateFixedNormals = false;
  66755. this._minimum = BABYLON.Vector3.Zero();
  66756. this._maximum = BABYLON.Vector3.Zero();
  66757. this._minBbox = BABYLON.Vector3.Zero();
  66758. this._maxBbox = BABYLON.Vector3.Zero();
  66759. this._particlesIntersect = false;
  66760. this._depthSortFunction = function (p1, p2) {
  66761. return (p2.sqDistance - p1.sqDistance);
  66762. };
  66763. this._needs32Bits = false;
  66764. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  66765. this._scaledPivot = BABYLON.Vector3.Zero();
  66766. this._particleHasParent = false;
  66767. this.name = name;
  66768. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66769. this._camera = scene.activeCamera;
  66770. this._pickable = options ? options.isPickable : false;
  66771. this._depthSort = options ? options.enableDepthSort : false;
  66772. this._particlesIntersect = options ? options.particleIntersection : false;
  66773. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  66774. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  66775. if (options && options.updatable !== undefined) {
  66776. this._updatable = options.updatable;
  66777. }
  66778. else {
  66779. this._updatable = true;
  66780. }
  66781. if (this._pickable) {
  66782. this.pickedParticles = [];
  66783. }
  66784. if (this._depthSort) {
  66785. this.depthSortedParticles = [];
  66786. }
  66787. }
  66788. /**
  66789. * Builds the SPS underlying mesh. Returns a standard Mesh.
  66790. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  66791. * @returns the created mesh
  66792. */
  66793. SolidParticleSystem.prototype.buildMesh = function () {
  66794. if (this.nbParticles === 0) {
  66795. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  66796. this.addShape(triangle, 1);
  66797. triangle.dispose();
  66798. }
  66799. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  66800. this._positions32 = new Float32Array(this._positions);
  66801. this._uvs32 = new Float32Array(this._uvs);
  66802. this._colors32 = new Float32Array(this._colors);
  66803. if (this.recomputeNormals) {
  66804. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  66805. }
  66806. this._normals32 = new Float32Array(this._normals);
  66807. this._fixedNormal32 = new Float32Array(this._normals);
  66808. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  66809. this._unrotateFixedNormals();
  66810. }
  66811. var vertexData = new BABYLON.VertexData();
  66812. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  66813. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  66814. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  66815. if (this._uvs32.length > 0) {
  66816. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  66817. }
  66818. if (this._colors32.length > 0) {
  66819. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  66820. }
  66821. var mesh = new BABYLON.Mesh(this.name, this._scene);
  66822. vertexData.applyToMesh(mesh, this._updatable);
  66823. this.mesh = mesh;
  66824. this.mesh.isPickable = this._pickable;
  66825. // free memory
  66826. if (!this._depthSort) {
  66827. this._indices = null;
  66828. }
  66829. this._positions = null;
  66830. this._normals = null;
  66831. this._uvs = null;
  66832. this._colors = null;
  66833. if (!this._updatable) {
  66834. this.particles.length = 0;
  66835. }
  66836. return mesh;
  66837. };
  66838. /**
  66839. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  66840. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  66841. * Thus the particles generated from `digest()` have their property `position` set yet.
  66842. * @param mesh ( Mesh ) is the mesh to be digested
  66843. * @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
  66844. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  66845. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  66846. * @returns the current SPS
  66847. */
  66848. SolidParticleSystem.prototype.digest = function (mesh, options) {
  66849. var size = (options && options.facetNb) || 1;
  66850. var number = (options && options.number) || 0;
  66851. var delta = (options && options.delta) || 0;
  66852. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66853. var meshInd = mesh.getIndices();
  66854. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66855. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66856. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66857. var f = 0; // facet counter
  66858. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  66859. // compute size from number
  66860. if (number) {
  66861. number = (number > totalFacets) ? totalFacets : number;
  66862. size = Math.round(totalFacets / number);
  66863. delta = 0;
  66864. }
  66865. else {
  66866. size = (size > totalFacets) ? totalFacets : size;
  66867. }
  66868. var facetPos = []; // submesh positions
  66869. var facetInd = []; // submesh indices
  66870. var facetUV = []; // submesh UV
  66871. var facetCol = []; // submesh colors
  66872. var barycenter = BABYLON.Vector3.Zero();
  66873. var sizeO = size;
  66874. while (f < totalFacets) {
  66875. size = sizeO + Math.floor((1 + delta) * Math.random());
  66876. if (f > totalFacets - size) {
  66877. size = totalFacets - f;
  66878. }
  66879. // reset temp arrays
  66880. facetPos.length = 0;
  66881. facetInd.length = 0;
  66882. facetUV.length = 0;
  66883. facetCol.length = 0;
  66884. // iterate over "size" facets
  66885. var fi = 0;
  66886. for (var j = f * 3; j < (f + size) * 3; j++) {
  66887. facetInd.push(fi);
  66888. var i = meshInd[j];
  66889. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  66890. if (meshUV) {
  66891. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  66892. }
  66893. if (meshCol) {
  66894. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  66895. }
  66896. fi++;
  66897. }
  66898. // create a model shape for each single particle
  66899. var idx = this.nbParticles;
  66900. var shape = this._posToShape(facetPos);
  66901. var shapeUV = this._uvsToShapeUV(facetUV);
  66902. // compute the barycenter of the shape
  66903. var v;
  66904. for (v = 0; v < shape.length; v++) {
  66905. barycenter.addInPlace(shape[v]);
  66906. }
  66907. barycenter.scaleInPlace(1 / shape.length);
  66908. // shift the shape from its barycenter to the origin
  66909. for (v = 0; v < shape.length; v++) {
  66910. shape[v].subtractInPlace(barycenter);
  66911. }
  66912. var bInfo;
  66913. if (this._particlesIntersect) {
  66914. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  66915. }
  66916. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  66917. // add the particle in the SPS
  66918. var currentPos = this._positions.length;
  66919. var currentInd = this._indices.length;
  66920. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  66921. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  66922. // initialize the particle position
  66923. this.particles[this.nbParticles].position.addInPlace(barycenter);
  66924. this._index += shape.length;
  66925. idx++;
  66926. this.nbParticles++;
  66927. this._shapeCounter++;
  66928. f += size;
  66929. }
  66930. return this;
  66931. };
  66932. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  66933. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  66934. var index = 0;
  66935. var idx = 0;
  66936. for (var p = 0; p < this.particles.length; p++) {
  66937. this._particle = this.particles[p];
  66938. this._shape = this._particle._model._shape;
  66939. if (this._particle.rotationQuaternion) {
  66940. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  66941. }
  66942. else {
  66943. this._yaw = this._particle.rotation.y;
  66944. this._pitch = this._particle.rotation.x;
  66945. this._roll = this._particle.rotation.z;
  66946. this._quaternionRotationYPR();
  66947. }
  66948. this._quaternionToRotationMatrix();
  66949. this._rotMatrix.invertToRef(this._invertMatrix);
  66950. for (var pt = 0; pt < this._shape.length; pt++) {
  66951. idx = index + pt * 3;
  66952. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  66953. this._fixedNormal32[idx] = this._normal.x;
  66954. this._fixedNormal32[idx + 1] = this._normal.y;
  66955. this._fixedNormal32[idx + 2] = this._normal.z;
  66956. }
  66957. index = idx + 3;
  66958. }
  66959. };
  66960. //reset copy
  66961. SolidParticleSystem.prototype._resetCopy = function () {
  66962. this._copy.position.x = 0;
  66963. this._copy.position.y = 0;
  66964. this._copy.position.z = 0;
  66965. this._copy.rotation.x = 0;
  66966. this._copy.rotation.y = 0;
  66967. this._copy.rotation.z = 0;
  66968. this._copy.rotationQuaternion = null;
  66969. this._copy.scaling.x = 1.0;
  66970. this._copy.scaling.y = 1.0;
  66971. this._copy.scaling.z = 1.0;
  66972. this._copy.uvs.x = 0;
  66973. this._copy.uvs.y = 0;
  66974. this._copy.uvs.z = 1.0;
  66975. this._copy.uvs.w = 1.0;
  66976. this._copy.color = null;
  66977. this._copy.translateFromPivot = false;
  66978. };
  66979. // _meshBuilder : inserts the shape model in the global SPS mesh
  66980. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  66981. var i;
  66982. var u = 0;
  66983. var c = 0;
  66984. var n = 0;
  66985. this._resetCopy();
  66986. if (options && options.positionFunction) { // call to custom positionFunction
  66987. options.positionFunction(this._copy, idx, idxInShape);
  66988. this._mustUnrotateFixedNormals = true;
  66989. }
  66990. if (this._copy.rotationQuaternion) {
  66991. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  66992. }
  66993. else {
  66994. this._yaw = this._copy.rotation.y;
  66995. this._pitch = this._copy.rotation.x;
  66996. this._roll = this._copy.rotation.z;
  66997. this._quaternionRotationYPR();
  66998. }
  66999. this._quaternionToRotationMatrix();
  67000. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  67001. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  67002. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  67003. if (this._copy.translateFromPivot) {
  67004. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  67005. }
  67006. else {
  67007. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  67008. }
  67009. for (i = 0; i < shape.length; i++) {
  67010. this._vertex.x = shape[i].x;
  67011. this._vertex.y = shape[i].y;
  67012. this._vertex.z = shape[i].z;
  67013. if (options && options.vertexFunction) {
  67014. options.vertexFunction(this._copy, this._vertex, i);
  67015. }
  67016. this._vertex.x *= this._copy.scaling.x;
  67017. this._vertex.y *= this._copy.scaling.y;
  67018. this._vertex.z *= this._copy.scaling.z;
  67019. this._vertex.x -= this._scaledPivot.x;
  67020. this._vertex.y -= this._scaledPivot.y;
  67021. this._vertex.z -= this._scaledPivot.z;
  67022. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  67023. this._rotated.addInPlace(this._pivotBackTranslation);
  67024. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  67025. if (meshUV) {
  67026. 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);
  67027. u += 2;
  67028. }
  67029. if (this._copy.color) {
  67030. this._color = this._copy.color;
  67031. }
  67032. else if (meshCol && meshCol[c] !== undefined) {
  67033. this._color.r = meshCol[c];
  67034. this._color.g = meshCol[c + 1];
  67035. this._color.b = meshCol[c + 2];
  67036. this._color.a = meshCol[c + 3];
  67037. }
  67038. else {
  67039. this._color.r = 1.0;
  67040. this._color.g = 1.0;
  67041. this._color.b = 1.0;
  67042. this._color.a = 1.0;
  67043. }
  67044. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  67045. c += 4;
  67046. if (!this.recomputeNormals && meshNor) {
  67047. this._normal.x = meshNor[n];
  67048. this._normal.y = meshNor[n + 1];
  67049. this._normal.z = meshNor[n + 2];
  67050. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  67051. normals.push(this._normal.x, this._normal.y, this._normal.z);
  67052. n += 3;
  67053. }
  67054. }
  67055. for (i = 0; i < meshInd.length; i++) {
  67056. var current_ind = p + meshInd[i];
  67057. indices.push(current_ind);
  67058. if (current_ind > 65535) {
  67059. this._needs32Bits = true;
  67060. }
  67061. }
  67062. if (this._pickable) {
  67063. var nbfaces = meshInd.length / 3;
  67064. for (i = 0; i < nbfaces; i++) {
  67065. this.pickedParticles.push({ idx: idx, faceId: i });
  67066. }
  67067. }
  67068. if (this._depthSort) {
  67069. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  67070. }
  67071. return this._copy;
  67072. };
  67073. // returns a shape array from positions array
  67074. SolidParticleSystem.prototype._posToShape = function (positions) {
  67075. var shape = [];
  67076. for (var i = 0; i < positions.length; i += 3) {
  67077. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  67078. }
  67079. return shape;
  67080. };
  67081. // returns a shapeUV array from a Vector4 uvs
  67082. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  67083. var shapeUV = [];
  67084. if (uvs) {
  67085. for (var i = 0; i < uvs.length; i++) {
  67086. shapeUV.push(uvs[i]);
  67087. }
  67088. }
  67089. return shapeUV;
  67090. };
  67091. // adds a new particle object in the particles array
  67092. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  67093. if (bInfo === void 0) { bInfo = null; }
  67094. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  67095. this.particles.push(sp);
  67096. return sp;
  67097. };
  67098. /**
  67099. * Adds some particles to the SPS from the model shape. Returns the shape id.
  67100. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  67101. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  67102. * @param nb (positive integer) the number of particles to be created from this model
  67103. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  67104. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  67105. * @returns the number of shapes in the system
  67106. */
  67107. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  67108. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67109. var meshInd = mesh.getIndices();
  67110. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  67111. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67112. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  67113. var bbInfo;
  67114. if (this._particlesIntersect) {
  67115. bbInfo = mesh.getBoundingInfo();
  67116. }
  67117. var shape = this._posToShape(meshPos);
  67118. var shapeUV = this._uvsToShapeUV(meshUV);
  67119. var posfunc = options ? options.positionFunction : null;
  67120. var vtxfunc = options ? options.vertexFunction : null;
  67121. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  67122. // particles
  67123. var sp;
  67124. var currentCopy;
  67125. var idx = this.nbParticles;
  67126. for (var i = 0; i < nb; i++) {
  67127. var currentPos = this._positions.length;
  67128. var currentInd = this._indices.length;
  67129. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  67130. if (this._updatable) {
  67131. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  67132. sp.position.copyFrom(currentCopy.position);
  67133. sp.rotation.copyFrom(currentCopy.rotation);
  67134. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  67135. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  67136. }
  67137. if (currentCopy.color && sp.color) {
  67138. sp.color.copyFrom(currentCopy.color);
  67139. }
  67140. sp.scaling.copyFrom(currentCopy.scaling);
  67141. sp.uvs.copyFrom(currentCopy.uvs);
  67142. }
  67143. this._index += shape.length;
  67144. idx++;
  67145. }
  67146. this.nbParticles += nb;
  67147. this._shapeCounter++;
  67148. return this._shapeCounter - 1;
  67149. };
  67150. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  67151. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  67152. this._resetCopy();
  67153. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  67154. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  67155. }
  67156. if (this._copy.rotationQuaternion) {
  67157. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  67158. }
  67159. else {
  67160. this._yaw = this._copy.rotation.y;
  67161. this._pitch = this._copy.rotation.x;
  67162. this._roll = this._copy.rotation.z;
  67163. this._quaternionRotationYPR();
  67164. }
  67165. this._quaternionToRotationMatrix();
  67166. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  67167. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  67168. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  67169. if (this._copy.translateFromPivot) {
  67170. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  67171. }
  67172. else {
  67173. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  67174. }
  67175. this._shape = particle._model._shape;
  67176. for (var pt = 0; pt < this._shape.length; pt++) {
  67177. this._vertex.x = this._shape[pt].x;
  67178. this._vertex.y = this._shape[pt].y;
  67179. this._vertex.z = this._shape[pt].z;
  67180. if (particle._model._vertexFunction) {
  67181. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  67182. }
  67183. this._vertex.x *= this._copy.scaling.x;
  67184. this._vertex.y *= this._copy.scaling.y;
  67185. this._vertex.z *= this._copy.scaling.z;
  67186. this._vertex.x -= this._scaledPivot.x;
  67187. this._vertex.y -= this._scaledPivot.y;
  67188. this._vertex.z -= this._scaledPivot.z;
  67189. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  67190. this._rotated.addInPlace(this._pivotBackTranslation);
  67191. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  67192. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  67193. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  67194. }
  67195. particle.position.x = 0.0;
  67196. particle.position.y = 0.0;
  67197. particle.position.z = 0.0;
  67198. particle.rotation.x = 0.0;
  67199. particle.rotation.y = 0.0;
  67200. particle.rotation.z = 0.0;
  67201. particle.rotationQuaternion = null;
  67202. particle.scaling.x = 1.0;
  67203. particle.scaling.y = 1.0;
  67204. particle.scaling.z = 1.0;
  67205. particle.uvs.x = 0.0;
  67206. particle.uvs.y = 0.0;
  67207. particle.uvs.z = 1.0;
  67208. particle.uvs.w = 1.0;
  67209. particle.pivot.x = 0.0;
  67210. particle.pivot.y = 0.0;
  67211. particle.pivot.z = 0.0;
  67212. particle.translateFromPivot = false;
  67213. particle.parentId = null;
  67214. };
  67215. /**
  67216. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  67217. * @returns the SPS.
  67218. */
  67219. SolidParticleSystem.prototype.rebuildMesh = function () {
  67220. for (var p = 0; p < this.particles.length; p++) {
  67221. this._rebuildParticle(this.particles[p]);
  67222. }
  67223. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  67224. return this;
  67225. };
  67226. /**
  67227. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  67228. * This method calls `updateParticle()` for each particle of the SPS.
  67229. * For an animated SPS, it is usually called within the render loop.
  67230. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  67231. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  67232. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  67233. * @returns the SPS.
  67234. */
  67235. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  67236. if (start === void 0) { start = 0; }
  67237. if (end === void 0) { end = this.nbParticles - 1; }
  67238. if (update === void 0) { update = true; }
  67239. if (!this._updatable) {
  67240. return this;
  67241. }
  67242. // custom beforeUpdate
  67243. this.beforeUpdateParticles(start, end, update);
  67244. this._cam_axisX.x = 1.0;
  67245. this._cam_axisX.y = 0.0;
  67246. this._cam_axisX.z = 0.0;
  67247. this._cam_axisY.x = 0.0;
  67248. this._cam_axisY.y = 1.0;
  67249. this._cam_axisY.z = 0.0;
  67250. this._cam_axisZ.x = 0.0;
  67251. this._cam_axisZ.y = 0.0;
  67252. this._cam_axisZ.z = 1.0;
  67253. // cases when the World Matrix is to be computed first
  67254. if (this.billboard || this._depthSort) {
  67255. this.mesh.computeWorldMatrix(true);
  67256. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  67257. }
  67258. // if the particles will always face the camera
  67259. if (this.billboard) {
  67260. // compute the camera position and un-rotate it by the current mesh rotation
  67261. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  67262. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  67263. this._cam_axisZ.normalize();
  67264. // same for camera up vector extracted from the cam view matrix
  67265. var view = this._camera.getViewMatrix(true);
  67266. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  67267. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  67268. this._cam_axisY.normalize();
  67269. this._cam_axisX.normalize();
  67270. }
  67271. // if depthSort, compute the camera global position in the mesh local system
  67272. if (this._depthSort) {
  67273. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  67274. }
  67275. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  67276. var idx = 0; // current position index in the global array positions32
  67277. var index = 0; // position start index in the global array positions32 of the current particle
  67278. var colidx = 0; // current color index in the global array colors32
  67279. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  67280. var uvidx = 0; // current uv index in the global array uvs32
  67281. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  67282. var pt = 0; // current index in the particle model shape
  67283. if (this.mesh.isFacetDataEnabled) {
  67284. this._computeBoundingBox = true;
  67285. }
  67286. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  67287. if (this._computeBoundingBox) {
  67288. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  67289. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  67290. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  67291. }
  67292. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  67293. if (this.mesh._boundingInfo) {
  67294. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  67295. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  67296. }
  67297. }
  67298. }
  67299. // particle loop
  67300. index = this.particles[start]._pos;
  67301. var vpos = (index / 3) | 0;
  67302. colorIndex = vpos * 4;
  67303. uvIndex = vpos * 2;
  67304. for (var p = start; p <= end; p++) {
  67305. this._particle = this.particles[p];
  67306. this._shape = this._particle._model._shape;
  67307. this._shapeUV = this._particle._model._shapeUV;
  67308. // call to custom user function to update the particle properties
  67309. this.updateParticle(this._particle);
  67310. // camera-particle distance for depth sorting
  67311. if (this._depthSort && this._depthSortParticles) {
  67312. var dsp = this.depthSortedParticles[p];
  67313. dsp.ind = this._particle._ind;
  67314. dsp.indicesLength = this._particle._model._indicesLength;
  67315. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  67316. }
  67317. // skip the computations for inactive or already invisible particles
  67318. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  67319. // increment indexes for the next particle
  67320. pt = this._shape.length;
  67321. index += pt * 3;
  67322. colorIndex += pt * 4;
  67323. uvIndex += pt * 2;
  67324. continue;
  67325. }
  67326. if (this._particle.isVisible) {
  67327. this._particle._stillInvisible = false; // un-mark permanent invisibility
  67328. this._particleHasParent = (this._particle.parentId !== null);
  67329. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  67330. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  67331. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  67332. // particle rotation matrix
  67333. if (this.billboard) {
  67334. this._particle.rotation.x = 0.0;
  67335. this._particle.rotation.y = 0.0;
  67336. }
  67337. if (this._computeParticleRotation || this.billboard) {
  67338. if (this._particle.rotationQuaternion) {
  67339. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  67340. }
  67341. else {
  67342. this._yaw = this._particle.rotation.y;
  67343. this._pitch = this._particle.rotation.x;
  67344. this._roll = this._particle.rotation.z;
  67345. this._quaternionRotationYPR();
  67346. }
  67347. this._quaternionToRotationMatrix();
  67348. }
  67349. if (this._particleHasParent) {
  67350. this._parent = this.particles[this._particle.parentId];
  67351. 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];
  67352. 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];
  67353. 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];
  67354. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  67355. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  67356. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  67357. if (this._computeParticleRotation || this.billboard) {
  67358. 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];
  67359. 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];
  67360. 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];
  67361. 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];
  67362. 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];
  67363. 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];
  67364. 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];
  67365. 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];
  67366. 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];
  67367. }
  67368. }
  67369. else {
  67370. this._particle._globalPosition.x = this._particle.position.x;
  67371. this._particle._globalPosition.y = this._particle.position.y;
  67372. this._particle._globalPosition.z = this._particle.position.z;
  67373. if (this._computeParticleRotation || this.billboard) {
  67374. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  67375. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  67376. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  67377. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  67378. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  67379. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  67380. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  67381. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  67382. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  67383. }
  67384. }
  67385. if (this._particle.translateFromPivot) {
  67386. this._pivotBackTranslation.x = 0.0;
  67387. this._pivotBackTranslation.y = 0.0;
  67388. this._pivotBackTranslation.z = 0.0;
  67389. }
  67390. else {
  67391. this._pivotBackTranslation.x = this._scaledPivot.x;
  67392. this._pivotBackTranslation.y = this._scaledPivot.y;
  67393. this._pivotBackTranslation.z = this._scaledPivot.z;
  67394. }
  67395. // particle vertex loop
  67396. for (pt = 0; pt < this._shape.length; pt++) {
  67397. idx = index + pt * 3;
  67398. colidx = colorIndex + pt * 4;
  67399. uvidx = uvIndex + pt * 2;
  67400. this._vertex.x = this._shape[pt].x;
  67401. this._vertex.y = this._shape[pt].y;
  67402. this._vertex.z = this._shape[pt].z;
  67403. if (this._computeParticleVertex) {
  67404. this.updateParticleVertex(this._particle, this._vertex, pt);
  67405. }
  67406. // positions
  67407. this._vertex.x *= this._particle.scaling.x;
  67408. this._vertex.y *= this._particle.scaling.y;
  67409. this._vertex.z *= this._particle.scaling.z;
  67410. this._vertex.x -= this._scaledPivot.x;
  67411. this._vertex.y -= this._scaledPivot.y;
  67412. this._vertex.z -= this._scaledPivot.z;
  67413. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  67414. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  67415. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  67416. this._rotated.x += this._pivotBackTranslation.x;
  67417. this._rotated.y += this._pivotBackTranslation.y;
  67418. this._rotated.z += this._pivotBackTranslation.z;
  67419. 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;
  67420. 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;
  67421. 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;
  67422. if (this._computeBoundingBox) {
  67423. if (this._positions32[idx] < this._minimum.x) {
  67424. this._minimum.x = this._positions32[idx];
  67425. }
  67426. if (this._positions32[idx] > this._maximum.x) {
  67427. this._maximum.x = this._positions32[idx];
  67428. }
  67429. if (this._positions32[idx + 1] < this._minimum.y) {
  67430. this._minimum.y = this._positions32[idx + 1];
  67431. }
  67432. if (this._positions32[idx + 1] > this._maximum.y) {
  67433. this._maximum.y = this._positions32[idx + 1];
  67434. }
  67435. if (this._positions32[idx + 2] < this._minimum.z) {
  67436. this._minimum.z = this._positions32[idx + 2];
  67437. }
  67438. if (this._positions32[idx + 2] > this._maximum.z) {
  67439. this._maximum.z = this._positions32[idx + 2];
  67440. }
  67441. }
  67442. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  67443. if (!this._computeParticleVertex) {
  67444. this._normal.x = this._fixedNormal32[idx];
  67445. this._normal.y = this._fixedNormal32[idx + 1];
  67446. this._normal.z = this._fixedNormal32[idx + 2];
  67447. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  67448. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  67449. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  67450. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  67451. 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;
  67452. 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;
  67453. }
  67454. if (this._computeParticleColor && this._particle.color) {
  67455. this._colors32[colidx] = this._particle.color.r;
  67456. this._colors32[colidx + 1] = this._particle.color.g;
  67457. this._colors32[colidx + 2] = this._particle.color.b;
  67458. this._colors32[colidx + 3] = this._particle.color.a;
  67459. }
  67460. if (this._computeParticleTexture) {
  67461. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  67462. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  67463. }
  67464. }
  67465. }
  67466. // particle just set invisible : scaled to zero and positioned at the origin
  67467. else {
  67468. this._particle._stillInvisible = true; // mark the particle as invisible
  67469. for (pt = 0; pt < this._shape.length; pt++) {
  67470. idx = index + pt * 3;
  67471. colidx = colorIndex + pt * 4;
  67472. uvidx = uvIndex + pt * 2;
  67473. this._positions32[idx] = 0.0;
  67474. this._positions32[idx + 1] = 0.0;
  67475. this._positions32[idx + 2] = 0.0;
  67476. this._normals32[idx] = 0.0;
  67477. this._normals32[idx + 1] = 0.0;
  67478. this._normals32[idx + 2] = 0.0;
  67479. if (this._computeParticleColor && this._particle.color) {
  67480. this._colors32[colidx] = this._particle.color.r;
  67481. this._colors32[colidx + 1] = this._particle.color.g;
  67482. this._colors32[colidx + 2] = this._particle.color.b;
  67483. this._colors32[colidx + 3] = this._particle.color.a;
  67484. }
  67485. if (this._computeParticleTexture) {
  67486. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  67487. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  67488. }
  67489. }
  67490. }
  67491. // if the particle intersections must be computed : update the bbInfo
  67492. if (this._particlesIntersect) {
  67493. var bInfo = this._particle._boundingInfo;
  67494. var bBox = bInfo.boundingBox;
  67495. var bSphere = bInfo.boundingSphere;
  67496. if (!this._bSphereOnly) {
  67497. // place, scale and rotate the particle bbox within the SPS local system, then update it
  67498. for (var b = 0; b < bBox.vectors.length; b++) {
  67499. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  67500. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  67501. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  67502. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  67503. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  67504. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  67505. 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;
  67506. 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;
  67507. 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;
  67508. }
  67509. bBox._update(this.mesh._worldMatrix);
  67510. }
  67511. // place and scale the particle bouding sphere in the SPS local system, then update it
  67512. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  67513. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  67514. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  67515. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  67516. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  67517. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  67518. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  67519. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  67520. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  67521. 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));
  67522. bSphere._update(this.mesh._worldMatrix);
  67523. }
  67524. // increment indexes for the next particle
  67525. index = idx + 3;
  67526. colorIndex = colidx + 4;
  67527. uvIndex = uvidx + 2;
  67528. }
  67529. // if the VBO must be updated
  67530. if (update) {
  67531. if (this._computeParticleColor) {
  67532. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  67533. }
  67534. if (this._computeParticleTexture) {
  67535. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  67536. }
  67537. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  67538. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  67539. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  67540. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  67541. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  67542. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  67543. for (var i = 0; i < this._normals32.length; i++) {
  67544. this._fixedNormal32[i] = this._normals32[i];
  67545. }
  67546. }
  67547. if (!this.mesh.areNormalsFrozen) {
  67548. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  67549. }
  67550. }
  67551. if (this._depthSort && this._depthSortParticles) {
  67552. this.depthSortedParticles.sort(this._depthSortFunction);
  67553. var dspl = this.depthSortedParticles.length;
  67554. var sorted = 0;
  67555. var lind = 0;
  67556. var sind = 0;
  67557. var sid = 0;
  67558. for (sorted = 0; sorted < dspl; sorted++) {
  67559. lind = this.depthSortedParticles[sorted].indicesLength;
  67560. sind = this.depthSortedParticles[sorted].ind;
  67561. for (var i = 0; i < lind; i++) {
  67562. this._indices32[sid] = this._indices[sind + i];
  67563. sid++;
  67564. }
  67565. }
  67566. this.mesh.updateIndices(this._indices32);
  67567. }
  67568. }
  67569. if (this._computeBoundingBox) {
  67570. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  67571. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  67572. }
  67573. this.afterUpdateParticles(start, end, update);
  67574. return this;
  67575. };
  67576. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  67577. this._halfroll = this._roll * 0.5;
  67578. this._halfpitch = this._pitch * 0.5;
  67579. this._halfyaw = this._yaw * 0.5;
  67580. this._sinRoll = Math.sin(this._halfroll);
  67581. this._cosRoll = Math.cos(this._halfroll);
  67582. this._sinPitch = Math.sin(this._halfpitch);
  67583. this._cosPitch = Math.cos(this._halfpitch);
  67584. this._sinYaw = Math.sin(this._halfyaw);
  67585. this._cosYaw = Math.cos(this._halfyaw);
  67586. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  67587. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  67588. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  67589. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  67590. };
  67591. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  67592. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  67593. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  67594. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  67595. this._rotMatrix.m[3] = 0;
  67596. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  67597. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  67598. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  67599. this._rotMatrix.m[7] = 0;
  67600. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  67601. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  67602. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  67603. this._rotMatrix.m[11] = 0;
  67604. this._rotMatrix.m[12] = 0;
  67605. this._rotMatrix.m[13] = 0;
  67606. this._rotMatrix.m[14] = 0;
  67607. this._rotMatrix.m[15] = 1.0;
  67608. };
  67609. /**
  67610. * Disposes the SPS.
  67611. */
  67612. SolidParticleSystem.prototype.dispose = function () {
  67613. this.mesh.dispose();
  67614. this.vars = null;
  67615. // drop references to internal big arrays for the GC
  67616. this._positions = null;
  67617. this._indices = null;
  67618. this._normals = null;
  67619. this._uvs = null;
  67620. this._colors = null;
  67621. this._indices32 = null;
  67622. this._positions32 = null;
  67623. this._normals32 = null;
  67624. this._fixedNormal32 = null;
  67625. this._uvs32 = null;
  67626. this._colors32 = null;
  67627. this.pickedParticles = null;
  67628. };
  67629. /**
  67630. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  67631. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67632. * @returns the SPS.
  67633. */
  67634. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  67635. if (!this._isVisibilityBoxLocked) {
  67636. this.mesh.refreshBoundingInfo();
  67637. }
  67638. return this;
  67639. };
  67640. /**
  67641. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  67642. * @param size the size (float) of the visibility box
  67643. * note : this doesn't lock the SPS mesh bounding box.
  67644. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67645. */
  67646. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  67647. var vis = size / 2;
  67648. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  67649. };
  67650. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  67651. /**
  67652. * Gets whether the SPS as always visible or not
  67653. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67654. */
  67655. get: function () {
  67656. return this._alwaysVisible;
  67657. },
  67658. /**
  67659. * Sets the SPS as always visible or not
  67660. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67661. */
  67662. set: function (val) {
  67663. this._alwaysVisible = val;
  67664. this.mesh.alwaysSelectAsActiveMesh = val;
  67665. },
  67666. enumerable: true,
  67667. configurable: true
  67668. });
  67669. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  67670. /**
  67671. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  67672. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67673. */
  67674. get: function () {
  67675. return this._isVisibilityBoxLocked;
  67676. },
  67677. /**
  67678. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  67679. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67680. */
  67681. set: function (val) {
  67682. this._isVisibilityBoxLocked = val;
  67683. var boundingInfo = this.mesh.getBoundingInfo();
  67684. boundingInfo.isLocked = val;
  67685. },
  67686. enumerable: true,
  67687. configurable: true
  67688. });
  67689. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  67690. /**
  67691. * Gets if `setParticles()` computes the particle rotations or not.
  67692. * Default value : true. The SPS is faster when it's set to false.
  67693. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  67694. */
  67695. get: function () {
  67696. return this._computeParticleRotation;
  67697. },
  67698. /**
  67699. * Tells to `setParticles()` to compute the particle rotations or not.
  67700. * Default value : true. The SPS is faster when it's set to false.
  67701. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  67702. */
  67703. set: function (val) {
  67704. this._computeParticleRotation = val;
  67705. },
  67706. enumerable: true,
  67707. configurable: true
  67708. });
  67709. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  67710. /**
  67711. * Gets if `setParticles()` computes the particle colors or not.
  67712. * Default value : true. The SPS is faster when it's set to false.
  67713. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  67714. */
  67715. get: function () {
  67716. return this._computeParticleColor;
  67717. },
  67718. /**
  67719. * Tells to `setParticles()` to compute the particle colors or not.
  67720. * Default value : true. The SPS is faster when it's set to false.
  67721. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  67722. */
  67723. set: function (val) {
  67724. this._computeParticleColor = val;
  67725. },
  67726. enumerable: true,
  67727. configurable: true
  67728. });
  67729. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  67730. /**
  67731. * Gets if `setParticles()` computes the particle textures or not.
  67732. * Default value : true. The SPS is faster when it's set to false.
  67733. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  67734. */
  67735. get: function () {
  67736. return this._computeParticleTexture;
  67737. },
  67738. set: function (val) {
  67739. this._computeParticleTexture = val;
  67740. },
  67741. enumerable: true,
  67742. configurable: true
  67743. });
  67744. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  67745. /**
  67746. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  67747. * Default value : false. The SPS is faster when it's set to false.
  67748. * Note : the particle custom vertex positions aren't stored values.
  67749. */
  67750. get: function () {
  67751. return this._computeParticleVertex;
  67752. },
  67753. /**
  67754. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  67755. * Default value : false. The SPS is faster when it's set to false.
  67756. * Note : the particle custom vertex positions aren't stored values.
  67757. */
  67758. set: function (val) {
  67759. this._computeParticleVertex = val;
  67760. },
  67761. enumerable: true,
  67762. configurable: true
  67763. });
  67764. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  67765. /**
  67766. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  67767. */
  67768. get: function () {
  67769. return this._computeBoundingBox;
  67770. },
  67771. /**
  67772. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  67773. */
  67774. set: function (val) {
  67775. this._computeBoundingBox = val;
  67776. },
  67777. enumerable: true,
  67778. configurable: true
  67779. });
  67780. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  67781. /**
  67782. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  67783. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  67784. * Default : `true`
  67785. */
  67786. get: function () {
  67787. return this._depthSortParticles;
  67788. },
  67789. /**
  67790. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  67791. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  67792. * Default : `true`
  67793. */
  67794. set: function (val) {
  67795. this._depthSortParticles = val;
  67796. },
  67797. enumerable: true,
  67798. configurable: true
  67799. });
  67800. // =======================================================================
  67801. // Particle behavior logic
  67802. // these following methods may be overwritten by the user to fit his needs
  67803. /**
  67804. * This function does nothing. It may be overwritten to set all the particle first values.
  67805. * The SPS doesn't call this function, you may have to call it by your own.
  67806. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  67807. */
  67808. SolidParticleSystem.prototype.initParticles = function () {
  67809. };
  67810. /**
  67811. * This function does nothing. It may be overwritten to recycle a particle.
  67812. * The SPS doesn't call this function, you may have to call it by your own.
  67813. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  67814. * @param particle The particle to recycle
  67815. * @returns the recycled particle
  67816. */
  67817. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  67818. return particle;
  67819. };
  67820. /**
  67821. * Updates a particle : this function should be overwritten by the user.
  67822. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  67823. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  67824. * @example : just set a particle position or velocity and recycle conditions
  67825. * @param particle The particle to update
  67826. * @returns the updated particle
  67827. */
  67828. SolidParticleSystem.prototype.updateParticle = function (particle) {
  67829. return particle;
  67830. };
  67831. /**
  67832. * Updates a vertex of a particle : it can be overwritten by the user.
  67833. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  67834. * @param particle the current particle
  67835. * @param vertex the current index of the current particle
  67836. * @param pt the index of the current vertex in the particle shape
  67837. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  67838. * @example : just set a vertex particle position
  67839. * @returns the updated vertex
  67840. */
  67841. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  67842. return vertex;
  67843. };
  67844. /**
  67845. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  67846. * This does nothing and may be overwritten by the user.
  67847. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67848. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67849. * @param update the boolean update value actually passed to setParticles()
  67850. */
  67851. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  67852. };
  67853. /**
  67854. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  67855. * This will be passed three parameters.
  67856. * This does nothing and may be overwritten by the user.
  67857. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67858. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67859. * @param update the boolean update value actually passed to setParticles()
  67860. */
  67861. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  67862. };
  67863. return SolidParticleSystem;
  67864. }());
  67865. BABYLON.SolidParticleSystem = SolidParticleSystem;
  67866. })(BABYLON || (BABYLON = {}));
  67867. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  67868. var BABYLON;
  67869. (function (BABYLON) {
  67870. /**
  67871. * Class containing static functions to help procedurally build meshes
  67872. */
  67873. var MeshBuilder = /** @class */ (function () {
  67874. function MeshBuilder() {
  67875. }
  67876. MeshBuilder.updateSideOrientation = function (orientation) {
  67877. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  67878. return BABYLON.Mesh.DOUBLESIDE;
  67879. }
  67880. if (orientation === undefined || orientation === null) {
  67881. return BABYLON.Mesh.FRONTSIDE;
  67882. }
  67883. return orientation;
  67884. };
  67885. /**
  67886. * Creates a box mesh
  67887. * * The parameter `size` sets the size (float) of each box side (default 1)
  67888. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  67889. * * 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)
  67890. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  67891. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67892. * * 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
  67893. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67894. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  67895. * @param name defines the name of the mesh
  67896. * @param options defines the options used to create the mesh
  67897. * @param scene defines the hosting scene
  67898. * @returns the box mesh
  67899. */
  67900. MeshBuilder.CreateBox = function (name, options, scene) {
  67901. if (scene === void 0) { scene = null; }
  67902. var box = new BABYLON.Mesh(name, scene);
  67903. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67904. box._originalBuilderSideOrientation = options.sideOrientation;
  67905. var vertexData = BABYLON.VertexData.CreateBox(options);
  67906. vertexData.applyToMesh(box, options.updatable);
  67907. return box;
  67908. };
  67909. /**
  67910. * Creates a sphere mesh
  67911. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  67912. * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value of `diameter`)
  67913. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  67914. * * 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
  67915. * * 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)
  67916. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67917. * * 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
  67918. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67919. * @param name defines the name of the mesh
  67920. * @param options defines the options used to create the mesh
  67921. * @param scene defines the hosting scene
  67922. * @returns the sphere mesh
  67923. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  67924. */
  67925. MeshBuilder.CreateSphere = function (name, options, scene) {
  67926. var sphere = new BABYLON.Mesh(name, scene);
  67927. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67928. sphere._originalBuilderSideOrientation = options.sideOrientation;
  67929. var vertexData = BABYLON.VertexData.CreateSphere(options);
  67930. vertexData.applyToMesh(sphere, options.updatable);
  67931. return sphere;
  67932. };
  67933. /**
  67934. * Creates a plane polygonal mesh. By default, this is a disc
  67935. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  67936. * * 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
  67937. * * 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
  67938. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67939. * * 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
  67940. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67941. * @param name defines the name of the mesh
  67942. * @param options defines the options used to create the mesh
  67943. * @param scene defines the hosting scene
  67944. * @returns the plane polygonal mesh
  67945. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  67946. */
  67947. MeshBuilder.CreateDisc = function (name, options, scene) {
  67948. if (scene === void 0) { scene = null; }
  67949. var disc = new BABYLON.Mesh(name, scene);
  67950. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67951. disc._originalBuilderSideOrientation = options.sideOrientation;
  67952. var vertexData = BABYLON.VertexData.CreateDisc(options);
  67953. vertexData.applyToMesh(disc, options.updatable);
  67954. return disc;
  67955. };
  67956. /**
  67957. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  67958. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  67959. * * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value of `radius`)
  67960. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  67961. * * 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
  67962. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67963. * * 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
  67964. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67965. * @param name defines the name of the mesh
  67966. * @param options defines the options used to create the mesh
  67967. * @param scene defines the hosting scene
  67968. * @returns the icosahedron mesh
  67969. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  67970. */
  67971. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  67972. var sphere = new BABYLON.Mesh(name, scene);
  67973. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67974. sphere._originalBuilderSideOrientation = options.sideOrientation;
  67975. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  67976. vertexData.applyToMesh(sphere, options.updatable);
  67977. return sphere;
  67978. };
  67979. /**
  67980. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  67981. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  67982. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  67983. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  67984. * * 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
  67985. * * 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
  67986. * * 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
  67987. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67988. * * 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
  67989. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  67990. * * 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
  67991. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  67992. * * 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
  67993. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  67994. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67995. * @param name defines the name of the mesh
  67996. * @param options defines the options used to create the mesh
  67997. * @param scene defines the hosting scene
  67998. * @returns the ribbon mesh
  67999. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  68000. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  68001. */
  68002. MeshBuilder.CreateRibbon = function (name, options, scene) {
  68003. if (scene === void 0) { scene = null; }
  68004. var pathArray = options.pathArray;
  68005. var closeArray = options.closeArray;
  68006. var closePath = options.closePath;
  68007. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68008. var instance = options.instance;
  68009. var updatable = options.updatable;
  68010. if (instance) { // existing ribbon instance update
  68011. // positionFunction : ribbon case
  68012. // only pathArray and sideOrientation parameters are taken into account for positions update
  68013. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  68014. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  68015. var positionFunction = function (positions) {
  68016. var minlg = pathArray[0].length;
  68017. var mesh = instance;
  68018. var i = 0;
  68019. var ns = (mesh._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  68020. for (var si = 1; si <= ns; si++) {
  68021. for (var p = 0; p < pathArray.length; p++) {
  68022. var path = pathArray[p];
  68023. var l = path.length;
  68024. minlg = (minlg < l) ? minlg : l;
  68025. var j = 0;
  68026. while (j < minlg) {
  68027. positions[i] = path[j].x;
  68028. positions[i + 1] = path[j].y;
  68029. positions[i + 2] = path[j].z;
  68030. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  68031. BABYLON.Tmp.Vector3[0].x = path[j].x;
  68032. }
  68033. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  68034. BABYLON.Tmp.Vector3[1].x = path[j].x;
  68035. }
  68036. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  68037. BABYLON.Tmp.Vector3[0].y = path[j].y;
  68038. }
  68039. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  68040. BABYLON.Tmp.Vector3[1].y = path[j].y;
  68041. }
  68042. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  68043. BABYLON.Tmp.Vector3[0].z = path[j].z;
  68044. }
  68045. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  68046. BABYLON.Tmp.Vector3[1].z = path[j].z;
  68047. }
  68048. j++;
  68049. i += 3;
  68050. }
  68051. if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) {
  68052. positions[i] = path[0].x;
  68053. positions[i + 1] = path[0].y;
  68054. positions[i + 2] = path[0].z;
  68055. i += 3;
  68056. }
  68057. }
  68058. }
  68059. };
  68060. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68061. positionFunction(positions);
  68062. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[2], BABYLON.Tmp.Vector3[3]);
  68063. instance._boundingInfo.update(instance._worldMatrix);
  68064. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  68065. if (options.colors) {
  68066. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  68067. for (var c = 0; c < options.colors.length; c++) {
  68068. colors[c * 4] = options.colors[c].r;
  68069. colors[c * 4 + 1] = options.colors[c].g;
  68070. colors[c * 4 + 2] = options.colors[c].b;
  68071. colors[c * 4 + 3] = options.colors[c].a;
  68072. }
  68073. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  68074. }
  68075. if (options.uvs) {
  68076. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  68077. for (var i = 0; i < options.uvs.length; i++) {
  68078. uvs[i * 2] = options.uvs[i].x;
  68079. uvs[i * 2 + 1] = options.uvs[i].y;
  68080. }
  68081. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  68082. }
  68083. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  68084. var indices = instance.getIndices();
  68085. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68086. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  68087. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  68088. if (instance._creationDataStorage && instance._creationDataStorage.closePath) {
  68089. var indexFirst = 0;
  68090. var indexLast = 0;
  68091. for (var p = 0; p < pathArray.length; p++) {
  68092. indexFirst = instance._creationDataStorage.idx[p] * 3;
  68093. if (p + 1 < pathArray.length) {
  68094. indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3;
  68095. }
  68096. else {
  68097. indexLast = normals.length - 3;
  68098. }
  68099. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  68100. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  68101. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  68102. normals[indexLast] = normals[indexFirst];
  68103. normals[indexLast + 1] = normals[indexFirst + 1];
  68104. normals[indexLast + 2] = normals[indexFirst + 2];
  68105. }
  68106. }
  68107. if (!(instance.areNormalsFrozen)) {
  68108. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  68109. }
  68110. }
  68111. return instance;
  68112. }
  68113. else { // new ribbon creation
  68114. var ribbon = new BABYLON.Mesh(name, scene);
  68115. ribbon._originalBuilderSideOrientation = sideOrientation;
  68116. ribbon._creationDataStorage = new BABYLON._CreationDataStorage();
  68117. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  68118. if (closePath) {
  68119. ribbon._creationDataStorage.idx = vertexData._idx;
  68120. }
  68121. ribbon._creationDataStorage.closePath = closePath;
  68122. ribbon._creationDataStorage.closeArray = closeArray;
  68123. vertexData.applyToMesh(ribbon, updatable);
  68124. return ribbon;
  68125. }
  68126. };
  68127. /**
  68128. * Creates a cylinder or a cone mesh
  68129. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  68130. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  68131. * * 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.
  68132. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  68133. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  68134. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  68135. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  68136. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  68137. * * 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).
  68138. * * 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
  68139. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  68140. * * 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
  68141. * * 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.
  68142. * * If `enclose` is false, a ring surface is one element.
  68143. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  68144. * * 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
  68145. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68146. * * 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
  68147. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68148. * @param name defines the name of the mesh
  68149. * @param options defines the options used to create the mesh
  68150. * @param scene defines the hosting scene
  68151. * @returns the cylinder mesh
  68152. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  68153. */
  68154. MeshBuilder.CreateCylinder = function (name, options, scene) {
  68155. var cylinder = new BABYLON.Mesh(name, scene);
  68156. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68157. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  68158. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  68159. vertexData.applyToMesh(cylinder, options.updatable);
  68160. return cylinder;
  68161. };
  68162. /**
  68163. * Creates a torus mesh
  68164. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  68165. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  68166. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  68167. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68168. * * 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
  68169. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68170. * @param name defines the name of the mesh
  68171. * @param options defines the options used to create the mesh
  68172. * @param scene defines the hosting scene
  68173. * @returns the torus mesh
  68174. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  68175. */
  68176. MeshBuilder.CreateTorus = function (name, options, scene) {
  68177. var torus = new BABYLON.Mesh(name, scene);
  68178. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68179. torus._originalBuilderSideOrientation = options.sideOrientation;
  68180. var vertexData = BABYLON.VertexData.CreateTorus(options);
  68181. vertexData.applyToMesh(torus, options.updatable);
  68182. return torus;
  68183. };
  68184. /**
  68185. * Creates a torus knot mesh
  68186. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  68187. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  68188. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  68189. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  68190. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68191. * * 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
  68192. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68193. * @param name defines the name of the mesh
  68194. * @param options defines the options used to create the mesh
  68195. * @param scene defines the hosting scene
  68196. * @returns the torus knot mesh
  68197. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  68198. */
  68199. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  68200. var torusKnot = new BABYLON.Mesh(name, scene);
  68201. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68202. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  68203. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  68204. vertexData.applyToMesh(torusKnot, options.updatable);
  68205. return torusKnot;
  68206. };
  68207. /**
  68208. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  68209. * * 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
  68210. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  68211. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  68212. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  68213. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  68214. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  68215. * * 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
  68216. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  68217. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68218. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  68219. * @param name defines the name of the new line system
  68220. * @param options defines the options used to create the line system
  68221. * @param scene defines the hosting scene
  68222. * @returns a new line system mesh
  68223. */
  68224. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  68225. var instance = options.instance;
  68226. var lines = options.lines;
  68227. var colors = options.colors;
  68228. if (instance) { // lines update
  68229. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68230. var vertexColor;
  68231. var lineColors;
  68232. if (colors) {
  68233. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  68234. }
  68235. var i = 0;
  68236. var c = 0;
  68237. for (var l = 0; l < lines.length; l++) {
  68238. var points = lines[l];
  68239. for (var p = 0; p < points.length; p++) {
  68240. positions[i] = points[p].x;
  68241. positions[i + 1] = points[p].y;
  68242. positions[i + 2] = points[p].z;
  68243. if (colors && vertexColor) {
  68244. lineColors = colors[l];
  68245. vertexColor[c] = lineColors[p].r;
  68246. vertexColor[c + 1] = lineColors[p].g;
  68247. vertexColor[c + 2] = lineColors[p].b;
  68248. vertexColor[c + 3] = lineColors[p].a;
  68249. c += 4;
  68250. }
  68251. i += 3;
  68252. }
  68253. }
  68254. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  68255. if (colors && vertexColor) {
  68256. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  68257. }
  68258. return instance;
  68259. }
  68260. // line system creation
  68261. var useVertexColor = (colors) ? true : false;
  68262. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  68263. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  68264. vertexData.applyToMesh(lineSystem, options.updatable);
  68265. return lineSystem;
  68266. };
  68267. /**
  68268. * Creates a line mesh
  68269. * 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
  68270. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  68271. * * The parameter `points` is an array successive Vector3
  68272. * * 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
  68273. * * The optional parameter `colors` is an array of successive Color4, one per line point
  68274. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  68275. * * When updating an instance, remember that only point positions can change, not the number of points
  68276. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68277. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  68278. * @param name defines the name of the new line system
  68279. * @param options defines the options used to create the line system
  68280. * @param scene defines the hosting scene
  68281. * @returns a new line mesh
  68282. */
  68283. MeshBuilder.CreateLines = function (name, options, scene) {
  68284. if (scene === void 0) { scene = null; }
  68285. var colors = (options.colors) ? [options.colors] : null;
  68286. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  68287. return lines;
  68288. };
  68289. /**
  68290. * Creates a dashed line mesh
  68291. * * 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
  68292. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  68293. * * The parameter `points` is an array successive Vector3
  68294. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  68295. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  68296. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  68297. * * 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
  68298. * * When updating an instance, remember that only point positions can change, not the number of points
  68299. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68300. * @param name defines the name of the mesh
  68301. * @param options defines the options used to create the mesh
  68302. * @param scene defines the hosting scene
  68303. * @returns the dashed line mesh
  68304. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  68305. */
  68306. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  68307. if (scene === void 0) { scene = null; }
  68308. var points = options.points;
  68309. var instance = options.instance;
  68310. var gapSize = options.gapSize || 1;
  68311. var dashSize = options.dashSize || 3;
  68312. if (instance) { // dashed lines update
  68313. var positionFunction = function (positions) {
  68314. var curvect = BABYLON.Vector3.Zero();
  68315. var nbSeg = positions.length / 6;
  68316. var lg = 0;
  68317. var nb = 0;
  68318. var shft = 0;
  68319. var dashshft = 0;
  68320. var curshft = 0;
  68321. var p = 0;
  68322. var i = 0;
  68323. var j = 0;
  68324. for (i = 0; i < points.length - 1; i++) {
  68325. points[i + 1].subtractToRef(points[i], curvect);
  68326. lg += curvect.length();
  68327. }
  68328. shft = lg / nbSeg;
  68329. var dashSize = instance._creationDataStorage.dashSize;
  68330. var gapSize = instance._creationDataStorage.gapSize;
  68331. dashshft = dashSize * shft / (dashSize + gapSize);
  68332. for (i = 0; i < points.length - 1; i++) {
  68333. points[i + 1].subtractToRef(points[i], curvect);
  68334. nb = Math.floor(curvect.length() / shft);
  68335. curvect.normalize();
  68336. j = 0;
  68337. while (j < nb && p < positions.length) {
  68338. curshft = shft * j;
  68339. positions[p] = points[i].x + curshft * curvect.x;
  68340. positions[p + 1] = points[i].y + curshft * curvect.y;
  68341. positions[p + 2] = points[i].z + curshft * curvect.z;
  68342. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  68343. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  68344. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  68345. p += 6;
  68346. j++;
  68347. }
  68348. }
  68349. while (p < positions.length) {
  68350. positions[p] = points[i].x;
  68351. positions[p + 1] = points[i].y;
  68352. positions[p + 2] = points[i].z;
  68353. p += 3;
  68354. }
  68355. };
  68356. instance.updateMeshPositions(positionFunction, false);
  68357. return instance;
  68358. }
  68359. // dashed lines creation
  68360. var dashedLines = new BABYLON.LinesMesh(name, scene);
  68361. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  68362. vertexData.applyToMesh(dashedLines, options.updatable);
  68363. dashedLines._creationDataStorage = new BABYLON._CreationDataStorage();
  68364. dashedLines._creationDataStorage.dashSize = dashSize;
  68365. dashedLines._creationDataStorage.gapSize = gapSize;
  68366. return dashedLines;
  68367. };
  68368. /**
  68369. * 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.
  68370. * * 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.
  68371. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  68372. * * 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.
  68373. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  68374. * * 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
  68375. * * 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
  68376. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  68377. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68378. * * 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
  68379. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  68380. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68381. * @param name defines the name of the mesh
  68382. * @param options defines the options used to create the mesh
  68383. * @param scene defines the hosting scene
  68384. * @returns the extruded shape mesh
  68385. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  68386. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  68387. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  68388. */
  68389. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  68390. if (scene === void 0) { scene = null; }
  68391. var path = options.path;
  68392. var shape = options.shape;
  68393. var scale = options.scale || 1;
  68394. var rotation = options.rotation || 0;
  68395. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  68396. var updatable = options.updatable;
  68397. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68398. var instance = options.instance || null;
  68399. var invertUV = options.invertUV || false;
  68400. 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);
  68401. };
  68402. /**
  68403. * Creates an custom extruded shape mesh.
  68404. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  68405. * * 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.
  68406. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  68407. * * 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
  68408. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  68409. * * 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
  68410. * * It must returns a float value that will be the scale value applied to the shape on each path point
  68411. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  68412. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  68413. * * 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
  68414. * * 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
  68415. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  68416. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68417. * * 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
  68418. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  68419. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68420. * @param name defines the name of the mesh
  68421. * @param options defines the options used to create the mesh
  68422. * @param scene defines the hosting scene
  68423. * @returns the custom extruded shape mesh
  68424. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  68425. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  68426. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  68427. */
  68428. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  68429. var path = options.path;
  68430. var shape = options.shape;
  68431. var scaleFunction = options.scaleFunction || (function () { return 1; });
  68432. var rotationFunction = options.rotationFunction || (function () { return 0; });
  68433. var ribbonCloseArray = options.ribbonCloseArray || false;
  68434. var ribbonClosePath = options.ribbonClosePath || false;
  68435. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  68436. var updatable = options.updatable;
  68437. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68438. var instance = options.instance;
  68439. var invertUV = options.invertUV || false;
  68440. 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);
  68441. };
  68442. /**
  68443. * Creates lathe mesh.
  68444. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  68445. * * 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
  68446. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  68447. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  68448. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  68449. * * 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
  68450. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  68451. * * 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
  68452. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68453. * * 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
  68454. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  68455. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68456. * @param name defines the name of the mesh
  68457. * @param options defines the options used to create the mesh
  68458. * @param scene defines the hosting scene
  68459. * @returns the lathe mesh
  68460. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  68461. */
  68462. MeshBuilder.CreateLathe = function (name, options, scene) {
  68463. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  68464. var closed = (options.closed === undefined) ? true : options.closed;
  68465. var shape = options.shape;
  68466. var radius = options.radius || 1;
  68467. var tessellation = options.tessellation || 64;
  68468. var clip = options.clip || 0;
  68469. var updatable = options.updatable;
  68470. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68471. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  68472. var pi2 = Math.PI * 2;
  68473. var paths = new Array();
  68474. var invertUV = options.invertUV || false;
  68475. var i = 0;
  68476. var p = 0;
  68477. var step = pi2 / tessellation * arc;
  68478. var rotated;
  68479. var path = new Array();
  68480. for (i = 0; i <= tessellation - clip; i++) {
  68481. var path = [];
  68482. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  68483. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  68484. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  68485. }
  68486. for (p = 0; p < shape.length; p++) {
  68487. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  68488. path.push(rotated);
  68489. }
  68490. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  68491. 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));
  68492. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  68493. }
  68494. paths.push(path);
  68495. }
  68496. // lathe ribbon
  68497. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  68498. return lathe;
  68499. };
  68500. /**
  68501. * Creates a plane mesh
  68502. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  68503. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  68504. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  68505. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68506. * * 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
  68507. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68508. * @param name defines the name of the mesh
  68509. * @param options defines the options used to create the mesh
  68510. * @param scene defines the hosting scene
  68511. * @returns the plane mesh
  68512. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  68513. */
  68514. MeshBuilder.CreatePlane = function (name, options, scene) {
  68515. var plane = new BABYLON.Mesh(name, scene);
  68516. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68517. plane._originalBuilderSideOrientation = options.sideOrientation;
  68518. var vertexData = BABYLON.VertexData.CreatePlane(options);
  68519. vertexData.applyToMesh(plane, options.updatable);
  68520. if (options.sourcePlane) {
  68521. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  68522. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  68523. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  68524. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  68525. plane.rotate(vectorProduct, product);
  68526. }
  68527. }
  68528. return plane;
  68529. };
  68530. /**
  68531. * Creates a ground mesh
  68532. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  68533. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  68534. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68535. * @param name defines the name of the mesh
  68536. * @param options defines the options used to create the mesh
  68537. * @param scene defines the hosting scene
  68538. * @returns the ground mesh
  68539. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  68540. */
  68541. MeshBuilder.CreateGround = function (name, options, scene) {
  68542. var ground = new BABYLON.GroundMesh(name, scene);
  68543. ground._setReady(false);
  68544. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  68545. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  68546. ground._width = options.width || 1;
  68547. ground._height = options.height || 1;
  68548. ground._maxX = ground._width / 2;
  68549. ground._maxZ = ground._height / 2;
  68550. ground._minX = -ground._maxX;
  68551. ground._minZ = -ground._maxZ;
  68552. var vertexData = BABYLON.VertexData.CreateGround(options);
  68553. vertexData.applyToMesh(ground, options.updatable);
  68554. ground._setReady(true);
  68555. return ground;
  68556. };
  68557. /**
  68558. * Creates a tiled ground mesh
  68559. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  68560. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  68561. * * 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
  68562. * * 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
  68563. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68564. * @param name defines the name of the mesh
  68565. * @param options defines the options used to create the mesh
  68566. * @param scene defines the hosting scene
  68567. * @returns the tiled ground mesh
  68568. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  68569. */
  68570. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  68571. var tiledGround = new BABYLON.Mesh(name, scene);
  68572. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  68573. vertexData.applyToMesh(tiledGround, options.updatable);
  68574. return tiledGround;
  68575. };
  68576. /**
  68577. * Creates a ground mesh from a height map
  68578. * * The parameter `url` sets the URL of the height map image resource.
  68579. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  68580. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  68581. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  68582. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  68583. * * 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.
  68584. * * 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).
  68585. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  68586. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68587. * @param name defines the name of the mesh
  68588. * @param url defines the url to the height map
  68589. * @param options defines the options used to create the mesh
  68590. * @param scene defines the hosting scene
  68591. * @returns the ground mesh
  68592. * @see http://doc.babylonjs.com/babylon101/height_map
  68593. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  68594. */
  68595. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  68596. var width = options.width || 10.0;
  68597. var height = options.height || 10.0;
  68598. var subdivisions = options.subdivisions || 1 | 0;
  68599. var minHeight = options.minHeight || 0.0;
  68600. var maxHeight = options.maxHeight || 1.0;
  68601. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  68602. var alphaFilter = options.alphaFilter || 0.0;
  68603. var updatable = options.updatable;
  68604. var onReady = options.onReady;
  68605. var ground = new BABYLON.GroundMesh(name, scene);
  68606. ground._subdivisionsX = subdivisions;
  68607. ground._subdivisionsY = subdivisions;
  68608. ground._width = width;
  68609. ground._height = height;
  68610. ground._maxX = ground._width / 2.0;
  68611. ground._maxZ = ground._height / 2.0;
  68612. ground._minX = -ground._maxX;
  68613. ground._minZ = -ground._maxZ;
  68614. ground._setReady(false);
  68615. var onload = function (img) {
  68616. // Getting height map data
  68617. var canvas = document.createElement("canvas");
  68618. var context = canvas.getContext("2d");
  68619. if (!context) {
  68620. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  68621. }
  68622. if (scene.isDisposed) {
  68623. return;
  68624. }
  68625. var bufferWidth = img.width;
  68626. var bufferHeight = img.height;
  68627. canvas.width = bufferWidth;
  68628. canvas.height = bufferHeight;
  68629. context.drawImage(img, 0, 0);
  68630. // Create VertexData from map data
  68631. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  68632. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  68633. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  68634. width: width, height: height,
  68635. subdivisions: subdivisions,
  68636. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  68637. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  68638. alphaFilter: alphaFilter
  68639. });
  68640. vertexData.applyToMesh(ground, updatable);
  68641. //execute ready callback, if set
  68642. if (onReady) {
  68643. onReady(ground);
  68644. }
  68645. ground._setReady(true);
  68646. };
  68647. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  68648. return ground;
  68649. };
  68650. /**
  68651. * Creates a polygon mesh
  68652. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  68653. * * 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
  68654. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68655. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68656. * * 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)
  68657. * * Remember you can only change the shape positions, not their number when updating a polygon
  68658. * @param name defines the name of the mesh
  68659. * @param options defines the options used to create the mesh
  68660. * @param scene defines the hosting scene
  68661. * @returns the polygon mesh
  68662. */
  68663. MeshBuilder.CreatePolygon = function (name, options, scene) {
  68664. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68665. var shape = options.shape;
  68666. var holes = options.holes || [];
  68667. var depth = options.depth || 0;
  68668. var contours = [];
  68669. var hole = [];
  68670. for (var i = 0; i < shape.length; i++) {
  68671. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  68672. }
  68673. var epsilon = 0.00000001;
  68674. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  68675. contours.pop();
  68676. }
  68677. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  68678. for (var hNb = 0; hNb < holes.length; hNb++) {
  68679. hole = [];
  68680. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  68681. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  68682. }
  68683. polygonTriangulation.addHole(hole);
  68684. }
  68685. var polygon = polygonTriangulation.build(options.updatable, depth);
  68686. polygon._originalBuilderSideOrientation = options.sideOrientation;
  68687. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  68688. vertexData.applyToMesh(polygon, options.updatable);
  68689. return polygon;
  68690. };
  68691. /**
  68692. * Creates an extruded polygon mesh, with depth in the Y direction.
  68693. * * 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)
  68694. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  68695. * @param name defines the name of the mesh
  68696. * @param options defines the options used to create the mesh
  68697. * @param scene defines the hosting scene
  68698. * @returns the polygon mesh
  68699. */
  68700. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  68701. return MeshBuilder.CreatePolygon(name, options, scene);
  68702. };
  68703. /**
  68704. * Creates a tube mesh.
  68705. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  68706. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  68707. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  68708. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  68709. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  68710. * * 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)
  68711. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  68712. * * 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
  68713. * * 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
  68714. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68715. * * 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
  68716. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  68717. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68718. * @param name defines the name of the mesh
  68719. * @param options defines the options used to create the mesh
  68720. * @param scene defines the hosting scene
  68721. * @returns the tube mesh
  68722. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  68723. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  68724. */
  68725. MeshBuilder.CreateTube = function (name, options, scene) {
  68726. var path = options.path;
  68727. var instance = options.instance;
  68728. var radius = 1.0;
  68729. if (options.radius !== undefined) {
  68730. radius = options.radius;
  68731. }
  68732. else if (instance) {
  68733. radius = instance._creationDataStorage.radius;
  68734. }
  68735. var tessellation = options.tessellation || 64 | 0;
  68736. var radiusFunction = options.radiusFunction || null;
  68737. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  68738. var invertUV = options.invertUV || false;
  68739. var updatable = options.updatable;
  68740. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68741. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  68742. // tube geometry
  68743. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  68744. var tangents = path3D.getTangents();
  68745. var normals = path3D.getNormals();
  68746. var distances = path3D.getDistances();
  68747. var pi2 = Math.PI * 2;
  68748. var step = pi2 / tessellation * arc;
  68749. var returnRadius = function () { return radius; };
  68750. var radiusFunctionFinal = radiusFunction || returnRadius;
  68751. var circlePath;
  68752. var rad;
  68753. var normal;
  68754. var rotated;
  68755. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  68756. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  68757. for (var i = 0; i < path.length; i++) {
  68758. rad = radiusFunctionFinal(i, distances[i]); // current radius
  68759. circlePath = Array(); // current circle array
  68760. normal = normals[i]; // current normal
  68761. for (var t = 0; t < tessellation; t++) {
  68762. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  68763. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  68764. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  68765. rotated.scaleInPlace(rad).addInPlace(path[i]);
  68766. circlePath[t] = rotated;
  68767. }
  68768. circlePaths[index] = circlePath;
  68769. index++;
  68770. }
  68771. // cap
  68772. var capPath = function (nbPoints, pathIndex) {
  68773. var pointCap = Array();
  68774. for (var i = 0; i < nbPoints; i++) {
  68775. pointCap.push(path[pathIndex]);
  68776. }
  68777. return pointCap;
  68778. };
  68779. switch (cap) {
  68780. case BABYLON.Mesh.NO_CAP:
  68781. break;
  68782. case BABYLON.Mesh.CAP_START:
  68783. circlePaths[0] = capPath(tessellation, 0);
  68784. circlePaths[1] = circlePaths[2].slice(0);
  68785. break;
  68786. case BABYLON.Mesh.CAP_END:
  68787. circlePaths[index] = circlePaths[index - 1].slice(0);
  68788. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  68789. break;
  68790. case BABYLON.Mesh.CAP_ALL:
  68791. circlePaths[0] = capPath(tessellation, 0);
  68792. circlePaths[1] = circlePaths[2].slice(0);
  68793. circlePaths[index] = circlePaths[index - 1].slice(0);
  68794. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  68795. break;
  68796. default:
  68797. break;
  68798. }
  68799. return circlePaths;
  68800. };
  68801. var path3D;
  68802. var pathArray;
  68803. if (instance) { // tube update
  68804. var storage = instance._creationDataStorage;
  68805. var arc = options.arc || storage.arc;
  68806. path3D = storage.path3D.update(path);
  68807. pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc);
  68808. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  68809. // Update mode, no need to recreate the storage.
  68810. storage.path3D = path3D;
  68811. storage.pathArray = pathArray;
  68812. storage.arc = arc;
  68813. storage.radius = radius;
  68814. return instance;
  68815. }
  68816. // tube creation
  68817. path3D = new BABYLON.Path3D(path);
  68818. var newPathArray = new Array();
  68819. cap = (cap < 0 || cap > 3) ? 0 : cap;
  68820. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  68821. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  68822. tube._creationDataStorage.pathArray = pathArray;
  68823. tube._creationDataStorage.path3D = path3D;
  68824. tube._creationDataStorage.tessellation = tessellation;
  68825. tube._creationDataStorage.cap = cap;
  68826. tube._creationDataStorage.arc = options.arc;
  68827. tube._creationDataStorage.radius = radius;
  68828. return tube;
  68829. };
  68830. /**
  68831. * Creates a polyhedron mesh
  68832. * * 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
  68833. * * The parameter `size` (positive float, default 1) sets the polygon size
  68834. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  68835. * * 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`
  68836. * * 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
  68837. * * 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)`)
  68838. * * 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
  68839. * * 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
  68840. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68841. * * 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
  68842. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68843. * @param name defines the name of the mesh
  68844. * @param options defines the options used to create the mesh
  68845. * @param scene defines the hosting scene
  68846. * @returns the polyhedron mesh
  68847. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  68848. */
  68849. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  68850. var polyhedron = new BABYLON.Mesh(name, scene);
  68851. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68852. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  68853. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  68854. vertexData.applyToMesh(polyhedron, options.updatable);
  68855. return polyhedron;
  68856. };
  68857. /**
  68858. * Creates a decal mesh.
  68859. * 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
  68860. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  68861. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  68862. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  68863. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  68864. * @param name defines the name of the mesh
  68865. * @param sourceMesh defines the mesh where the decal must be applied
  68866. * @param options defines the options used to create the mesh
  68867. * @param scene defines the hosting scene
  68868. * @returns the decal mesh
  68869. * @see http://doc.babylonjs.com/how_to/decals
  68870. */
  68871. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  68872. var indices = sourceMesh.getIndices();
  68873. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68874. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68875. var position = options.position || BABYLON.Vector3.Zero();
  68876. var normal = options.normal || BABYLON.Vector3.Up();
  68877. var size = options.size || BABYLON.Vector3.One();
  68878. var angle = options.angle || 0;
  68879. // Getting correct rotation
  68880. if (!normal) {
  68881. var target = new BABYLON.Vector3(0, 0, 1);
  68882. var camera = sourceMesh.getScene().activeCamera;
  68883. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  68884. normal = camera.globalPosition.subtract(cameraWorldTarget);
  68885. }
  68886. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  68887. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  68888. var pitch = Math.atan2(normal.y, len);
  68889. // Matrix
  68890. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  68891. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  68892. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  68893. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  68894. var vertexData = new BABYLON.VertexData();
  68895. vertexData.indices = [];
  68896. vertexData.positions = [];
  68897. vertexData.normals = [];
  68898. vertexData.uvs = [];
  68899. var currentVertexDataIndex = 0;
  68900. var extractDecalVector3 = function (indexId) {
  68901. var result = new BABYLON.PositionNormalVertex();
  68902. if (!indices || !positions || !normals) {
  68903. return result;
  68904. }
  68905. var vertexId = indices[indexId];
  68906. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  68907. // Send vector to decal local world
  68908. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  68909. // Get normal
  68910. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  68911. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  68912. return result;
  68913. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  68914. var clip = function (vertices, axis) {
  68915. if (vertices.length === 0) {
  68916. return vertices;
  68917. }
  68918. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  68919. var clipVertices = function (v0, v1) {
  68920. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  68921. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  68922. };
  68923. var result = new Array();
  68924. for (var index = 0; index < vertices.length; index += 3) {
  68925. var v1Out;
  68926. var v2Out;
  68927. var v3Out;
  68928. var total = 0;
  68929. var nV1 = null;
  68930. var nV2 = null;
  68931. var nV3 = null;
  68932. var nV4 = null;
  68933. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  68934. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  68935. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  68936. v1Out = d1 > 0;
  68937. v2Out = d2 > 0;
  68938. v3Out = d3 > 0;
  68939. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  68940. switch (total) {
  68941. case 0:
  68942. result.push(vertices[index]);
  68943. result.push(vertices[index + 1]);
  68944. result.push(vertices[index + 2]);
  68945. break;
  68946. case 1:
  68947. if (v1Out) {
  68948. nV1 = vertices[index + 1];
  68949. nV2 = vertices[index + 2];
  68950. nV3 = clipVertices(vertices[index], nV1);
  68951. nV4 = clipVertices(vertices[index], nV2);
  68952. }
  68953. if (v2Out) {
  68954. nV1 = vertices[index];
  68955. nV2 = vertices[index + 2];
  68956. nV3 = clipVertices(vertices[index + 1], nV1);
  68957. nV4 = clipVertices(vertices[index + 1], nV2);
  68958. result.push(nV3);
  68959. result.push(nV2.clone());
  68960. result.push(nV1.clone());
  68961. result.push(nV2.clone());
  68962. result.push(nV3.clone());
  68963. result.push(nV4);
  68964. break;
  68965. }
  68966. if (v3Out) {
  68967. nV1 = vertices[index];
  68968. nV2 = vertices[index + 1];
  68969. nV3 = clipVertices(vertices[index + 2], nV1);
  68970. nV4 = clipVertices(vertices[index + 2], nV2);
  68971. }
  68972. if (nV1 && nV2 && nV3 && nV4) {
  68973. result.push(nV1.clone());
  68974. result.push(nV2.clone());
  68975. result.push(nV3);
  68976. result.push(nV4);
  68977. result.push(nV3.clone());
  68978. result.push(nV2.clone());
  68979. }
  68980. break;
  68981. case 2:
  68982. if (!v1Out) {
  68983. nV1 = vertices[index].clone();
  68984. nV2 = clipVertices(nV1, vertices[index + 1]);
  68985. nV3 = clipVertices(nV1, vertices[index + 2]);
  68986. result.push(nV1);
  68987. result.push(nV2);
  68988. result.push(nV3);
  68989. }
  68990. if (!v2Out) {
  68991. nV1 = vertices[index + 1].clone();
  68992. nV2 = clipVertices(nV1, vertices[index + 2]);
  68993. nV3 = clipVertices(nV1, vertices[index]);
  68994. result.push(nV1);
  68995. result.push(nV2);
  68996. result.push(nV3);
  68997. }
  68998. if (!v3Out) {
  68999. nV1 = vertices[index + 2].clone();
  69000. nV2 = clipVertices(nV1, vertices[index]);
  69001. nV3 = clipVertices(nV1, vertices[index + 1]);
  69002. result.push(nV1);
  69003. result.push(nV2);
  69004. result.push(nV3);
  69005. }
  69006. break;
  69007. case 3:
  69008. break;
  69009. }
  69010. }
  69011. return result;
  69012. };
  69013. for (var index = 0; index < indices.length; index += 3) {
  69014. var faceVertices = new Array();
  69015. faceVertices.push(extractDecalVector3(index));
  69016. faceVertices.push(extractDecalVector3(index + 1));
  69017. faceVertices.push(extractDecalVector3(index + 2));
  69018. // Clip
  69019. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  69020. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  69021. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  69022. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  69023. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  69024. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  69025. if (faceVertices.length === 0) {
  69026. continue;
  69027. }
  69028. // Add UVs and get back to world
  69029. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  69030. var vertex = faceVertices[vIndex];
  69031. //TODO check for Int32Array | Uint32Array | Uint16Array
  69032. vertexData.indices.push(currentVertexDataIndex);
  69033. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  69034. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  69035. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  69036. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  69037. currentVertexDataIndex++;
  69038. }
  69039. }
  69040. // Return mesh
  69041. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  69042. vertexData.applyToMesh(decal);
  69043. decal.position = position.clone();
  69044. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  69045. return decal;
  69046. };
  69047. // Privates
  69048. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  69049. // extrusion geometry
  69050. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  69051. var tangents = path3D.getTangents();
  69052. var normals = path3D.getNormals();
  69053. var binormals = path3D.getBinormals();
  69054. var distances = path3D.getDistances();
  69055. var angle = 0;
  69056. var returnScale = function () { return scale !== null ? scale : 1; };
  69057. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  69058. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  69059. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  69060. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  69061. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  69062. for (var i = 0; i < curve.length; i++) {
  69063. var shapePath = new Array();
  69064. var angleStep = rotate(i, distances[i]);
  69065. var scaleRatio = scl(i, distances[i]);
  69066. for (var p = 0; p < shape.length; p++) {
  69067. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  69068. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  69069. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  69070. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  69071. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  69072. shapePath[p] = rotated;
  69073. }
  69074. shapePaths[index] = shapePath;
  69075. angle += angleStep;
  69076. index++;
  69077. }
  69078. // cap
  69079. var capPath = function (shapePath) {
  69080. var pointCap = Array();
  69081. var barycenter = BABYLON.Vector3.Zero();
  69082. var i;
  69083. for (i = 0; i < shapePath.length; i++) {
  69084. barycenter.addInPlace(shapePath[i]);
  69085. }
  69086. barycenter.scaleInPlace(1.0 / shapePath.length);
  69087. for (i = 0; i < shapePath.length; i++) {
  69088. pointCap.push(barycenter);
  69089. }
  69090. return pointCap;
  69091. };
  69092. switch (cap) {
  69093. case BABYLON.Mesh.NO_CAP:
  69094. break;
  69095. case BABYLON.Mesh.CAP_START:
  69096. shapePaths[0] = capPath(shapePaths[2]);
  69097. shapePaths[1] = shapePaths[2];
  69098. break;
  69099. case BABYLON.Mesh.CAP_END:
  69100. shapePaths[index] = shapePaths[index - 1];
  69101. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  69102. break;
  69103. case BABYLON.Mesh.CAP_ALL:
  69104. shapePaths[0] = capPath(shapePaths[2]);
  69105. shapePaths[1] = shapePaths[2];
  69106. shapePaths[index] = shapePaths[index - 1];
  69107. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  69108. break;
  69109. default:
  69110. break;
  69111. }
  69112. return shapePaths;
  69113. };
  69114. var path3D;
  69115. var pathArray;
  69116. if (instance) { // instance update
  69117. var storage = instance._creationDataStorage;
  69118. path3D = storage.path3D.update(curve);
  69119. pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom);
  69120. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  69121. return instance;
  69122. }
  69123. // extruded shape creation
  69124. path3D = new BABYLON.Path3D(curve);
  69125. var newShapePaths = new Array();
  69126. cap = (cap < 0 || cap > 3) ? 0 : cap;
  69127. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  69128. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  69129. extrudedGeneric._creationDataStorage.pathArray = pathArray;
  69130. extrudedGeneric._creationDataStorage.path3D = path3D;
  69131. extrudedGeneric._creationDataStorage.cap = cap;
  69132. return extrudedGeneric;
  69133. };
  69134. return MeshBuilder;
  69135. }());
  69136. BABYLON.MeshBuilder = MeshBuilder;
  69137. })(BABYLON || (BABYLON = {}));
  69138. //# sourceMappingURL=babylon.meshBuilder.js.map
  69139. var BABYLON;
  69140. (function (BABYLON) {
  69141. /**
  69142. * Draco compression (https://google.github.io/draco/)
  69143. *
  69144. * This class wraps the Draco module.
  69145. *
  69146. * **Encoder**
  69147. *
  69148. * The encoder is not currently implemented.
  69149. *
  69150. * **Decoder**
  69151. *
  69152. * By default, the configuration points to a copy of the Draco decoder files for glTF from the babylon.js preview cdn https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js.
  69153. *
  69154. * To update the configuration, use the following code:
  69155. * ```javascript
  69156. * BABYLON.DracoCompression.Configuration = {
  69157. * decoder: {
  69158. * wasmUrl: "<url to the WebAssembly library>",
  69159. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  69160. * fallbackUrl: "<url to the fallback JavaScript library>",
  69161. * }
  69162. * };
  69163. * ```
  69164. *
  69165. * 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.
  69166. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  69167. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  69168. *
  69169. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  69170. * ```javascript
  69171. * var dracoCompression = new BABYLON.DracoCompression();
  69172. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  69173. * [BABYLON.VertexBuffer.PositionKind]: 0
  69174. * });
  69175. * ```
  69176. *
  69177. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  69178. */
  69179. var DracoCompression = /** @class */ (function () {
  69180. /**
  69181. * Constructor
  69182. */
  69183. function DracoCompression() {
  69184. }
  69185. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  69186. /**
  69187. * Returns true if the decoder is available.
  69188. */
  69189. get: function () {
  69190. if (typeof DracoDecoderModule !== "undefined") {
  69191. return true;
  69192. }
  69193. var decoder = DracoCompression.Configuration.decoder;
  69194. if (decoder) {
  69195. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  69196. return true;
  69197. }
  69198. if (decoder.fallbackUrl) {
  69199. return true;
  69200. }
  69201. }
  69202. return false;
  69203. },
  69204. enumerable: true,
  69205. configurable: true
  69206. });
  69207. /**
  69208. * Stop all async operations and release resources.
  69209. */
  69210. DracoCompression.prototype.dispose = function () {
  69211. };
  69212. /**
  69213. * Decode Draco compressed mesh data to vertex data.
  69214. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  69215. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  69216. * @returns A promise that resolves with the decoded vertex data
  69217. */
  69218. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  69219. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  69220. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  69221. var module = wrappedModule.module;
  69222. var vertexData = new BABYLON.VertexData();
  69223. var buffer = new module.DecoderBuffer();
  69224. buffer.Init(dataView, dataView.byteLength);
  69225. var decoder = new module.Decoder();
  69226. var geometry;
  69227. var status;
  69228. try {
  69229. var type = decoder.GetEncodedGeometryType(buffer);
  69230. switch (type) {
  69231. case module.TRIANGULAR_MESH:
  69232. geometry = new module.Mesh();
  69233. status = decoder.DecodeBufferToMesh(buffer, geometry);
  69234. break;
  69235. case module.POINT_CLOUD:
  69236. geometry = new module.PointCloud();
  69237. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  69238. break;
  69239. default:
  69240. throw new Error("Invalid geometry type " + type);
  69241. }
  69242. if (!status.ok() || !geometry.ptr) {
  69243. throw new Error(status.error_msg());
  69244. }
  69245. var numPoints = geometry.num_points();
  69246. if (type === module.TRIANGULAR_MESH) {
  69247. var numFaces = geometry.num_faces();
  69248. var faceIndices = new module.DracoInt32Array();
  69249. try {
  69250. var indices = new Uint32Array(numFaces * 3);
  69251. for (var i = 0; i < numFaces; i++) {
  69252. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  69253. var offset = i * 3;
  69254. indices[offset + 0] = faceIndices.GetValue(0);
  69255. indices[offset + 1] = faceIndices.GetValue(1);
  69256. indices[offset + 2] = faceIndices.GetValue(2);
  69257. }
  69258. vertexData.indices = indices;
  69259. }
  69260. finally {
  69261. module.destroy(faceIndices);
  69262. }
  69263. }
  69264. for (var kind in attributes) {
  69265. var uniqueId = attributes[kind];
  69266. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  69267. var dracoData = new module.DracoFloat32Array();
  69268. try {
  69269. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  69270. var babylonData = new Float32Array(numPoints * attribute.num_components());
  69271. for (var i = 0; i < babylonData.length; i++) {
  69272. babylonData[i] = dracoData.GetValue(i);
  69273. }
  69274. vertexData.set(babylonData, kind);
  69275. }
  69276. finally {
  69277. module.destroy(dracoData);
  69278. }
  69279. }
  69280. }
  69281. finally {
  69282. if (geometry) {
  69283. module.destroy(geometry);
  69284. }
  69285. module.destroy(decoder);
  69286. module.destroy(buffer);
  69287. }
  69288. return vertexData;
  69289. });
  69290. };
  69291. DracoCompression._GetDecoderModule = function () {
  69292. if (!DracoCompression._DecoderModulePromise) {
  69293. var promise = null;
  69294. var config_1 = {};
  69295. if (typeof DracoDecoderModule !== "undefined") {
  69296. promise = Promise.resolve();
  69297. }
  69298. else {
  69299. var decoder = DracoCompression.Configuration.decoder;
  69300. if (decoder) {
  69301. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  69302. promise = Promise.all([
  69303. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  69304. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  69305. config_1.wasmBinary = data;
  69306. })
  69307. ]);
  69308. }
  69309. else if (decoder.fallbackUrl) {
  69310. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  69311. }
  69312. }
  69313. }
  69314. if (!promise) {
  69315. throw new Error("Draco decoder module is not available");
  69316. }
  69317. DracoCompression._DecoderModulePromise = promise.then(function () {
  69318. return new Promise(function (resolve) {
  69319. config_1.onModuleLoaded = function (decoderModule) {
  69320. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  69321. resolve({ module: decoderModule });
  69322. };
  69323. DracoDecoderModule(config_1);
  69324. });
  69325. });
  69326. }
  69327. return DracoCompression._DecoderModulePromise;
  69328. };
  69329. DracoCompression._LoadScriptAsync = function (url) {
  69330. return new Promise(function (resolve, reject) {
  69331. BABYLON.Tools.LoadScript(url, function () {
  69332. resolve();
  69333. }, function (message) {
  69334. reject(new Error(message));
  69335. });
  69336. });
  69337. };
  69338. DracoCompression._LoadFileAsync = function (url) {
  69339. return new Promise(function (resolve, reject) {
  69340. BABYLON.Tools.LoadFile(url, function (data) {
  69341. resolve(data);
  69342. }, undefined, undefined, true, function (request, exception) {
  69343. reject(exception);
  69344. });
  69345. });
  69346. };
  69347. /**
  69348. * The configuration. Defaults to the following urls:
  69349. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  69350. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  69351. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  69352. */
  69353. DracoCompression.Configuration = {
  69354. decoder: {
  69355. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  69356. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  69357. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  69358. }
  69359. };
  69360. return DracoCompression;
  69361. }());
  69362. BABYLON.DracoCompression = DracoCompression;
  69363. })(BABYLON || (BABYLON = {}));
  69364. //# sourceMappingURL=babylon.dracoCompression.js.map
  69365. var BABYLON;
  69366. (function (BABYLON) {
  69367. // Sets the default audio engine to Babylon JS.
  69368. BABYLON.Engine.AudioEngineFactory = function (hostElement) { return new AudioEngine(hostElement); };
  69369. /**
  69370. * This represents the default audio engine used in babylon.
  69371. * It is responsible to play, synchronize and analyse sounds throughout the application.
  69372. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  69373. */
  69374. var AudioEngine = /** @class */ (function () {
  69375. /**
  69376. * Instantiates a new audio engine.
  69377. *
  69378. * There should be only one per page as some browsers restrict the number
  69379. * of audio contexts you can create.
  69380. * @param hostElement defines the host element where to display the mute icon if necessary
  69381. */
  69382. function AudioEngine(hostElement) {
  69383. if (hostElement === void 0) { hostElement = null; }
  69384. var _this = this;
  69385. this._audioContext = null;
  69386. this._audioContextInitialized = false;
  69387. this._muteButton = null;
  69388. /**
  69389. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  69390. */
  69391. this.canUseWebAudio = false;
  69392. /**
  69393. * Defines if Babylon should emit a warning if WebAudio is not supported.
  69394. * @ignoreNaming
  69395. */
  69396. this.WarnedWebAudioUnsupported = false;
  69397. /**
  69398. * Gets whether or not mp3 are supported by your browser.
  69399. */
  69400. this.isMP3supported = false;
  69401. /**
  69402. * Gets whether or not ogg are supported by your browser.
  69403. */
  69404. this.isOGGsupported = false;
  69405. /**
  69406. * Gets whether audio has been unlocked on the device.
  69407. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  69408. * a user interaction has happened.
  69409. */
  69410. this.unlocked = true;
  69411. /**
  69412. * Defines if the audio engine relies on a custom unlocked button.
  69413. * In this case, the embedded button will not be displayed.
  69414. */
  69415. this.useCustomUnlockedButton = false;
  69416. /**
  69417. * Event raised when audio has been unlocked on the browser.
  69418. */
  69419. this.onAudioUnlockedObservable = new BABYLON.Observable();
  69420. /**
  69421. * Event raised when audio has been locked on the browser.
  69422. */
  69423. this.onAudioLockedObservable = new BABYLON.Observable();
  69424. this._tryToRun = false;
  69425. this._onResize = function () {
  69426. _this._moveButtonToTopLeft();
  69427. };
  69428. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  69429. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  69430. this.canUseWebAudio = true;
  69431. }
  69432. var audioElem = document.createElement('audio');
  69433. this._hostElement = hostElement;
  69434. try {
  69435. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  69436. this.isMP3supported = true;
  69437. }
  69438. }
  69439. catch (e) {
  69440. // protect error during capability check.
  69441. }
  69442. try {
  69443. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  69444. this.isOGGsupported = true;
  69445. }
  69446. }
  69447. catch (e) {
  69448. // protect error during capability check.
  69449. }
  69450. }
  69451. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  69452. /**
  69453. * Gets the current AudioContext if available.
  69454. */
  69455. get: function () {
  69456. if (!this._audioContextInitialized) {
  69457. this._initializeAudioContext();
  69458. }
  69459. else {
  69460. if (!this.unlocked && !this._muteButton) {
  69461. this._displayMuteButton();
  69462. }
  69463. }
  69464. return this._audioContext;
  69465. },
  69466. enumerable: true,
  69467. configurable: true
  69468. });
  69469. /**
  69470. * Flags the audio engine in Locked state.
  69471. * This happens due to new browser policies preventing audio to autoplay.
  69472. */
  69473. AudioEngine.prototype.lock = function () {
  69474. this._triggerSuspendedState();
  69475. };
  69476. /**
  69477. * Unlocks the audio engine once a user action has been done on the dom.
  69478. * This is helpful to resume play once browser policies have been satisfied.
  69479. */
  69480. AudioEngine.prototype.unlock = function () {
  69481. this._triggerRunningState();
  69482. };
  69483. AudioEngine.prototype._resumeAudioContext = function () {
  69484. var result;
  69485. if (this._audioContext.resume) {
  69486. result = this._audioContext.resume();
  69487. }
  69488. return result || Promise.resolve();
  69489. };
  69490. AudioEngine.prototype._initializeAudioContext = function () {
  69491. try {
  69492. if (this.canUseWebAudio) {
  69493. this._audioContext = new AudioContext();
  69494. // create a global volume gain node
  69495. this.masterGain = this._audioContext.createGain();
  69496. this.masterGain.gain.value = 1;
  69497. this.masterGain.connect(this._audioContext.destination);
  69498. this._audioContextInitialized = true;
  69499. if (this._audioContext.state === "running") {
  69500. // Do not wait for the promise to unlock.
  69501. this._triggerRunningState();
  69502. }
  69503. }
  69504. }
  69505. catch (e) {
  69506. this.canUseWebAudio = false;
  69507. BABYLON.Tools.Error("Web Audio: " + e.message);
  69508. }
  69509. };
  69510. AudioEngine.prototype._triggerRunningState = function () {
  69511. var _this = this;
  69512. if (this._tryToRun) {
  69513. return;
  69514. }
  69515. this._tryToRun = true;
  69516. this._resumeAudioContext()
  69517. .then(function () {
  69518. _this._tryToRun = false;
  69519. if (_this._muteButton) {
  69520. _this._hideMuteButton();
  69521. }
  69522. }).catch(function () {
  69523. _this._tryToRun = false;
  69524. _this.unlocked = false;
  69525. });
  69526. // Notify users that the audio stack is unlocked/unmuted
  69527. this.unlocked = true;
  69528. this.onAudioUnlockedObservable.notifyObservers(this);
  69529. };
  69530. AudioEngine.prototype._triggerSuspendedState = function () {
  69531. this.unlocked = false;
  69532. this.onAudioLockedObservable.notifyObservers(this);
  69533. this._displayMuteButton();
  69534. };
  69535. AudioEngine.prototype._displayMuteButton = function () {
  69536. var _this = this;
  69537. if (this.useCustomUnlockedButton) {
  69538. return;
  69539. }
  69540. this._muteButton = document.createElement("BUTTON");
  69541. this._muteButton.className = "babylonUnmuteIcon";
  69542. this._muteButton.id = "babylonUnmuteIconBtn";
  69543. this._muteButton.title = "Unmute";
  69544. var css = ".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }";
  69545. var style = document.createElement('style');
  69546. style.appendChild(document.createTextNode(css));
  69547. document.getElementsByTagName('head')[0].appendChild(style);
  69548. document.body.appendChild(this._muteButton);
  69549. this._moveButtonToTopLeft();
  69550. this._muteButton.addEventListener('touchend', function () {
  69551. _this._triggerRunningState();
  69552. }, true);
  69553. this._muteButton.addEventListener('click', function () {
  69554. _this._triggerRunningState();
  69555. }, true);
  69556. window.addEventListener("resize", this._onResize);
  69557. };
  69558. AudioEngine.prototype._moveButtonToTopLeft = function () {
  69559. if (this._hostElement && this._muteButton) {
  69560. this._muteButton.style.top = this._hostElement.offsetTop + 20 + "px";
  69561. this._muteButton.style.left = this._hostElement.offsetLeft + 20 + "px";
  69562. }
  69563. };
  69564. AudioEngine.prototype._hideMuteButton = function () {
  69565. if (this._muteButton) {
  69566. document.body.removeChild(this._muteButton);
  69567. this._muteButton = null;
  69568. }
  69569. };
  69570. /**
  69571. * Destroy and release the resources associated with the audio ccontext.
  69572. */
  69573. AudioEngine.prototype.dispose = function () {
  69574. if (this.canUseWebAudio && this._audioContextInitialized) {
  69575. if (this._connectedAnalyser && this._audioContext) {
  69576. this._connectedAnalyser.stopDebugCanvas();
  69577. this._connectedAnalyser.dispose();
  69578. this.masterGain.disconnect();
  69579. this.masterGain.connect(this._audioContext.destination);
  69580. this._connectedAnalyser = null;
  69581. }
  69582. this.masterGain.gain.value = 1;
  69583. }
  69584. this.WarnedWebAudioUnsupported = false;
  69585. this._hideMuteButton();
  69586. window.removeEventListener("resize", this._onResize);
  69587. this.onAudioUnlockedObservable.clear();
  69588. this.onAudioLockedObservable.clear();
  69589. };
  69590. /**
  69591. * Gets the global volume sets on the master gain.
  69592. * @returns the global volume if set or -1 otherwise
  69593. */
  69594. AudioEngine.prototype.getGlobalVolume = function () {
  69595. if (this.canUseWebAudio && this._audioContextInitialized) {
  69596. return this.masterGain.gain.value;
  69597. }
  69598. else {
  69599. return -1;
  69600. }
  69601. };
  69602. /**
  69603. * Sets the global volume of your experience (sets on the master gain).
  69604. * @param newVolume Defines the new global volume of the application
  69605. */
  69606. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  69607. if (this.canUseWebAudio && this._audioContextInitialized) {
  69608. this.masterGain.gain.value = newVolume;
  69609. }
  69610. };
  69611. /**
  69612. * Connect the audio engine to an audio analyser allowing some amazing
  69613. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  69614. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  69615. * @param analyser The analyser to connect to the engine
  69616. */
  69617. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  69618. if (this._connectedAnalyser) {
  69619. this._connectedAnalyser.stopDebugCanvas();
  69620. }
  69621. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  69622. this._connectedAnalyser = analyser;
  69623. this.masterGain.disconnect();
  69624. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  69625. }
  69626. };
  69627. return AudioEngine;
  69628. }());
  69629. BABYLON.AudioEngine = AudioEngine;
  69630. })(BABYLON || (BABYLON = {}));
  69631. //# sourceMappingURL=babylon.audioEngine.js.map
  69632. var BABYLON;
  69633. (function (BABYLON) {
  69634. /**
  69635. * Defines a sound that can be played in the application.
  69636. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  69637. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  69638. */
  69639. var Sound = /** @class */ (function () {
  69640. /**
  69641. * Create a sound and attach it to a scene
  69642. * @param name Name of your sound
  69643. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  69644. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  69645. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  69646. */
  69647. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  69648. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  69649. var _this = this;
  69650. /**
  69651. * Does the sound autoplay once loaded.
  69652. */
  69653. this.autoplay = false;
  69654. /**
  69655. * Does the sound loop after it finishes playing once.
  69656. */
  69657. this.loop = false;
  69658. /**
  69659. * Does the sound use a custom attenuation curve to simulate the falloff
  69660. * happening when the source gets further away from the camera.
  69661. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  69662. */
  69663. this.useCustomAttenuation = false;
  69664. /**
  69665. * Is this sound currently played.
  69666. */
  69667. this.isPlaying = false;
  69668. /**
  69669. * Is this sound currently paused.
  69670. */
  69671. this.isPaused = false;
  69672. /**
  69673. * Does this sound enables spatial sound.
  69674. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69675. */
  69676. this.spatialSound = false;
  69677. /**
  69678. * Define the reference distance the sound should be heard perfectly.
  69679. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69680. */
  69681. this.refDistance = 1;
  69682. /**
  69683. * Define the roll off factor of spatial sounds.
  69684. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69685. */
  69686. this.rolloffFactor = 1;
  69687. /**
  69688. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  69689. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69690. */
  69691. this.maxDistance = 100;
  69692. /**
  69693. * Define the distance attenuation model the sound will follow.
  69694. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69695. */
  69696. this.distanceModel = "linear";
  69697. /**
  69698. * Observable event when the current playing sound finishes.
  69699. */
  69700. this.onEndedObservable = new BABYLON.Observable();
  69701. this._panningModel = "equalpower";
  69702. this._playbackRate = 1;
  69703. this._streaming = false;
  69704. this._startTime = 0;
  69705. this._startOffset = 0;
  69706. this._position = BABYLON.Vector3.Zero();
  69707. /** @hidden */
  69708. this._positionInEmitterSpace = false;
  69709. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  69710. this._volume = 1;
  69711. this._isReadyToPlay = false;
  69712. this._isDirectional = false;
  69713. // Used if you'd like to create a directional sound.
  69714. // If not set, the sound will be omnidirectional
  69715. this._coneInnerAngle = 360;
  69716. this._coneOuterAngle = 360;
  69717. this._coneOuterGain = 0;
  69718. this._isOutputConnected = false;
  69719. this._urlType = "Unknown";
  69720. this.name = name;
  69721. this._scene = scene;
  69722. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69723. if (!compo) {
  69724. compo = new BABYLON.AudioSceneComponent(scene);
  69725. scene._addComponent(compo);
  69726. }
  69727. this._readyToPlayCallback = readyToPlayCallback;
  69728. // Default custom attenuation function is a linear attenuation
  69729. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  69730. if (currentDistance < maxDistance) {
  69731. return currentVolume * (1 - currentDistance / maxDistance);
  69732. }
  69733. else {
  69734. return 0;
  69735. }
  69736. };
  69737. if (options) {
  69738. this.autoplay = options.autoplay || false;
  69739. this.loop = options.loop || false;
  69740. // if volume === 0, we need another way to check this option
  69741. if (options.volume !== undefined) {
  69742. this._volume = options.volume;
  69743. }
  69744. this.spatialSound = options.spatialSound || false;
  69745. this.maxDistance = options.maxDistance || 100;
  69746. this.useCustomAttenuation = options.useCustomAttenuation || false;
  69747. this.rolloffFactor = options.rolloffFactor || 1;
  69748. this.refDistance = options.refDistance || 1;
  69749. this.distanceModel = options.distanceModel || "linear";
  69750. this._playbackRate = options.playbackRate || 1;
  69751. this._streaming = options.streaming || false;
  69752. }
  69753. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  69754. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  69755. this._soundGain.gain.value = this._volume;
  69756. this._inputAudioNode = this._soundGain;
  69757. this._outputAudioNode = this._soundGain;
  69758. if (this.spatialSound) {
  69759. this._createSpatialParameters();
  69760. }
  69761. this._scene.mainSoundTrack.AddSound(this);
  69762. var validParameter = true;
  69763. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  69764. if (urlOrArrayBuffer) {
  69765. try {
  69766. if (typeof (urlOrArrayBuffer) === "string") {
  69767. this._urlType = "String";
  69768. }
  69769. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  69770. this._urlType = "ArrayBuffer";
  69771. }
  69772. else if (urlOrArrayBuffer instanceof MediaStream) {
  69773. this._urlType = "MediaStream";
  69774. }
  69775. else if (Array.isArray(urlOrArrayBuffer)) {
  69776. this._urlType = "Array";
  69777. }
  69778. var urls = [];
  69779. var codecSupportedFound = false;
  69780. switch (this._urlType) {
  69781. case "MediaStream":
  69782. this._streaming = true;
  69783. this._isReadyToPlay = true;
  69784. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  69785. if (this.autoplay) {
  69786. this.play();
  69787. }
  69788. if (this._readyToPlayCallback) {
  69789. this._readyToPlayCallback();
  69790. }
  69791. break;
  69792. case "ArrayBuffer":
  69793. if (urlOrArrayBuffer.byteLength > 0) {
  69794. codecSupportedFound = true;
  69795. this._soundLoaded(urlOrArrayBuffer);
  69796. }
  69797. break;
  69798. case "String":
  69799. urls.push(urlOrArrayBuffer);
  69800. case "Array":
  69801. if (urls.length === 0) {
  69802. urls = urlOrArrayBuffer;
  69803. }
  69804. // If we found a supported format, we load it immediately and stop the loop
  69805. for (var i = 0; i < urls.length; i++) {
  69806. var url = urls[i];
  69807. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  69808. codecSupportedFound = true;
  69809. }
  69810. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  69811. codecSupportedFound = true;
  69812. }
  69813. if (url.indexOf(".wav", url.length - 4) !== -1) {
  69814. codecSupportedFound = true;
  69815. }
  69816. if (url.indexOf("blob:") !== -1) {
  69817. codecSupportedFound = true;
  69818. }
  69819. if (codecSupportedFound) {
  69820. // Loading sound using XHR2
  69821. if (!this._streaming) {
  69822. this._scene._loadFile(url, function (data) {
  69823. _this._soundLoaded(data);
  69824. }, undefined, true, true, function (exception) {
  69825. if (exception) {
  69826. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  69827. }
  69828. BABYLON.Tools.Error("Sound creation aborted.");
  69829. _this._scene.mainSoundTrack.RemoveSound(_this);
  69830. });
  69831. }
  69832. // Streaming sound using HTML5 Audio tag
  69833. else {
  69834. this._htmlAudioElement = new Audio(url);
  69835. this._htmlAudioElement.controls = false;
  69836. this._htmlAudioElement.loop = this.loop;
  69837. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  69838. this._htmlAudioElement.preload = "auto";
  69839. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  69840. _this._isReadyToPlay = true;
  69841. if (_this.autoplay) {
  69842. _this.play();
  69843. }
  69844. if (_this._readyToPlayCallback) {
  69845. _this._readyToPlayCallback();
  69846. }
  69847. });
  69848. document.body.appendChild(this._htmlAudioElement);
  69849. this._htmlAudioElement.load();
  69850. }
  69851. break;
  69852. }
  69853. }
  69854. break;
  69855. default:
  69856. validParameter = false;
  69857. break;
  69858. }
  69859. if (!validParameter) {
  69860. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  69861. }
  69862. else {
  69863. if (!codecSupportedFound) {
  69864. this._isReadyToPlay = true;
  69865. // Simulating a ready to play event to avoid breaking code path
  69866. if (this._readyToPlayCallback) {
  69867. window.setTimeout(function () {
  69868. if (_this._readyToPlayCallback) {
  69869. _this._readyToPlayCallback();
  69870. }
  69871. }, 1000);
  69872. }
  69873. }
  69874. }
  69875. }
  69876. catch (ex) {
  69877. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  69878. this._scene.mainSoundTrack.RemoveSound(this);
  69879. }
  69880. }
  69881. }
  69882. else {
  69883. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  69884. this._scene.mainSoundTrack.AddSound(this);
  69885. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  69886. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  69887. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  69888. }
  69889. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  69890. if (this._readyToPlayCallback) {
  69891. window.setTimeout(function () {
  69892. if (_this._readyToPlayCallback) {
  69893. _this._readyToPlayCallback();
  69894. }
  69895. }, 1000);
  69896. }
  69897. }
  69898. }
  69899. /**
  69900. * Release the sound and its associated resources
  69901. */
  69902. Sound.prototype.dispose = function () {
  69903. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69904. if (this.isPlaying) {
  69905. this.stop();
  69906. }
  69907. this._isReadyToPlay = false;
  69908. if (this.soundTrackId === -1) {
  69909. this._scene.mainSoundTrack.RemoveSound(this);
  69910. }
  69911. else if (this._scene.soundTracks) {
  69912. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  69913. }
  69914. if (this._soundGain) {
  69915. this._soundGain.disconnect();
  69916. this._soundGain = null;
  69917. }
  69918. if (this._soundPanner) {
  69919. this._soundPanner.disconnect();
  69920. this._soundPanner = null;
  69921. }
  69922. if (this._soundSource) {
  69923. this._soundSource.disconnect();
  69924. this._soundSource = null;
  69925. }
  69926. this._audioBuffer = null;
  69927. if (this._htmlAudioElement) {
  69928. this._htmlAudioElement.pause();
  69929. this._htmlAudioElement.src = "";
  69930. document.body.removeChild(this._htmlAudioElement);
  69931. }
  69932. if (this._streamingSource) {
  69933. this._streamingSource.disconnect();
  69934. }
  69935. if (this._connectedMesh && this._registerFunc) {
  69936. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  69937. this._connectedMesh = null;
  69938. }
  69939. }
  69940. };
  69941. /**
  69942. * Gets if the sounds is ready to be played or not.
  69943. * @returns true if ready, otherwise false
  69944. */
  69945. Sound.prototype.isReady = function () {
  69946. return this._isReadyToPlay;
  69947. };
  69948. Sound.prototype._soundLoaded = function (audioData) {
  69949. var _this = this;
  69950. if (!BABYLON.Engine.audioEngine.audioContext) {
  69951. return;
  69952. }
  69953. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  69954. _this._audioBuffer = buffer;
  69955. _this._isReadyToPlay = true;
  69956. if (_this.autoplay) {
  69957. _this.play();
  69958. }
  69959. if (_this._readyToPlayCallback) {
  69960. _this._readyToPlayCallback();
  69961. }
  69962. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  69963. };
  69964. /**
  69965. * Sets the data of the sound from an audiobuffer
  69966. * @param audioBuffer The audioBuffer containing the data
  69967. */
  69968. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  69969. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69970. this._audioBuffer = audioBuffer;
  69971. this._isReadyToPlay = true;
  69972. }
  69973. };
  69974. /**
  69975. * Updates the current sounds options such as maxdistance, loop...
  69976. * @param options A JSON object containing values named as the object properties
  69977. */
  69978. Sound.prototype.updateOptions = function (options) {
  69979. if (options) {
  69980. this.loop = options.loop || this.loop;
  69981. this.maxDistance = options.maxDistance || this.maxDistance;
  69982. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  69983. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  69984. this.refDistance = options.refDistance || this.refDistance;
  69985. this.distanceModel = options.distanceModel || this.distanceModel;
  69986. this._playbackRate = options.playbackRate || this._playbackRate;
  69987. this._updateSpatialParameters();
  69988. if (this.isPlaying) {
  69989. if (this._streaming && this._htmlAudioElement) {
  69990. this._htmlAudioElement.playbackRate = this._playbackRate;
  69991. }
  69992. else {
  69993. if (this._soundSource) {
  69994. this._soundSource.playbackRate.value = this._playbackRate;
  69995. }
  69996. }
  69997. }
  69998. }
  69999. };
  70000. Sound.prototype._createSpatialParameters = function () {
  70001. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  70002. if (this._scene.headphone) {
  70003. this._panningModel = "HRTF";
  70004. }
  70005. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  70006. this._updateSpatialParameters();
  70007. this._soundPanner.connect(this._outputAudioNode);
  70008. this._inputAudioNode = this._soundPanner;
  70009. }
  70010. };
  70011. Sound.prototype._updateSpatialParameters = function () {
  70012. if (this.spatialSound && this._soundPanner) {
  70013. if (this.useCustomAttenuation) {
  70014. // Tricks to disable in a way embedded Web Audio attenuation
  70015. this._soundPanner.distanceModel = "linear";
  70016. this._soundPanner.maxDistance = Number.MAX_VALUE;
  70017. this._soundPanner.refDistance = 1;
  70018. this._soundPanner.rolloffFactor = 1;
  70019. this._soundPanner.panningModel = this._panningModel;
  70020. }
  70021. else {
  70022. this._soundPanner.distanceModel = this.distanceModel;
  70023. this._soundPanner.maxDistance = this.maxDistance;
  70024. this._soundPanner.refDistance = this.refDistance;
  70025. this._soundPanner.rolloffFactor = this.rolloffFactor;
  70026. this._soundPanner.panningModel = this._panningModel;
  70027. }
  70028. }
  70029. };
  70030. /**
  70031. * Switch the panning model to HRTF:
  70032. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  70033. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70034. */
  70035. Sound.prototype.switchPanningModelToHRTF = function () {
  70036. this._panningModel = "HRTF";
  70037. this._switchPanningModel();
  70038. };
  70039. /**
  70040. * Switch the panning model to Equal Power:
  70041. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  70042. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70043. */
  70044. Sound.prototype.switchPanningModelToEqualPower = function () {
  70045. this._panningModel = "equalpower";
  70046. this._switchPanningModel();
  70047. };
  70048. Sound.prototype._switchPanningModel = function () {
  70049. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  70050. this._soundPanner.panningModel = this._panningModel;
  70051. }
  70052. };
  70053. /**
  70054. * Connect this sound to a sound track audio node like gain...
  70055. * @param soundTrackAudioNode the sound track audio node to connect to
  70056. */
  70057. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  70058. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70059. if (this._isOutputConnected) {
  70060. this._outputAudioNode.disconnect();
  70061. }
  70062. this._outputAudioNode.connect(soundTrackAudioNode);
  70063. this._isOutputConnected = true;
  70064. }
  70065. };
  70066. /**
  70067. * Transform this sound into a directional source
  70068. * @param coneInnerAngle Size of the inner cone in degree
  70069. * @param coneOuterAngle Size of the outer cone in degree
  70070. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  70071. */
  70072. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  70073. if (coneOuterAngle < coneInnerAngle) {
  70074. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  70075. return;
  70076. }
  70077. this._coneInnerAngle = coneInnerAngle;
  70078. this._coneOuterAngle = coneOuterAngle;
  70079. this._coneOuterGain = coneOuterGain;
  70080. this._isDirectional = true;
  70081. if (this.isPlaying && this.loop) {
  70082. this.stop();
  70083. this.play();
  70084. }
  70085. };
  70086. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  70087. /**
  70088. * Gets or sets the inner angle for the directional cone.
  70089. */
  70090. get: function () {
  70091. return this._coneInnerAngle;
  70092. },
  70093. /**
  70094. * Gets or sets the inner angle for the directional cone.
  70095. */
  70096. set: function (value) {
  70097. if (value != this._coneInnerAngle) {
  70098. if (this._coneOuterAngle < value) {
  70099. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70100. return;
  70101. }
  70102. this._coneInnerAngle = value;
  70103. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  70104. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  70105. }
  70106. }
  70107. },
  70108. enumerable: true,
  70109. configurable: true
  70110. });
  70111. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  70112. /**
  70113. * Gets or sets the outer angle for the directional cone.
  70114. */
  70115. get: function () {
  70116. return this._coneOuterAngle;
  70117. },
  70118. /**
  70119. * Gets or sets the outer angle for the directional cone.
  70120. */
  70121. set: function (value) {
  70122. if (value != this._coneOuterAngle) {
  70123. if (value < this._coneInnerAngle) {
  70124. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70125. return;
  70126. }
  70127. this._coneOuterAngle = value;
  70128. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  70129. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  70130. }
  70131. }
  70132. },
  70133. enumerable: true,
  70134. configurable: true
  70135. });
  70136. /**
  70137. * Sets the position of the emitter if spatial sound is enabled
  70138. * @param newPosition Defines the new posisiton
  70139. */
  70140. Sound.prototype.setPosition = function (newPosition) {
  70141. this._position = newPosition;
  70142. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  70143. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  70144. }
  70145. };
  70146. /**
  70147. * Sets the local direction of the emitter if spatial sound is enabled
  70148. * @param newLocalDirection Defines the new local direction
  70149. */
  70150. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  70151. this._localDirection = newLocalDirection;
  70152. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  70153. this._updateDirection();
  70154. }
  70155. };
  70156. Sound.prototype._updateDirection = function () {
  70157. if (!this._connectedMesh || !this._soundPanner) {
  70158. return;
  70159. }
  70160. var mat = this._connectedMesh.getWorldMatrix();
  70161. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  70162. direction.normalize();
  70163. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  70164. };
  70165. /** @hidden */
  70166. Sound.prototype.updateDistanceFromListener = function () {
  70167. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  70168. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  70169. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  70170. }
  70171. };
  70172. /**
  70173. * Sets a new custom attenuation function for the sound.
  70174. * @param callback Defines the function used for the attenuation
  70175. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  70176. */
  70177. Sound.prototype.setAttenuationFunction = function (callback) {
  70178. this._customAttenuationFunction = callback;
  70179. };
  70180. /**
  70181. * Play the sound
  70182. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  70183. * @param offset (optional) Start the sound setting it at a specific time
  70184. */
  70185. Sound.prototype.play = function (time, offset) {
  70186. var _this = this;
  70187. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  70188. try {
  70189. if (this._startOffset < 0) {
  70190. time = -this._startOffset;
  70191. this._startOffset = 0;
  70192. }
  70193. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  70194. if (!this._soundSource || !this._streamingSource) {
  70195. if (this.spatialSound && this._soundPanner) {
  70196. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  70197. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  70198. }
  70199. if (this._isDirectional) {
  70200. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  70201. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  70202. this._soundPanner.coneOuterGain = this._coneOuterGain;
  70203. if (this._connectedMesh) {
  70204. this._updateDirection();
  70205. }
  70206. else {
  70207. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  70208. }
  70209. }
  70210. }
  70211. }
  70212. if (this._streaming) {
  70213. if (!this._streamingSource) {
  70214. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  70215. this._htmlAudioElement.onended = function () { _this._onended(); };
  70216. this._htmlAudioElement.playbackRate = this._playbackRate;
  70217. }
  70218. this._streamingSource.disconnect();
  70219. this._streamingSource.connect(this._inputAudioNode);
  70220. if (this._htmlAudioElement) {
  70221. // required to manage properly the new suspended default state of Chrome
  70222. // When the option 'streaming: true' is used, we need first to wait for
  70223. // the audio engine to be unlocked by a user gesture before trying to play
  70224. // an HTML Audio elememt
  70225. var tryToPlay = function () {
  70226. if (BABYLON.Engine.audioEngine.unlocked) {
  70227. var playPromise = _this._htmlAudioElement.play();
  70228. // In browsers that don’t yet support this functionality,
  70229. // playPromise won’t be defined.
  70230. if (playPromise !== undefined) {
  70231. playPromise.catch(function (error) {
  70232. // Automatic playback failed.
  70233. // Waiting for the audio engine to be unlocked by user click on unmute
  70234. BABYLON.Engine.audioEngine.lock();
  70235. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  70236. });
  70237. }
  70238. }
  70239. else {
  70240. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  70241. }
  70242. };
  70243. tryToPlay();
  70244. }
  70245. }
  70246. else {
  70247. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  70248. this._soundSource.buffer = this._audioBuffer;
  70249. this._soundSource.connect(this._inputAudioNode);
  70250. this._soundSource.loop = this.loop;
  70251. this._soundSource.playbackRate.value = this._playbackRate;
  70252. this._soundSource.onended = function () { _this._onended(); };
  70253. if (this._soundSource.buffer) {
  70254. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  70255. }
  70256. }
  70257. this._startTime = startTime;
  70258. this.isPlaying = true;
  70259. this.isPaused = false;
  70260. }
  70261. catch (ex) {
  70262. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  70263. }
  70264. }
  70265. };
  70266. Sound.prototype._onended = function () {
  70267. this.isPlaying = false;
  70268. if (this.onended) {
  70269. this.onended();
  70270. }
  70271. this.onEndedObservable.notifyObservers(this);
  70272. };
  70273. /**
  70274. * Stop the sound
  70275. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  70276. */
  70277. Sound.prototype.stop = function (time) {
  70278. if (this.isPlaying) {
  70279. if (this._streaming) {
  70280. if (this._htmlAudioElement) {
  70281. this._htmlAudioElement.pause();
  70282. // Test needed for Firefox or it will generate an Invalid State Error
  70283. if (this._htmlAudioElement.currentTime > 0) {
  70284. this._htmlAudioElement.currentTime = 0;
  70285. }
  70286. }
  70287. else {
  70288. this._streamingSource.disconnect();
  70289. }
  70290. }
  70291. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  70292. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  70293. this._soundSource.stop(stopTime);
  70294. this._soundSource.onended = function () { };
  70295. if (!this.isPaused) {
  70296. this._startOffset = 0;
  70297. }
  70298. }
  70299. this.isPlaying = false;
  70300. }
  70301. };
  70302. /**
  70303. * Put the sound in pause
  70304. */
  70305. Sound.prototype.pause = function () {
  70306. if (this.isPlaying) {
  70307. this.isPaused = true;
  70308. if (this._streaming) {
  70309. if (this._htmlAudioElement) {
  70310. this._htmlAudioElement.pause();
  70311. }
  70312. else {
  70313. this._streamingSource.disconnect();
  70314. }
  70315. }
  70316. else if (BABYLON.Engine.audioEngine.audioContext) {
  70317. this.stop(0);
  70318. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  70319. }
  70320. }
  70321. };
  70322. /**
  70323. * Sets a dedicated volume for this sounds
  70324. * @param newVolume Define the new volume of the sound
  70325. * @param time Define in how long the sound should be at this value
  70326. */
  70327. Sound.prototype.setVolume = function (newVolume, time) {
  70328. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  70329. if (time && BABYLON.Engine.audioEngine.audioContext) {
  70330. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  70331. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  70332. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  70333. }
  70334. else {
  70335. this._soundGain.gain.value = newVolume;
  70336. }
  70337. }
  70338. this._volume = newVolume;
  70339. };
  70340. /**
  70341. * Set the sound play back rate
  70342. * @param newPlaybackRate Define the playback rate the sound should be played at
  70343. */
  70344. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  70345. this._playbackRate = newPlaybackRate;
  70346. if (this.isPlaying) {
  70347. if (this._streaming && this._htmlAudioElement) {
  70348. this._htmlAudioElement.playbackRate = this._playbackRate;
  70349. }
  70350. else if (this._soundSource) {
  70351. this._soundSource.playbackRate.value = this._playbackRate;
  70352. }
  70353. }
  70354. };
  70355. /**
  70356. * Gets the volume of the sound.
  70357. * @returns the volume of the sound
  70358. */
  70359. Sound.prototype.getVolume = function () {
  70360. return this._volume;
  70361. };
  70362. /**
  70363. * Attach the sound to a dedicated mesh
  70364. * @param meshToConnectTo The mesh to connect the sound with
  70365. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  70366. */
  70367. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  70368. var _this = this;
  70369. if (this._connectedMesh && this._registerFunc) {
  70370. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  70371. this._registerFunc = null;
  70372. }
  70373. this._connectedMesh = meshToConnectTo;
  70374. if (!this.spatialSound) {
  70375. this.spatialSound = true;
  70376. this._createSpatialParameters();
  70377. if (this.isPlaying && this.loop) {
  70378. this.stop();
  70379. this.play();
  70380. }
  70381. }
  70382. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  70383. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  70384. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  70385. };
  70386. /**
  70387. * Detach the sound from the previously attached mesh
  70388. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  70389. */
  70390. Sound.prototype.detachFromMesh = function () {
  70391. if (this._connectedMesh && this._registerFunc) {
  70392. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  70393. this._registerFunc = null;
  70394. this._connectedMesh = null;
  70395. }
  70396. };
  70397. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  70398. if (!node.getBoundingInfo) {
  70399. return;
  70400. }
  70401. var mesh = node;
  70402. if (this._positionInEmitterSpace) {
  70403. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  70404. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  70405. }
  70406. else {
  70407. var boundingInfo = mesh.getBoundingInfo();
  70408. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  70409. }
  70410. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  70411. this._updateDirection();
  70412. }
  70413. };
  70414. /**
  70415. * Clone the current sound in the scene.
  70416. * @returns the new sound clone
  70417. */
  70418. Sound.prototype.clone = function () {
  70419. var _this = this;
  70420. if (!this._streaming) {
  70421. var setBufferAndRun = function () {
  70422. if (_this._isReadyToPlay) {
  70423. clonedSound._audioBuffer = _this.getAudioBuffer();
  70424. clonedSound._isReadyToPlay = true;
  70425. if (clonedSound.autoplay) {
  70426. clonedSound.play();
  70427. }
  70428. }
  70429. else {
  70430. window.setTimeout(setBufferAndRun, 300);
  70431. }
  70432. };
  70433. var currentOptions = {
  70434. autoplay: this.autoplay, loop: this.loop,
  70435. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  70436. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  70437. refDistance: this.refDistance, distanceModel: this.distanceModel
  70438. };
  70439. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  70440. if (this.useCustomAttenuation) {
  70441. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  70442. }
  70443. clonedSound.setPosition(this._position);
  70444. clonedSound.setPlaybackRate(this._playbackRate);
  70445. setBufferAndRun();
  70446. return clonedSound;
  70447. }
  70448. // Can't clone a streaming sound
  70449. else {
  70450. return null;
  70451. }
  70452. };
  70453. /**
  70454. * Gets the current underlying audio buffer containing the data
  70455. * @returns the audio buffer
  70456. */
  70457. Sound.prototype.getAudioBuffer = function () {
  70458. return this._audioBuffer;
  70459. };
  70460. /**
  70461. * Serializes the Sound in a JSON representation
  70462. * @returns the JSON representation of the sound
  70463. */
  70464. Sound.prototype.serialize = function () {
  70465. var serializationObject = {
  70466. name: this.name,
  70467. url: this.name,
  70468. autoplay: this.autoplay,
  70469. loop: this.loop,
  70470. volume: this._volume,
  70471. spatialSound: this.spatialSound,
  70472. maxDistance: this.maxDistance,
  70473. rolloffFactor: this.rolloffFactor,
  70474. refDistance: this.refDistance,
  70475. distanceModel: this.distanceModel,
  70476. playbackRate: this._playbackRate,
  70477. panningModel: this._panningModel,
  70478. soundTrackId: this.soundTrackId
  70479. };
  70480. if (this.spatialSound) {
  70481. if (this._connectedMesh) {
  70482. serializationObject.connectedMeshId = this._connectedMesh.id;
  70483. }
  70484. serializationObject.position = this._position.asArray();
  70485. serializationObject.refDistance = this.refDistance;
  70486. serializationObject.distanceModel = this.distanceModel;
  70487. serializationObject.isDirectional = this._isDirectional;
  70488. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  70489. serializationObject.coneInnerAngle = this._coneInnerAngle;
  70490. serializationObject.coneOuterAngle = this._coneOuterAngle;
  70491. serializationObject.coneOuterGain = this._coneOuterGain;
  70492. }
  70493. return serializationObject;
  70494. };
  70495. /**
  70496. * Parse a JSON representation of a sound to innstantiate in a given scene
  70497. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  70498. * @param scene Define the scene the new parsed sound should be created in
  70499. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  70500. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  70501. * @returns the newly parsed sound
  70502. */
  70503. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  70504. var soundName = parsedSound.name;
  70505. var soundUrl;
  70506. if (parsedSound.url) {
  70507. soundUrl = rootUrl + parsedSound.url;
  70508. }
  70509. else {
  70510. soundUrl = rootUrl + soundName;
  70511. }
  70512. var options = {
  70513. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  70514. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  70515. rolloffFactor: parsedSound.rolloffFactor,
  70516. refDistance: parsedSound.refDistance,
  70517. distanceModel: parsedSound.distanceModel,
  70518. playbackRate: parsedSound.playbackRate
  70519. };
  70520. var newSound;
  70521. if (!sourceSound) {
  70522. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  70523. scene._addPendingData(newSound);
  70524. }
  70525. else {
  70526. var setBufferAndRun = function () {
  70527. if (sourceSound._isReadyToPlay) {
  70528. newSound._audioBuffer = sourceSound.getAudioBuffer();
  70529. newSound._isReadyToPlay = true;
  70530. if (newSound.autoplay) {
  70531. newSound.play();
  70532. }
  70533. }
  70534. else {
  70535. window.setTimeout(setBufferAndRun, 300);
  70536. }
  70537. };
  70538. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  70539. setBufferAndRun();
  70540. }
  70541. if (parsedSound.position) {
  70542. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  70543. newSound.setPosition(soundPosition);
  70544. }
  70545. if (parsedSound.isDirectional) {
  70546. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  70547. if (parsedSound.localDirectionToMesh) {
  70548. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  70549. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  70550. }
  70551. }
  70552. if (parsedSound.connectedMeshId) {
  70553. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  70554. if (connectedMesh) {
  70555. newSound.attachToMesh(connectedMesh);
  70556. }
  70557. }
  70558. return newSound;
  70559. };
  70560. return Sound;
  70561. }());
  70562. BABYLON.Sound = Sound;
  70563. })(BABYLON || (BABYLON = {}));
  70564. //# sourceMappingURL=babylon.sound.js.map
  70565. var BABYLON;
  70566. (function (BABYLON) {
  70567. /**
  70568. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  70569. * It will be also used in a future release to apply effects on a specific track.
  70570. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  70571. */
  70572. var SoundTrack = /** @class */ (function () {
  70573. /**
  70574. * Creates a new sound track.
  70575. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  70576. * @param scene Define the scene the sound track belongs to
  70577. * @param options
  70578. */
  70579. function SoundTrack(scene, options) {
  70580. if (options === void 0) { options = {}; }
  70581. /**
  70582. * The unique identifier of the sound track in the scene.
  70583. */
  70584. this.id = -1;
  70585. this._isMainTrack = false;
  70586. this._isInitialized = false;
  70587. this._scene = scene;
  70588. this.soundCollection = new Array();
  70589. this._options = options;
  70590. if (!this._isMainTrack && this._scene.soundTracks) {
  70591. this._scene.soundTracks.push(this);
  70592. this.id = this._scene.soundTracks.length - 1;
  70593. }
  70594. }
  70595. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  70596. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  70597. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  70598. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  70599. if (this._options) {
  70600. if (this._options.volume) {
  70601. this._outputAudioNode.gain.value = this._options.volume;
  70602. }
  70603. if (this._options.mainTrack) {
  70604. this._isMainTrack = this._options.mainTrack;
  70605. }
  70606. }
  70607. this._isInitialized = true;
  70608. }
  70609. };
  70610. /**
  70611. * Release the sound track and its associated resources
  70612. */
  70613. SoundTrack.prototype.dispose = function () {
  70614. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  70615. if (this._connectedAnalyser) {
  70616. this._connectedAnalyser.stopDebugCanvas();
  70617. }
  70618. while (this.soundCollection.length) {
  70619. this.soundCollection[0].dispose();
  70620. }
  70621. if (this._outputAudioNode) {
  70622. this._outputAudioNode.disconnect();
  70623. }
  70624. this._outputAudioNode = null;
  70625. }
  70626. };
  70627. /**
  70628. * Adds a sound to this sound track
  70629. * @param sound define the cound to add
  70630. * @ignoreNaming
  70631. */
  70632. SoundTrack.prototype.AddSound = function (sound) {
  70633. if (!this._isInitialized) {
  70634. this._initializeSoundTrackAudioGraph();
  70635. }
  70636. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  70637. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  70638. }
  70639. if (sound.soundTrackId) {
  70640. if (sound.soundTrackId === -1) {
  70641. this._scene.mainSoundTrack.RemoveSound(sound);
  70642. }
  70643. else if (this._scene.soundTracks) {
  70644. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  70645. }
  70646. }
  70647. this.soundCollection.push(sound);
  70648. sound.soundTrackId = this.id;
  70649. };
  70650. /**
  70651. * Removes a sound to this sound track
  70652. * @param sound define the cound to remove
  70653. * @ignoreNaming
  70654. */
  70655. SoundTrack.prototype.RemoveSound = function (sound) {
  70656. var index = this.soundCollection.indexOf(sound);
  70657. if (index !== -1) {
  70658. this.soundCollection.splice(index, 1);
  70659. }
  70660. };
  70661. /**
  70662. * Set a global volume for the full sound track.
  70663. * @param newVolume Define the new volume of the sound track
  70664. */
  70665. SoundTrack.prototype.setVolume = function (newVolume) {
  70666. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  70667. this._outputAudioNode.gain.value = newVolume;
  70668. }
  70669. };
  70670. /**
  70671. * Switch the panning model to HRTF:
  70672. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  70673. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70674. */
  70675. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  70676. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70677. for (var i = 0; i < this.soundCollection.length; i++) {
  70678. this.soundCollection[i].switchPanningModelToHRTF();
  70679. }
  70680. }
  70681. };
  70682. /**
  70683. * Switch the panning model to Equal Power:
  70684. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  70685. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70686. */
  70687. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  70688. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70689. for (var i = 0; i < this.soundCollection.length; i++) {
  70690. this.soundCollection[i].switchPanningModelToEqualPower();
  70691. }
  70692. }
  70693. };
  70694. /**
  70695. * Connect the sound track to an audio analyser allowing some amazing
  70696. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  70697. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  70698. * @param analyser The analyser to connect to the engine
  70699. */
  70700. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  70701. if (this._connectedAnalyser) {
  70702. this._connectedAnalyser.stopDebugCanvas();
  70703. }
  70704. this._connectedAnalyser = analyser;
  70705. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  70706. this._outputAudioNode.disconnect();
  70707. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  70708. }
  70709. };
  70710. return SoundTrack;
  70711. }());
  70712. BABYLON.SoundTrack = SoundTrack;
  70713. })(BABYLON || (BABYLON = {}));
  70714. //# sourceMappingURL=babylon.soundtrack.js.map
  70715. var BABYLON;
  70716. (function (BABYLON) {
  70717. /**
  70718. * Class used to work with sound analyzer using fast fourier transform (FFT)
  70719. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  70720. */
  70721. var Analyser = /** @class */ (function () {
  70722. /**
  70723. * Creates a new analyser
  70724. * @param scene defines hosting scene
  70725. */
  70726. function Analyser(scene) {
  70727. /**
  70728. * Gets or sets the smoothing
  70729. * @ignorenaming
  70730. */
  70731. this.SMOOTHING = 0.75;
  70732. /**
  70733. * Gets or sets the FFT table size
  70734. * @ignorenaming
  70735. */
  70736. this.FFT_SIZE = 512;
  70737. /**
  70738. * Gets or sets the bar graph amplitude
  70739. * @ignorenaming
  70740. */
  70741. this.BARGRAPHAMPLITUDE = 256;
  70742. /**
  70743. * Gets or sets the position of the debug canvas
  70744. * @ignorenaming
  70745. */
  70746. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  70747. /**
  70748. * Gets or sets the debug canvas size
  70749. * @ignorenaming
  70750. */
  70751. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  70752. this._scene = scene;
  70753. this._audioEngine = BABYLON.Engine.audioEngine;
  70754. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  70755. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  70756. this._webAudioAnalyser.minDecibels = -140;
  70757. this._webAudioAnalyser.maxDecibels = 0;
  70758. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  70759. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  70760. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  70761. }
  70762. }
  70763. /**
  70764. * Get the number of data values you will have to play with for the visualization
  70765. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  70766. * @returns a number
  70767. */
  70768. Analyser.prototype.getFrequencyBinCount = function () {
  70769. if (this._audioEngine.canUseWebAudio) {
  70770. return this._webAudioAnalyser.frequencyBinCount;
  70771. }
  70772. else {
  70773. return 0;
  70774. }
  70775. };
  70776. /**
  70777. * Gets the current frequency data as a byte array
  70778. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  70779. * @returns a Uint8Array
  70780. */
  70781. Analyser.prototype.getByteFrequencyData = function () {
  70782. if (this._audioEngine.canUseWebAudio) {
  70783. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  70784. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  70785. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  70786. }
  70787. return this._byteFreqs;
  70788. };
  70789. /**
  70790. * Gets the current waveform as a byte array
  70791. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  70792. * @returns a Uint8Array
  70793. */
  70794. Analyser.prototype.getByteTimeDomainData = function () {
  70795. if (this._audioEngine.canUseWebAudio) {
  70796. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  70797. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  70798. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  70799. }
  70800. return this._byteTime;
  70801. };
  70802. /**
  70803. * Gets the current frequency data as a float array
  70804. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  70805. * @returns a Float32Array
  70806. */
  70807. Analyser.prototype.getFloatFrequencyData = function () {
  70808. if (this._audioEngine.canUseWebAudio) {
  70809. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  70810. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  70811. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  70812. }
  70813. return this._floatFreqs;
  70814. };
  70815. /**
  70816. * Renders the debug canvas
  70817. */
  70818. Analyser.prototype.drawDebugCanvas = function () {
  70819. var _this = this;
  70820. if (this._audioEngine.canUseWebAudio) {
  70821. if (!this._debugCanvas) {
  70822. this._debugCanvas = document.createElement("canvas");
  70823. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  70824. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  70825. this._debugCanvas.style.position = "absolute";
  70826. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  70827. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  70828. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  70829. document.body.appendChild(this._debugCanvas);
  70830. this._registerFunc = function () {
  70831. _this.drawDebugCanvas();
  70832. };
  70833. this._scene.registerBeforeRender(this._registerFunc);
  70834. }
  70835. if (this._registerFunc && this._debugCanvasContext) {
  70836. var workingArray = this.getByteFrequencyData();
  70837. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  70838. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  70839. // Draw the frequency domain chart.
  70840. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  70841. var value = workingArray[i];
  70842. var percent = value / this.BARGRAPHAMPLITUDE;
  70843. var height = this.DEBUGCANVASSIZE.height * percent;
  70844. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  70845. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  70846. var hue = i / this.getFrequencyBinCount() * 360;
  70847. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  70848. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  70849. }
  70850. }
  70851. }
  70852. };
  70853. /**
  70854. * Stops rendering the debug canvas and removes it
  70855. */
  70856. Analyser.prototype.stopDebugCanvas = function () {
  70857. if (this._debugCanvas) {
  70858. if (this._registerFunc) {
  70859. this._scene.unregisterBeforeRender(this._registerFunc);
  70860. this._registerFunc = null;
  70861. }
  70862. document.body.removeChild(this._debugCanvas);
  70863. this._debugCanvas = null;
  70864. this._debugCanvasContext = null;
  70865. }
  70866. };
  70867. /**
  70868. * Connects two audio nodes
  70869. * @param inputAudioNode defines first node to connect
  70870. * @param outputAudioNode defines second node to connect
  70871. */
  70872. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  70873. if (this._audioEngine.canUseWebAudio) {
  70874. inputAudioNode.connect(this._webAudioAnalyser);
  70875. this._webAudioAnalyser.connect(outputAudioNode);
  70876. }
  70877. };
  70878. /**
  70879. * Releases all associated resources
  70880. */
  70881. Analyser.prototype.dispose = function () {
  70882. if (this._audioEngine.canUseWebAudio) {
  70883. this._webAudioAnalyser.disconnect();
  70884. }
  70885. };
  70886. return Analyser;
  70887. }());
  70888. BABYLON.Analyser = Analyser;
  70889. })(BABYLON || (BABYLON = {}));
  70890. //# sourceMappingURL=babylon.analyser.js.map
  70891. var BABYLON;
  70892. (function (BABYLON) {
  70893. /**
  70894. * Wraps one or more Sound objects and selects one with random weight for playback.
  70895. */
  70896. var WeightedSound = /** @class */ (function () {
  70897. /**
  70898. * Creates a new WeightedSound from the list of sounds given.
  70899. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  70900. * @param sounds Array of Sounds that will be selected from.
  70901. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  70902. */
  70903. function WeightedSound(loop, sounds, weights) {
  70904. var _this = this;
  70905. /** When true a Sound will be selected and played when the current playing Sound completes. */
  70906. this.loop = false;
  70907. this._coneInnerAngle = 360;
  70908. this._coneOuterAngle = 360;
  70909. this._volume = 1;
  70910. /** A Sound is currently playing. */
  70911. this.isPlaying = false;
  70912. /** A Sound is currently paused. */
  70913. this.isPaused = false;
  70914. this._sounds = [];
  70915. this._weights = [];
  70916. if (sounds.length !== weights.length) {
  70917. throw new Error('Sounds length does not equal weights length');
  70918. }
  70919. this.loop = loop;
  70920. this._weights = weights;
  70921. // Normalize the weights
  70922. var weightSum = 0;
  70923. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  70924. var weight = weights_1[_i];
  70925. weightSum += weight;
  70926. }
  70927. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  70928. for (var i = 0; i < this._weights.length; i++) {
  70929. this._weights[i] *= invWeightSum;
  70930. }
  70931. this._sounds = sounds;
  70932. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  70933. var sound = _b[_a];
  70934. sound.onEndedObservable.add(function () { _this._onended(); });
  70935. }
  70936. }
  70937. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  70938. /**
  70939. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  70940. */
  70941. get: function () {
  70942. return this._coneInnerAngle;
  70943. },
  70944. /**
  70945. * The size of cone in degress for a directional sound in which there will be no attenuation.
  70946. */
  70947. set: function (value) {
  70948. if (value !== this._coneInnerAngle) {
  70949. if (this._coneOuterAngle < value) {
  70950. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70951. return;
  70952. }
  70953. this._coneInnerAngle = value;
  70954. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70955. var sound = _a[_i];
  70956. sound.directionalConeInnerAngle = value;
  70957. }
  70958. }
  70959. },
  70960. enumerable: true,
  70961. configurable: true
  70962. });
  70963. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  70964. /**
  70965. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  70966. * Listener angles between innerAngle and outerAngle will falloff linearly.
  70967. */
  70968. get: function () {
  70969. return this._coneOuterAngle;
  70970. },
  70971. /**
  70972. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  70973. * Listener angles between innerAngle and outerAngle will falloff linearly.
  70974. */
  70975. set: function (value) {
  70976. if (value !== this._coneOuterAngle) {
  70977. if (value < this._coneInnerAngle) {
  70978. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70979. return;
  70980. }
  70981. this._coneOuterAngle = value;
  70982. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70983. var sound = _a[_i];
  70984. sound.directionalConeOuterAngle = value;
  70985. }
  70986. }
  70987. },
  70988. enumerable: true,
  70989. configurable: true
  70990. });
  70991. Object.defineProperty(WeightedSound.prototype, "volume", {
  70992. /**
  70993. * Playback volume.
  70994. */
  70995. get: function () {
  70996. return this._volume;
  70997. },
  70998. /**
  70999. * Playback volume.
  71000. */
  71001. set: function (value) {
  71002. if (value !== this._volume) {
  71003. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  71004. var sound = _a[_i];
  71005. sound.setVolume(value);
  71006. }
  71007. }
  71008. },
  71009. enumerable: true,
  71010. configurable: true
  71011. });
  71012. WeightedSound.prototype._onended = function () {
  71013. if (this._currentIndex !== undefined) {
  71014. this._sounds[this._currentIndex].autoplay = false;
  71015. }
  71016. if (this.loop && this.isPlaying) {
  71017. this.play();
  71018. }
  71019. else {
  71020. this.isPlaying = false;
  71021. }
  71022. };
  71023. /**
  71024. * Suspend playback
  71025. */
  71026. WeightedSound.prototype.pause = function () {
  71027. this.isPaused = true;
  71028. if (this._currentIndex !== undefined) {
  71029. this._sounds[this._currentIndex].pause();
  71030. }
  71031. };
  71032. /**
  71033. * Stop playback
  71034. */
  71035. WeightedSound.prototype.stop = function () {
  71036. this.isPlaying = false;
  71037. if (this._currentIndex !== undefined) {
  71038. this._sounds[this._currentIndex].stop();
  71039. }
  71040. };
  71041. /**
  71042. * Start playback.
  71043. * @param startOffset Position the clip head at a specific time in seconds.
  71044. */
  71045. WeightedSound.prototype.play = function (startOffset) {
  71046. if (!this.isPaused) {
  71047. this.stop();
  71048. var randomValue = Math.random();
  71049. var total = 0;
  71050. for (var i = 0; i < this._weights.length; i++) {
  71051. total += this._weights[i];
  71052. if (randomValue <= total) {
  71053. this._currentIndex = i;
  71054. break;
  71055. }
  71056. }
  71057. }
  71058. var sound = this._sounds[this._currentIndex];
  71059. if (sound.isReady()) {
  71060. sound.play(0, this.isPaused ? undefined : startOffset);
  71061. }
  71062. else {
  71063. sound.autoplay = true;
  71064. }
  71065. this.isPlaying = true;
  71066. this.isPaused = false;
  71067. };
  71068. return WeightedSound;
  71069. }());
  71070. BABYLON.WeightedSound = WeightedSound;
  71071. })(BABYLON || (BABYLON = {}));
  71072. //# sourceMappingURL=babylon.weightedsound.js.map
  71073. var BABYLON;
  71074. (function (BABYLON) {
  71075. // Adds the parser to the scene parsers.
  71076. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  71077. // TODO: add sound
  71078. var loadedSounds = [];
  71079. var loadedSound;
  71080. container.sounds = container.sounds || [];
  71081. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  71082. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  71083. var parsedSound = parsedData.sounds[index];
  71084. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71085. if (!parsedSound.url) {
  71086. parsedSound.url = parsedSound.name;
  71087. }
  71088. if (!loadedSounds[parsedSound.url]) {
  71089. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  71090. loadedSounds[parsedSound.url] = loadedSound;
  71091. container.sounds.push(loadedSound);
  71092. }
  71093. else {
  71094. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  71095. }
  71096. }
  71097. else {
  71098. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  71099. }
  71100. }
  71101. }
  71102. loadedSounds = [];
  71103. });
  71104. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  71105. get: function () {
  71106. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  71107. if (!compo) {
  71108. compo = new AudioSceneComponent(this);
  71109. this._addComponent(compo);
  71110. }
  71111. if (!this._mainSoundTrack) {
  71112. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  71113. }
  71114. return this._mainSoundTrack;
  71115. },
  71116. enumerable: true,
  71117. configurable: true
  71118. });
  71119. BABYLON.Scene.prototype.getSoundByName = function (name) {
  71120. var index;
  71121. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  71122. if (this.mainSoundTrack.soundCollection[index].name === name) {
  71123. return this.mainSoundTrack.soundCollection[index];
  71124. }
  71125. }
  71126. if (this.soundTracks) {
  71127. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  71128. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  71129. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  71130. return this.soundTracks[sdIndex].soundCollection[index];
  71131. }
  71132. }
  71133. }
  71134. }
  71135. return null;
  71136. };
  71137. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  71138. get: function () {
  71139. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  71140. if (!compo) {
  71141. compo = new AudioSceneComponent(this);
  71142. this._addComponent(compo);
  71143. }
  71144. return compo.audioEnabled;
  71145. },
  71146. set: function (value) {
  71147. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  71148. if (!compo) {
  71149. compo = new AudioSceneComponent(this);
  71150. this._addComponent(compo);
  71151. }
  71152. if (value) {
  71153. compo.enableAudio();
  71154. }
  71155. else {
  71156. compo.disableAudio();
  71157. }
  71158. },
  71159. enumerable: true,
  71160. configurable: true
  71161. });
  71162. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  71163. get: function () {
  71164. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  71165. if (!compo) {
  71166. compo = new AudioSceneComponent(this);
  71167. this._addComponent(compo);
  71168. }
  71169. return compo.headphone;
  71170. },
  71171. set: function (value) {
  71172. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  71173. if (!compo) {
  71174. compo = new AudioSceneComponent(this);
  71175. this._addComponent(compo);
  71176. }
  71177. if (value) {
  71178. compo.switchAudioModeForHeadphones();
  71179. }
  71180. else {
  71181. compo.switchAudioModeForNormalSpeakers();
  71182. }
  71183. },
  71184. enumerable: true,
  71185. configurable: true
  71186. });
  71187. /**
  71188. * Defines the sound scene component responsible to manage any sounds
  71189. * in a given scene.
  71190. */
  71191. var AudioSceneComponent = /** @class */ (function () {
  71192. /**
  71193. * Creates a new instance of the component for the given scene
  71194. * @param scene Defines the scene to register the component in
  71195. */
  71196. function AudioSceneComponent(scene) {
  71197. /**
  71198. * The component name helpfull to identify the component in the list of scene components.
  71199. */
  71200. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  71201. this._audioEnabled = true;
  71202. this._headphone = false;
  71203. this.scene = scene;
  71204. scene.soundTracks = new Array();
  71205. scene.sounds = new Array();
  71206. }
  71207. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  71208. /**
  71209. * Gets whether audio is enabled or not.
  71210. * Please use related enable/disable method to switch state.
  71211. */
  71212. get: function () {
  71213. return this._audioEnabled;
  71214. },
  71215. enumerable: true,
  71216. configurable: true
  71217. });
  71218. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  71219. /**
  71220. * Gets whether audio is outputing to headphone or not.
  71221. * Please use the according Switch methods to change output.
  71222. */
  71223. get: function () {
  71224. return this._headphone;
  71225. },
  71226. enumerable: true,
  71227. configurable: true
  71228. });
  71229. /**
  71230. * Registers the component in a given scene
  71231. */
  71232. AudioSceneComponent.prototype.register = function () {
  71233. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  71234. };
  71235. /**
  71236. * Rebuilds the elements related to this component in case of
  71237. * context lost for instance.
  71238. */
  71239. AudioSceneComponent.prototype.rebuild = function () {
  71240. // Nothing to do here. (Not rendering related)
  71241. };
  71242. /**
  71243. * Serializes the component data to the specified json object
  71244. * @param serializationObject The object to serialize to
  71245. */
  71246. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  71247. serializationObject.sounds = [];
  71248. if (this.scene.soundTracks) {
  71249. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  71250. var soundtrack = this.scene.soundTracks[index];
  71251. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  71252. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  71253. }
  71254. }
  71255. }
  71256. };
  71257. /**
  71258. * Adds all the element from the container to the scene
  71259. * @param container the container holding the elements
  71260. */
  71261. AudioSceneComponent.prototype.addFromContainer = function (container) {
  71262. var _this = this;
  71263. if (!container.sounds) {
  71264. return;
  71265. }
  71266. container.sounds.forEach(function (sound) {
  71267. sound.play();
  71268. sound.autoplay = true;
  71269. _this.scene.mainSoundTrack.AddSound(sound);
  71270. });
  71271. };
  71272. /**
  71273. * Removes all the elements in the container from the scene
  71274. * @param container contains the elements to remove
  71275. */
  71276. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  71277. var _this = this;
  71278. if (!container.sounds) {
  71279. return;
  71280. }
  71281. container.sounds.forEach(function (sound) {
  71282. sound.stop();
  71283. sound.autoplay = false;
  71284. _this.scene.mainSoundTrack.RemoveSound(sound);
  71285. });
  71286. };
  71287. /**
  71288. * Disposes the component and the associated ressources.
  71289. */
  71290. AudioSceneComponent.prototype.dispose = function () {
  71291. var scene = this.scene;
  71292. if (scene._mainSoundTrack) {
  71293. scene.mainSoundTrack.dispose();
  71294. }
  71295. if (scene.soundTracks) {
  71296. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  71297. scene.soundTracks[scIndex].dispose();
  71298. }
  71299. }
  71300. };
  71301. /**
  71302. * Disables audio in the associated scene.
  71303. */
  71304. AudioSceneComponent.prototype.disableAudio = function () {
  71305. var scene = this.scene;
  71306. this._audioEnabled = false;
  71307. var i;
  71308. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  71309. scene.mainSoundTrack.soundCollection[i].pause();
  71310. }
  71311. if (scene.soundTracks) {
  71312. for (i = 0; i < scene.soundTracks.length; i++) {
  71313. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  71314. scene.soundTracks[i].soundCollection[j].pause();
  71315. }
  71316. }
  71317. }
  71318. };
  71319. /**
  71320. * Enables audio in the associated scene.
  71321. */
  71322. AudioSceneComponent.prototype.enableAudio = function () {
  71323. var scene = this.scene;
  71324. this._audioEnabled = true;
  71325. var i;
  71326. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  71327. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  71328. scene.mainSoundTrack.soundCollection[i].play();
  71329. }
  71330. }
  71331. if (scene.soundTracks) {
  71332. for (i = 0; i < scene.soundTracks.length; i++) {
  71333. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  71334. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  71335. scene.soundTracks[i].soundCollection[j].play();
  71336. }
  71337. }
  71338. }
  71339. }
  71340. };
  71341. /**
  71342. * Switch audio to headphone output.
  71343. */
  71344. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  71345. var scene = this.scene;
  71346. this._headphone = true;
  71347. scene.mainSoundTrack.switchPanningModelToHRTF();
  71348. if (scene.soundTracks) {
  71349. for (var i = 0; i < scene.soundTracks.length; i++) {
  71350. scene.soundTracks[i].switchPanningModelToHRTF();
  71351. }
  71352. }
  71353. };
  71354. /**
  71355. * Switch audio to normal speakers.
  71356. */
  71357. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  71358. var scene = this.scene;
  71359. this._headphone = false;
  71360. scene.mainSoundTrack.switchPanningModelToEqualPower();
  71361. if (scene.soundTracks) {
  71362. for (var i = 0; i < scene.soundTracks.length; i++) {
  71363. scene.soundTracks[i].switchPanningModelToEqualPower();
  71364. }
  71365. }
  71366. };
  71367. AudioSceneComponent.prototype._afterRender = function () {
  71368. var scene = this.scene;
  71369. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  71370. return;
  71371. }
  71372. var listeningCamera;
  71373. var audioEngine = BABYLON.Engine.audioEngine;
  71374. if (scene.activeCameras.length > 0) {
  71375. listeningCamera = scene.activeCameras[0];
  71376. }
  71377. else {
  71378. listeningCamera = scene.activeCamera;
  71379. }
  71380. if (listeningCamera && audioEngine.audioContext) {
  71381. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  71382. // for VR cameras
  71383. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  71384. listeningCamera = listeningCamera.rigCameras[0];
  71385. }
  71386. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  71387. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  71388. cameraDirection.normalize();
  71389. // To avoid some errors on GearVR
  71390. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  71391. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  71392. }
  71393. var i;
  71394. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  71395. var sound = scene.mainSoundTrack.soundCollection[i];
  71396. if (sound.useCustomAttenuation) {
  71397. sound.updateDistanceFromListener();
  71398. }
  71399. }
  71400. if (scene.soundTracks) {
  71401. for (i = 0; i < scene.soundTracks.length; i++) {
  71402. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  71403. sound = scene.soundTracks[i].soundCollection[j];
  71404. if (sound.useCustomAttenuation) {
  71405. sound.updateDistanceFromListener();
  71406. }
  71407. }
  71408. }
  71409. }
  71410. }
  71411. };
  71412. return AudioSceneComponent;
  71413. }());
  71414. BABYLON.AudioSceneComponent = AudioSceneComponent;
  71415. })(BABYLON || (BABYLON = {}));
  71416. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  71417. var BABYLON;
  71418. (function (BABYLON) {
  71419. /**
  71420. * This defines an action helpful to play a defined sound on a triggered action.
  71421. */
  71422. var PlaySoundAction = /** @class */ (function (_super) {
  71423. __extends(PlaySoundAction, _super);
  71424. /**
  71425. * Instantiate the action
  71426. * @param triggerOptions defines the trigger options
  71427. * @param sound defines the sound to play
  71428. * @param condition defines the trigger related conditions
  71429. */
  71430. function PlaySoundAction(triggerOptions, sound, condition) {
  71431. var _this = _super.call(this, triggerOptions, condition) || this;
  71432. _this._sound = sound;
  71433. return _this;
  71434. }
  71435. /** @hidden */
  71436. PlaySoundAction.prototype._prepare = function () {
  71437. };
  71438. /**
  71439. * Execute the action and play the sound.
  71440. */
  71441. PlaySoundAction.prototype.execute = function () {
  71442. if (this._sound !== undefined) {
  71443. this._sound.play();
  71444. }
  71445. };
  71446. /**
  71447. * Serializes the actions and its related information.
  71448. * @param parent defines the object to serialize in
  71449. * @returns the serialized object
  71450. */
  71451. PlaySoundAction.prototype.serialize = function (parent) {
  71452. return _super.prototype._serialize.call(this, {
  71453. name: "PlaySoundAction",
  71454. properties: [{ name: "sound", value: this._sound.name }]
  71455. }, parent);
  71456. };
  71457. return PlaySoundAction;
  71458. }(BABYLON.Action));
  71459. BABYLON.PlaySoundAction = PlaySoundAction;
  71460. /**
  71461. * This defines an action helpful to stop a defined sound on a triggered action.
  71462. */
  71463. var StopSoundAction = /** @class */ (function (_super) {
  71464. __extends(StopSoundAction, _super);
  71465. /**
  71466. * Instantiate the action
  71467. * @param triggerOptions defines the trigger options
  71468. * @param sound defines the sound to stop
  71469. * @param condition defines the trigger related conditions
  71470. */
  71471. function StopSoundAction(triggerOptions, sound, condition) {
  71472. var _this = _super.call(this, triggerOptions, condition) || this;
  71473. _this._sound = sound;
  71474. return _this;
  71475. }
  71476. /** @hidden */
  71477. StopSoundAction.prototype._prepare = function () {
  71478. };
  71479. /**
  71480. * Execute the action and stop the sound.
  71481. */
  71482. StopSoundAction.prototype.execute = function () {
  71483. if (this._sound !== undefined) {
  71484. this._sound.stop();
  71485. }
  71486. };
  71487. /**
  71488. * Serializes the actions and its related information.
  71489. * @param parent defines the object to serialize in
  71490. * @returns the serialized object
  71491. */
  71492. StopSoundAction.prototype.serialize = function (parent) {
  71493. return _super.prototype._serialize.call(this, {
  71494. name: "StopSoundAction",
  71495. properties: [{ name: "sound", value: this._sound.name }]
  71496. }, parent);
  71497. };
  71498. return StopSoundAction;
  71499. }(BABYLON.Action));
  71500. BABYLON.StopSoundAction = StopSoundAction;
  71501. })(BABYLON || (BABYLON = {}));
  71502. //# sourceMappingURL=babylon.directAudioActions.js.map
  71503. var BABYLON;
  71504. (function (BABYLON) {
  71505. /**
  71506. * Class for creating a cube texture
  71507. */
  71508. var CubeTexture = /** @class */ (function (_super) {
  71509. __extends(CubeTexture, _super);
  71510. /**
  71511. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  71512. * as prefiltered data.
  71513. * @param rootUrl defines the url of the texture or the root name of the six images
  71514. * @param scene defines the scene the texture is attached to
  71515. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  71516. * @param noMipmap defines if mipmaps should be created or not
  71517. * @param files defines the six files to load for the different faces
  71518. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  71519. * @param onError defines a callback triggered in case of error during load
  71520. * @param format defines the internal format to use for the texture once loaded
  71521. * @param prefiltered defines whether or not the texture is created from prefiltered data
  71522. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  71523. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  71524. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  71525. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  71526. * @return the cube texture
  71527. */
  71528. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  71529. if (extensions === void 0) { extensions = null; }
  71530. if (noMipmap === void 0) { noMipmap = false; }
  71531. if (files === void 0) { files = null; }
  71532. if (onLoad === void 0) { onLoad = null; }
  71533. if (onError === void 0) { onError = null; }
  71534. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  71535. if (prefiltered === void 0) { prefiltered = false; }
  71536. if (forcedExtension === void 0) { forcedExtension = null; }
  71537. if (createPolynomials === void 0) { createPolynomials = false; }
  71538. if (lodScale === void 0) { lodScale = 0.8; }
  71539. if (lodOffset === void 0) { lodOffset = 0; }
  71540. var _this = _super.call(this, scene) || this;
  71541. /**
  71542. * Gets or sets the center of the bounding box associated with the cube texture.
  71543. * It must define where the camera used to render the texture was set
  71544. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  71545. */
  71546. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  71547. _this._rotationY = 0;
  71548. /** @hidden */
  71549. _this._prefiltered = false;
  71550. _this.name = rootUrl;
  71551. _this.url = rootUrl;
  71552. _this._noMipmap = noMipmap;
  71553. _this.hasAlpha = false;
  71554. _this._format = format;
  71555. _this.isCube = true;
  71556. _this._textureMatrix = BABYLON.Matrix.Identity();
  71557. _this._createPolynomials = createPolynomials;
  71558. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  71559. if (!rootUrl && !files) {
  71560. return _this;
  71561. }
  71562. var lastDot = rootUrl.lastIndexOf(".");
  71563. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  71564. var isDDS = (extension === ".dds");
  71565. var isEnv = (extension === ".env");
  71566. if (isEnv) {
  71567. _this.gammaSpace = false;
  71568. _this._prefiltered = false;
  71569. }
  71570. else {
  71571. _this._prefiltered = prefiltered;
  71572. if (prefiltered) {
  71573. _this.gammaSpace = false;
  71574. }
  71575. }
  71576. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  71577. if (!files) {
  71578. if (!isEnv && !isDDS && !extensions) {
  71579. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  71580. }
  71581. files = [];
  71582. if (extensions) {
  71583. for (var index = 0; index < extensions.length; index++) {
  71584. files.push(rootUrl + extensions[index]);
  71585. }
  71586. }
  71587. }
  71588. _this._files = files;
  71589. if (!_this._texture) {
  71590. if (!scene.useDelayedTextureLoading) {
  71591. if (prefiltered) {
  71592. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  71593. }
  71594. else {
  71595. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  71596. }
  71597. }
  71598. else {
  71599. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  71600. }
  71601. }
  71602. else if (onLoad) {
  71603. if (_this._texture.isReady) {
  71604. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  71605. }
  71606. else {
  71607. _this._texture.onLoadedObservable.add(onLoad);
  71608. }
  71609. }
  71610. return _this;
  71611. }
  71612. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  71613. /**
  71614. * Returns the bounding box size
  71615. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  71616. */
  71617. get: function () {
  71618. return this._boundingBoxSize;
  71619. },
  71620. /**
  71621. * Gets or sets the size of the bounding box associated with the cube texture
  71622. * When defined, the cubemap will switch to local mode
  71623. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  71624. * @example https://www.babylonjs-playground.com/#RNASML
  71625. */
  71626. set: function (value) {
  71627. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  71628. return;
  71629. }
  71630. this._boundingBoxSize = value;
  71631. var scene = this.getScene();
  71632. if (scene) {
  71633. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  71634. }
  71635. },
  71636. enumerable: true,
  71637. configurable: true
  71638. });
  71639. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  71640. /**
  71641. * Gets texture matrix rotation angle around Y axis radians.
  71642. */
  71643. get: function () {
  71644. return this._rotationY;
  71645. },
  71646. /**
  71647. * Sets texture matrix rotation angle around Y axis in radians.
  71648. */
  71649. set: function (value) {
  71650. this._rotationY = value;
  71651. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  71652. },
  71653. enumerable: true,
  71654. configurable: true
  71655. });
  71656. /**
  71657. * Creates a cube texture from an array of image urls
  71658. * @param files defines an array of image urls
  71659. * @param scene defines the hosting scene
  71660. * @param noMipmap specifies if mip maps are not used
  71661. * @returns a cube texture
  71662. */
  71663. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  71664. var rootUrlKey = "";
  71665. files.forEach(function (url) { return rootUrlKey += url; });
  71666. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  71667. };
  71668. /**
  71669. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  71670. * @param url defines the url of the prefiltered texture
  71671. * @param scene defines the scene the texture is attached to
  71672. * @param forcedExtension defines the extension of the file if different from the url
  71673. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  71674. * @return the prefiltered texture
  71675. */
  71676. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  71677. if (forcedExtension === void 0) { forcedExtension = null; }
  71678. if (createPolynomials === void 0) { createPolynomials = true; }
  71679. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  71680. };
  71681. /**
  71682. * Delays loading of the cube texture
  71683. */
  71684. CubeTexture.prototype.delayLoad = function () {
  71685. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  71686. return;
  71687. }
  71688. var scene = this.getScene();
  71689. if (!scene) {
  71690. return;
  71691. }
  71692. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  71693. this._texture = this._getFromCache(this.url, this._noMipmap);
  71694. if (!this._texture) {
  71695. if (this._prefiltered) {
  71696. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  71697. }
  71698. else {
  71699. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  71700. }
  71701. }
  71702. };
  71703. /**
  71704. * Returns the reflection texture matrix
  71705. * @returns the reflection texture matrix
  71706. */
  71707. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  71708. return this._textureMatrix;
  71709. };
  71710. /**
  71711. * Sets the reflection texture matrix
  71712. * @param value Reflection texture matrix
  71713. */
  71714. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  71715. this._textureMatrix = value;
  71716. };
  71717. /**
  71718. * Parses text to create a cube texture
  71719. * @param parsedTexture define the serialized text to read from
  71720. * @param scene defines the hosting scene
  71721. * @param rootUrl defines the root url of the cube texture
  71722. * @returns a cube texture
  71723. */
  71724. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  71725. var texture = BABYLON.SerializationHelper.Parse(function () {
  71726. var prefiltered = false;
  71727. if (parsedTexture.prefiltered) {
  71728. prefiltered = parsedTexture.prefiltered;
  71729. }
  71730. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  71731. }, parsedTexture, scene);
  71732. // Local Cubemaps
  71733. if (parsedTexture.boundingBoxPosition) {
  71734. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  71735. }
  71736. if (parsedTexture.boundingBoxSize) {
  71737. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  71738. }
  71739. // Animations
  71740. if (parsedTexture.animations) {
  71741. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  71742. var parsedAnimation = parsedTexture.animations[animationIndex];
  71743. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  71744. }
  71745. }
  71746. return texture;
  71747. };
  71748. /**
  71749. * Makes a clone, or deep copy, of the cube texture
  71750. * @returns a new cube texture
  71751. */
  71752. CubeTexture.prototype.clone = function () {
  71753. var _this = this;
  71754. return BABYLON.SerializationHelper.Clone(function () {
  71755. var scene = _this.getScene();
  71756. if (!scene) {
  71757. return _this;
  71758. }
  71759. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  71760. }, this);
  71761. };
  71762. __decorate([
  71763. BABYLON.serialize("rotationY")
  71764. ], CubeTexture.prototype, "rotationY", null);
  71765. return CubeTexture;
  71766. }(BABYLON.BaseTexture));
  71767. BABYLON.CubeTexture = CubeTexture;
  71768. })(BABYLON || (BABYLON = {}));
  71769. //# sourceMappingURL=babylon.cubeTexture.js.map
  71770. var BABYLON;
  71771. (function (BABYLON) {
  71772. /**
  71773. * Raw cube texture where the raw buffers are passed in
  71774. */
  71775. var RawCubeTexture = /** @class */ (function (_super) {
  71776. __extends(RawCubeTexture, _super);
  71777. /**
  71778. * Creates a cube texture where the raw buffers are passed in.
  71779. * @param scene defines the scene the texture is attached to
  71780. * @param data defines the array of data to use to create each face
  71781. * @param size defines the size of the textures
  71782. * @param format defines the format of the data
  71783. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  71784. * @param generateMipMaps defines if the engine should generate the mip levels
  71785. * @param invertY defines if data must be stored with Y axis inverted
  71786. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  71787. * @param compression defines the compression used (null by default)
  71788. */
  71789. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  71790. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  71791. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71792. if (generateMipMaps === void 0) { generateMipMaps = false; }
  71793. if (invertY === void 0) { invertY = false; }
  71794. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71795. if (compression === void 0) { compression = null; }
  71796. var _this = _super.call(this, "", scene) || this;
  71797. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  71798. return _this;
  71799. }
  71800. /**
  71801. * Updates the raw cube texture.
  71802. * @param data defines the data to store
  71803. * @param format defines the data format
  71804. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  71805. * @param invertY defines if data must be stored with Y axis inverted
  71806. * @param compression defines the compression used (null by default)
  71807. * @param level defines which level of the texture to update
  71808. */
  71809. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  71810. if (compression === void 0) { compression = null; }
  71811. if (level === void 0) { level = 0; }
  71812. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  71813. };
  71814. /**
  71815. * Updates a raw cube texture with RGBD encoded data.
  71816. * @param data defines the array of data [mipmap][face] to use to create each face
  71817. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  71818. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  71819. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  71820. * @returns a promsie that resolves when the operation is complete
  71821. */
  71822. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  71823. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  71824. if (lodScale === void 0) { lodScale = 0.8; }
  71825. if (lodOffset === void 0) { lodOffset = 0; }
  71826. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  71827. };
  71828. /**
  71829. * Clones the raw cube texture.
  71830. * @return a new cube texture
  71831. */
  71832. RawCubeTexture.prototype.clone = function () {
  71833. var _this = this;
  71834. return BABYLON.SerializationHelper.Clone(function () {
  71835. var scene = _this.getScene();
  71836. var internalTexture = _this._texture;
  71837. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  71838. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  71839. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  71840. }
  71841. return texture;
  71842. }, this);
  71843. };
  71844. /** @hidden */
  71845. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  71846. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  71847. internalTexture._bufferViewArrayArray = data;
  71848. internalTexture._lodGenerationScale = lodScale;
  71849. internalTexture._lodGenerationOffset = lodOffset;
  71850. internalTexture._sphericalPolynomial = sphericalPolynomial;
  71851. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  71852. internalTexture.isReady = true;
  71853. });
  71854. };
  71855. return RawCubeTexture;
  71856. }(BABYLON.CubeTexture));
  71857. BABYLON.RawCubeTexture = RawCubeTexture;
  71858. })(BABYLON || (BABYLON = {}));
  71859. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  71860. var BABYLON;
  71861. (function (BABYLON) {
  71862. /**
  71863. * This Helps creating a texture that will be created from a camera in your scene.
  71864. * It is basically a dynamic texture that could be used to create special effects for instance.
  71865. * Actually, It is the base of lot of effects in the framework like post process, shadows, effect layers and rendering pipelines...
  71866. */
  71867. var RenderTargetTexture = /** @class */ (function (_super) {
  71868. __extends(RenderTargetTexture, _super);
  71869. /**
  71870. * Instantiate a render target texture. This is mainly used to render of screen the scene to for instance apply post processse
  71871. * or used a shadow, depth texture...
  71872. * @param name The friendly name of the texture
  71873. * @param size The size of the RTT (number if square, or {width: number, height:number} or {ratio:} to define a ratio from the main scene)
  71874. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  71875. * @param generateMipMaps True if mip maps need to be generated after render.
  71876. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  71877. * @param type The type of the buffer in the RTT (int, half float, float...)
  71878. * @param isCube True if a cube texture needs to be created
  71879. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  71880. * @param generateDepthBuffer True to generate a depth buffer
  71881. * @param generateStencilBuffer True to generate a stencil buffer
  71882. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  71883. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  71884. */
  71885. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  71886. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  71887. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71888. if (isCube === void 0) { isCube = false; }
  71889. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71890. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  71891. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  71892. if (isMulti === void 0) { isMulti = false; }
  71893. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  71894. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  71895. _this.isCube = isCube;
  71896. /**
  71897. * Define if particles should be rendered in your texture.
  71898. */
  71899. _this.renderParticles = true;
  71900. /**
  71901. * Define if sprites should be rendered in your texture.
  71902. */
  71903. _this.renderSprites = false;
  71904. /**
  71905. * Override the default coordinates mode to projection for RTT as it is the most common case for rendered textures.
  71906. */
  71907. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  71908. /**
  71909. * Define if the camera viewport should be respected while rendering the texture or if the render should be done to the entire texture.
  71910. */
  71911. _this.ignoreCameraViewport = false;
  71912. /**
  71913. * An event triggered when the texture is unbind.
  71914. */
  71915. _this.onBeforeBindObservable = new BABYLON.Observable();
  71916. /**
  71917. * An event triggered when the texture is unbind.
  71918. */
  71919. _this.onAfterUnbindObservable = new BABYLON.Observable();
  71920. /**
  71921. * An event triggered before rendering the texture
  71922. */
  71923. _this.onBeforeRenderObservable = new BABYLON.Observable();
  71924. /**
  71925. * An event triggered after rendering the texture
  71926. */
  71927. _this.onAfterRenderObservable = new BABYLON.Observable();
  71928. /**
  71929. * An event triggered after the texture clear
  71930. */
  71931. _this.onClearObservable = new BABYLON.Observable();
  71932. _this._currentRefreshId = -1;
  71933. _this._refreshRate = 1;
  71934. _this._samples = 1;
  71935. /**
  71936. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  71937. * It must define where the camera used to render the texture is set
  71938. */
  71939. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  71940. scene = _this.getScene();
  71941. if (!scene) {
  71942. return _this;
  71943. }
  71944. _this.renderList = new Array();
  71945. _this._engine = scene.getEngine();
  71946. _this.name = name;
  71947. _this.isRenderTarget = true;
  71948. _this._initialSizeParameter = size;
  71949. _this._processSizeParameter(size);
  71950. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  71951. });
  71952. _this._generateMipMaps = generateMipMaps ? true : false;
  71953. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  71954. // Rendering groups
  71955. _this._renderingManager = new BABYLON.RenderingManager(scene);
  71956. _this._renderingManager._useSceneAutoClearSetup = true;
  71957. if (isMulti) {
  71958. return _this;
  71959. }
  71960. _this._renderTargetOptions = {
  71961. generateMipMaps: generateMipMaps,
  71962. type: type,
  71963. format: format,
  71964. samplingMode: samplingMode,
  71965. generateDepthBuffer: generateDepthBuffer,
  71966. generateStencilBuffer: generateStencilBuffer
  71967. };
  71968. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  71969. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71970. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71971. }
  71972. if (isCube) {
  71973. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  71974. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  71975. _this._textureMatrix = BABYLON.Matrix.Identity();
  71976. }
  71977. else {
  71978. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  71979. }
  71980. return _this;
  71981. }
  71982. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  71983. /**
  71984. * Use this list to define the list of mesh you want to render.
  71985. */
  71986. get: function () {
  71987. return this._renderList;
  71988. },
  71989. set: function (value) {
  71990. this._renderList = value;
  71991. if (this._renderList) {
  71992. this._hookArray(this._renderList);
  71993. }
  71994. },
  71995. enumerable: true,
  71996. configurable: true
  71997. });
  71998. RenderTargetTexture.prototype._hookArray = function (array) {
  71999. var _this = this;
  72000. var oldPush = array.push;
  72001. array.push = function () {
  72002. var items = [];
  72003. for (var _i = 0; _i < arguments.length; _i++) {
  72004. items[_i] = arguments[_i];
  72005. }
  72006. var wasEmpty = array.length === 0;
  72007. var result = oldPush.apply(array, items);
  72008. if (wasEmpty) {
  72009. _this.getScene().meshes.forEach(function (mesh) {
  72010. mesh._markSubMeshesAsLightDirty();
  72011. });
  72012. }
  72013. return result;
  72014. };
  72015. var oldSplice = array.splice;
  72016. array.splice = function (index, deleteCount) {
  72017. var deleted = oldSplice.apply(array, [index, deleteCount]);
  72018. if (array.length === 0) {
  72019. _this.getScene().meshes.forEach(function (mesh) {
  72020. mesh._markSubMeshesAsLightDirty();
  72021. });
  72022. }
  72023. return deleted;
  72024. };
  72025. };
  72026. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  72027. /**
  72028. * Set a after unbind callback in the texture.
  72029. * This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended.
  72030. */
  72031. set: function (callback) {
  72032. if (this._onAfterUnbindObserver) {
  72033. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  72034. }
  72035. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  72036. },
  72037. enumerable: true,
  72038. configurable: true
  72039. });
  72040. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  72041. /**
  72042. * Set a before render callback in the texture.
  72043. * This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended.
  72044. */
  72045. set: function (callback) {
  72046. if (this._onBeforeRenderObserver) {
  72047. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  72048. }
  72049. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  72050. },
  72051. enumerable: true,
  72052. configurable: true
  72053. });
  72054. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  72055. /**
  72056. * Set a after render callback in the texture.
  72057. * This has been kept for backward compatibility and use of onAfterRenderObservable is recommended.
  72058. */
  72059. set: function (callback) {
  72060. if (this._onAfterRenderObserver) {
  72061. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  72062. }
  72063. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  72064. },
  72065. enumerable: true,
  72066. configurable: true
  72067. });
  72068. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  72069. /**
  72070. * Set a clear callback in the texture.
  72071. * This has been kept for backward compatibility and use of onClearObservable is recommended.
  72072. */
  72073. set: function (callback) {
  72074. if (this._onClearObserver) {
  72075. this.onClearObservable.remove(this._onClearObserver);
  72076. }
  72077. this._onClearObserver = this.onClearObservable.add(callback);
  72078. },
  72079. enumerable: true,
  72080. configurable: true
  72081. });
  72082. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  72083. /**
  72084. * Gets render target creation options that were used.
  72085. */
  72086. get: function () {
  72087. return this._renderTargetOptions;
  72088. },
  72089. enumerable: true,
  72090. configurable: true
  72091. });
  72092. RenderTargetTexture.prototype._onRatioRescale = function () {
  72093. if (this._sizeRatio) {
  72094. this.resize(this._initialSizeParameter);
  72095. }
  72096. };
  72097. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  72098. get: function () {
  72099. return this._boundingBoxSize;
  72100. },
  72101. /**
  72102. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  72103. * When defined, the cubemap will switch to local mode
  72104. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  72105. * @example https://www.babylonjs-playground.com/#RNASML
  72106. */
  72107. set: function (value) {
  72108. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  72109. return;
  72110. }
  72111. this._boundingBoxSize = value;
  72112. var scene = this.getScene();
  72113. if (scene) {
  72114. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  72115. }
  72116. },
  72117. enumerable: true,
  72118. configurable: true
  72119. });
  72120. /**
  72121. * Creates a depth stencil texture.
  72122. * This is only available in WebGL 2 or with the depth texture extension available.
  72123. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  72124. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  72125. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  72126. */
  72127. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  72128. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  72129. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  72130. if (generateStencil === void 0) { generateStencil = false; }
  72131. if (!this.getScene()) {
  72132. return;
  72133. }
  72134. var engine = this.getScene().getEngine();
  72135. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  72136. bilinearFiltering: bilinearFiltering,
  72137. comparisonFunction: comparisonFunction,
  72138. generateStencil: generateStencil,
  72139. isCube: this.isCube
  72140. });
  72141. engine.setFrameBufferDepthStencilTexture(this);
  72142. };
  72143. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  72144. if (size.ratio) {
  72145. this._sizeRatio = size.ratio;
  72146. this._size = {
  72147. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  72148. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  72149. };
  72150. }
  72151. else {
  72152. this._size = size;
  72153. }
  72154. };
  72155. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  72156. /**
  72157. * Define the number of samples to use in case of MSAA.
  72158. * It defaults to one meaning no MSAA has been enabled.
  72159. */
  72160. get: function () {
  72161. return this._samples;
  72162. },
  72163. set: function (value) {
  72164. if (this._samples === value) {
  72165. return;
  72166. }
  72167. var scene = this.getScene();
  72168. if (!scene) {
  72169. return;
  72170. }
  72171. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  72172. },
  72173. enumerable: true,
  72174. configurable: true
  72175. });
  72176. /**
  72177. * Resets the refresh counter of the texture and start bak from scratch.
  72178. * Could be usefull to regenerate the texture if it is setup to render only once.
  72179. */
  72180. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  72181. this._currentRefreshId = -1;
  72182. };
  72183. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  72184. /**
  72185. * Define the refresh rate of the texture or the rendering frequency.
  72186. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  72187. */
  72188. get: function () {
  72189. return this._refreshRate;
  72190. },
  72191. set: function (value) {
  72192. this._refreshRate = value;
  72193. this.resetRefreshCounter();
  72194. },
  72195. enumerable: true,
  72196. configurable: true
  72197. });
  72198. /**
  72199. * Adds a post process to the render target rendering passes.
  72200. * @param postProcess define the post process to add
  72201. */
  72202. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  72203. if (!this._postProcessManager) {
  72204. var scene = this.getScene();
  72205. if (!scene) {
  72206. return;
  72207. }
  72208. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  72209. this._postProcesses = new Array();
  72210. }
  72211. this._postProcesses.push(postProcess);
  72212. this._postProcesses[0].autoClear = false;
  72213. };
  72214. /**
  72215. * Clear all the post processes attached to the render target
  72216. * @param dispose define if the cleared post processesshould also be disposed (false by default)
  72217. */
  72218. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  72219. if (dispose === void 0) { dispose = false; }
  72220. if (!this._postProcesses) {
  72221. return;
  72222. }
  72223. if (dispose) {
  72224. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  72225. var postProcess = _a[_i];
  72226. postProcess.dispose();
  72227. }
  72228. }
  72229. this._postProcesses = [];
  72230. };
  72231. /**
  72232. * Remove one of the post process from the list of attached post processes to the texture
  72233. * @param postProcess define the post process to remove from the list
  72234. */
  72235. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  72236. if (!this._postProcesses) {
  72237. return;
  72238. }
  72239. var index = this._postProcesses.indexOf(postProcess);
  72240. if (index === -1) {
  72241. return;
  72242. }
  72243. this._postProcesses.splice(index, 1);
  72244. if (this._postProcesses.length > 0) {
  72245. this._postProcesses[0].autoClear = false;
  72246. }
  72247. };
  72248. /** @hidden */
  72249. RenderTargetTexture.prototype._shouldRender = function () {
  72250. if (this._currentRefreshId === -1) { // At least render once
  72251. this._currentRefreshId = 1;
  72252. return true;
  72253. }
  72254. if (this.refreshRate === this._currentRefreshId) {
  72255. this._currentRefreshId = 1;
  72256. return true;
  72257. }
  72258. this._currentRefreshId++;
  72259. return false;
  72260. };
  72261. /**
  72262. * Gets the actual render size of the texture.
  72263. * @returns the width of the render size
  72264. */
  72265. RenderTargetTexture.prototype.getRenderSize = function () {
  72266. return this.getRenderWidth();
  72267. };
  72268. /**
  72269. * Gets the actual render width of the texture.
  72270. * @returns the width of the render size
  72271. */
  72272. RenderTargetTexture.prototype.getRenderWidth = function () {
  72273. if (this._size.width) {
  72274. return this._size.width;
  72275. }
  72276. return this._size;
  72277. };
  72278. /**
  72279. * Gets the actual render height of the texture.
  72280. * @returns the height of the render size
  72281. */
  72282. RenderTargetTexture.prototype.getRenderHeight = function () {
  72283. if (this._size.width) {
  72284. return this._size.height;
  72285. }
  72286. return this._size;
  72287. };
  72288. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  72289. /**
  72290. * Get if the texture can be rescaled or not.
  72291. */
  72292. get: function () {
  72293. return true;
  72294. },
  72295. enumerable: true,
  72296. configurable: true
  72297. });
  72298. /**
  72299. * Resize the texture using a ratio.
  72300. * @param ratio the ratio to apply to the texture size in order to compute the new target size
  72301. */
  72302. RenderTargetTexture.prototype.scale = function (ratio) {
  72303. var newSize = this.getRenderSize() * ratio;
  72304. this.resize(newSize);
  72305. };
  72306. /**
  72307. * Get the texture reflection matrix used to rotate/transform the reflection.
  72308. * @returns the reflection matrix
  72309. */
  72310. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  72311. if (this.isCube) {
  72312. return this._textureMatrix;
  72313. }
  72314. return _super.prototype.getReflectionTextureMatrix.call(this);
  72315. };
  72316. /**
  72317. * Resize the texture to a new desired size.
  72318. * Be carrefull as it will recreate all the data in the new texture.
  72319. * @param size Define the new size. It can be:
  72320. * - a number for squared texture,
  72321. * - an object containing { width: number, height: number }
  72322. * - or an object containing a ratio { ratio: number }
  72323. */
  72324. RenderTargetTexture.prototype.resize = function (size) {
  72325. this.releaseInternalTexture();
  72326. var scene = this.getScene();
  72327. if (!scene) {
  72328. return;
  72329. }
  72330. this._processSizeParameter(size);
  72331. if (this.isCube) {
  72332. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  72333. }
  72334. else {
  72335. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  72336. }
  72337. };
  72338. /**
  72339. * Renders all the objects from the render list into the texture.
  72340. * @param useCameraPostProcess Define if camera post processes should be used during the rendering
  72341. * @param dumpForDebug Define if the rendering result should be dumped (copied) for debugging purpose
  72342. */
  72343. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  72344. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  72345. if (dumpForDebug === void 0) { dumpForDebug = false; }
  72346. var scene = this.getScene();
  72347. if (!scene) {
  72348. return;
  72349. }
  72350. var engine = scene.getEngine();
  72351. if (this.useCameraPostProcesses !== undefined) {
  72352. useCameraPostProcess = this.useCameraPostProcesses;
  72353. }
  72354. if (this._waitingRenderList) {
  72355. this.renderList = [];
  72356. for (var index = 0; index < this._waitingRenderList.length; index++) {
  72357. var id = this._waitingRenderList[index];
  72358. var mesh_1 = scene.getMeshByID(id);
  72359. if (mesh_1) {
  72360. this.renderList.push(mesh_1);
  72361. }
  72362. }
  72363. delete this._waitingRenderList;
  72364. }
  72365. // Is predicate defined?
  72366. if (this.renderListPredicate) {
  72367. if (this.renderList) {
  72368. this.renderList.splice(0); // Clear previous renderList
  72369. }
  72370. else {
  72371. this.renderList = [];
  72372. }
  72373. var scene = this.getScene();
  72374. if (!scene) {
  72375. return;
  72376. }
  72377. var sceneMeshes = scene.meshes;
  72378. for (var index = 0; index < sceneMeshes.length; index++) {
  72379. var mesh = sceneMeshes[index];
  72380. if (this.renderListPredicate(mesh)) {
  72381. this.renderList.push(mesh);
  72382. }
  72383. }
  72384. }
  72385. this.onBeforeBindObservable.notifyObservers(this);
  72386. // Set custom projection.
  72387. // Needs to be before binding to prevent changing the aspect ratio.
  72388. var camera;
  72389. if (this.activeCamera) {
  72390. camera = this.activeCamera;
  72391. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  72392. if (this.activeCamera !== scene.activeCamera) {
  72393. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  72394. }
  72395. }
  72396. else {
  72397. camera = scene.activeCamera;
  72398. if (camera) {
  72399. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  72400. }
  72401. }
  72402. // Prepare renderingManager
  72403. this._renderingManager.reset();
  72404. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  72405. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  72406. var sceneRenderId = scene.getRenderId();
  72407. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  72408. var mesh = currentRenderList[meshIndex];
  72409. if (mesh) {
  72410. if (!mesh.isReady(this.refreshRate === 0)) {
  72411. this.resetRefreshCounter();
  72412. continue;
  72413. }
  72414. mesh._preActivateForIntermediateRendering(sceneRenderId);
  72415. var isMasked = void 0;
  72416. if (!this.renderList && camera) {
  72417. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  72418. }
  72419. else {
  72420. isMasked = false;
  72421. }
  72422. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  72423. mesh._activate(sceneRenderId);
  72424. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  72425. var subMesh = mesh.subMeshes[subIndex];
  72426. scene._activeIndices.addCount(subMesh.indexCount, false);
  72427. this._renderingManager.dispatch(subMesh, mesh);
  72428. }
  72429. }
  72430. }
  72431. }
  72432. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  72433. var particleSystem = scene.particleSystems[particleIndex];
  72434. var emitter = particleSystem.emitter;
  72435. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  72436. continue;
  72437. }
  72438. if (currentRenderList.indexOf(emitter) >= 0) {
  72439. this._renderingManager.dispatchParticles(particleSystem);
  72440. }
  72441. }
  72442. if (this.isCube) {
  72443. for (var face = 0; face < 6; face++) {
  72444. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  72445. scene.incrementRenderId();
  72446. scene.resetCachedMaterial();
  72447. }
  72448. }
  72449. else {
  72450. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  72451. }
  72452. this.onAfterUnbindObservable.notifyObservers(this);
  72453. if (scene.activeCamera) {
  72454. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  72455. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  72456. }
  72457. engine.setViewport(scene.activeCamera.viewport);
  72458. }
  72459. scene.resetCachedMaterial();
  72460. };
  72461. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  72462. var minimum = 128;
  72463. var x = renderDimension * scale;
  72464. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  72465. // Ensure we don't exceed the render dimension (while staying POT)
  72466. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  72467. };
  72468. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  72469. var _this = this;
  72470. if (!this._texture) {
  72471. return;
  72472. }
  72473. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  72474. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  72475. });
  72476. };
  72477. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  72478. var scene = this.getScene();
  72479. if (!scene) {
  72480. return;
  72481. }
  72482. var engine = scene.getEngine();
  72483. if (!this._texture) {
  72484. return;
  72485. }
  72486. // Bind
  72487. if (this._postProcessManager) {
  72488. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  72489. }
  72490. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  72491. if (this._texture) {
  72492. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  72493. }
  72494. }
  72495. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  72496. // Clear
  72497. if (this.onClearObservable.hasObservers()) {
  72498. this.onClearObservable.notifyObservers(engine);
  72499. }
  72500. else {
  72501. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  72502. }
  72503. if (!this._doNotChangeAspectRatio) {
  72504. scene.updateTransformMatrix(true);
  72505. }
  72506. // Render
  72507. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  72508. if (this._postProcessManager) {
  72509. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  72510. }
  72511. else if (useCameraPostProcess) {
  72512. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  72513. }
  72514. if (!this._doNotChangeAspectRatio) {
  72515. scene.updateTransformMatrix(true);
  72516. }
  72517. // Dump ?
  72518. if (dumpForDebug) {
  72519. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  72520. }
  72521. // Unbind
  72522. if (!this.isCube || faceIndex === 5) {
  72523. if (this.isCube) {
  72524. if (faceIndex === 5) {
  72525. engine.generateMipMapsForCubemap(this._texture);
  72526. }
  72527. }
  72528. this.unbindFrameBuffer(engine, faceIndex);
  72529. }
  72530. else {
  72531. this.onAfterRenderObservable.notifyObservers(faceIndex);
  72532. }
  72533. };
  72534. /**
  72535. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  72536. * This allowed control for front to back rendering or reversly depending of the special needs.
  72537. *
  72538. * @param renderingGroupId The rendering group id corresponding to its index
  72539. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  72540. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  72541. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  72542. */
  72543. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  72544. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  72545. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  72546. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  72547. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  72548. };
  72549. /**
  72550. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  72551. *
  72552. * @param renderingGroupId The rendering group id corresponding to its index
  72553. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  72554. */
  72555. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  72556. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  72557. this._renderingManager._useSceneAutoClearSetup = false;
  72558. };
  72559. /**
  72560. * Clones the texture.
  72561. * @returns the cloned texture
  72562. */
  72563. RenderTargetTexture.prototype.clone = function () {
  72564. var textureSize = this.getSize();
  72565. 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);
  72566. // Base texture
  72567. newTexture.hasAlpha = this.hasAlpha;
  72568. newTexture.level = this.level;
  72569. // RenderTarget Texture
  72570. newTexture.coordinatesMode = this.coordinatesMode;
  72571. if (this.renderList) {
  72572. newTexture.renderList = this.renderList.slice(0);
  72573. }
  72574. return newTexture;
  72575. };
  72576. /**
  72577. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  72578. * @returns The JSON representation of the texture
  72579. */
  72580. RenderTargetTexture.prototype.serialize = function () {
  72581. if (!this.name) {
  72582. return null;
  72583. }
  72584. var serializationObject = _super.prototype.serialize.call(this);
  72585. serializationObject.renderTargetSize = this.getRenderSize();
  72586. serializationObject.renderList = [];
  72587. if (this.renderList) {
  72588. for (var index = 0; index < this.renderList.length; index++) {
  72589. serializationObject.renderList.push(this.renderList[index].id);
  72590. }
  72591. }
  72592. return serializationObject;
  72593. };
  72594. /**
  72595. * This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  72596. */
  72597. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  72598. var objBuffer = this.getInternalTexture();
  72599. var scene = this.getScene();
  72600. if (objBuffer && scene) {
  72601. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  72602. }
  72603. };
  72604. /**
  72605. * Dispose the texture and release its associated resources.
  72606. */
  72607. RenderTargetTexture.prototype.dispose = function () {
  72608. if (this._postProcessManager) {
  72609. this._postProcessManager.dispose();
  72610. this._postProcessManager = null;
  72611. }
  72612. this.clearPostProcesses(true);
  72613. if (this._resizeObserver) {
  72614. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  72615. this._resizeObserver = null;
  72616. }
  72617. this.renderList = null;
  72618. // Remove from custom render targets
  72619. var scene = this.getScene();
  72620. if (!scene) {
  72621. return;
  72622. }
  72623. var index = scene.customRenderTargets.indexOf(this);
  72624. if (index >= 0) {
  72625. scene.customRenderTargets.splice(index, 1);
  72626. }
  72627. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  72628. var camera = _a[_i];
  72629. index = camera.customRenderTargets.indexOf(this);
  72630. if (index >= 0) {
  72631. camera.customRenderTargets.splice(index, 1);
  72632. }
  72633. }
  72634. _super.prototype.dispose.call(this);
  72635. };
  72636. /** @hidden */
  72637. RenderTargetTexture.prototype._rebuild = function () {
  72638. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  72639. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  72640. }
  72641. if (this._postProcessManager) {
  72642. this._postProcessManager._rebuild();
  72643. }
  72644. };
  72645. /**
  72646. * Clear the info related to rendering groups preventing retention point in material dispose.
  72647. */
  72648. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  72649. if (this._renderingManager) {
  72650. this._renderingManager.freeRenderingGroups();
  72651. }
  72652. };
  72653. /**
  72654. * The texture will only be rendered once which can be useful to improve performance if everything in your render is static for instance.
  72655. */
  72656. RenderTargetTexture.REFRESHRATE_RENDER_ONCE = 0;
  72657. /**
  72658. * The texture will only be rendered rendered every frame and is recomended for dynamic contents.
  72659. */
  72660. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  72661. /**
  72662. * The texture will be rendered every 2 frames which could be enough if your dynamic objects are not
  72663. * the central point of your effect and can save a lot of performances.
  72664. */
  72665. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  72666. return RenderTargetTexture;
  72667. }(BABYLON.Texture));
  72668. BABYLON.RenderTargetTexture = RenderTargetTexture;
  72669. })(BABYLON || (BABYLON = {}));
  72670. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  72671. var BABYLON;
  72672. (function (BABYLON) {
  72673. /**
  72674. * A multi render target, like a render target provides the ability to render to a texture.
  72675. * Unlike the render target, it can render to several draw buffers in one draw.
  72676. * This is specially interesting in deferred rendering or for any effects requiring more than
  72677. * just one color from a single pass.
  72678. */
  72679. var MultiRenderTarget = /** @class */ (function (_super) {
  72680. __extends(MultiRenderTarget, _super);
  72681. /**
  72682. * Instantiate a new multi render target texture.
  72683. * A multi render target, like a render target provides the ability to render to a texture.
  72684. * Unlike the render target, it can render to several draw buffers in one draw.
  72685. * This is specially interesting in deferred rendering or for any effects requiring more than
  72686. * just one color from a single pass.
  72687. * @param name Define the name of the texture
  72688. * @param size Define the size of the buffers to render to
  72689. * @param count Define the number of target we are rendering into
  72690. * @param scene Define the scene the texture belongs to
  72691. * @param options Define the options used to create the multi render target
  72692. */
  72693. function MultiRenderTarget(name, size, count, scene, options) {
  72694. var _this = this;
  72695. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  72696. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  72697. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  72698. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  72699. _this._engine = scene.getEngine();
  72700. if (!_this.isSupported) {
  72701. _this.dispose();
  72702. return;
  72703. }
  72704. var types = [];
  72705. var samplingModes = [];
  72706. for (var i = 0; i < count; i++) {
  72707. if (options && options.types && options.types[i] !== undefined) {
  72708. types.push(options.types[i]);
  72709. }
  72710. else {
  72711. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72712. }
  72713. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  72714. samplingModes.push(options.samplingModes[i]);
  72715. }
  72716. else {
  72717. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72718. }
  72719. }
  72720. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  72721. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  72722. _this._size = size;
  72723. _this._multiRenderTargetOptions = {
  72724. samplingModes: samplingModes,
  72725. generateMipMaps: generateMipMaps,
  72726. generateDepthBuffer: generateDepthBuffer,
  72727. generateStencilBuffer: generateStencilBuffer,
  72728. generateDepthTexture: generateDepthTexture,
  72729. types: types,
  72730. textureCount: count
  72731. };
  72732. _this._createInternalTextures();
  72733. _this._createTextures();
  72734. return _this;
  72735. }
  72736. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  72737. /**
  72738. * Get if draw buffers are currently supported by the used hardware and browser.
  72739. */
  72740. get: function () {
  72741. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  72742. },
  72743. enumerable: true,
  72744. configurable: true
  72745. });
  72746. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  72747. /**
  72748. * Get the list of textures generated by the multi render target.
  72749. */
  72750. get: function () {
  72751. return this._textures;
  72752. },
  72753. enumerable: true,
  72754. configurable: true
  72755. });
  72756. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  72757. /**
  72758. * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set
  72759. */
  72760. get: function () {
  72761. return this._textures[this._textures.length - 1];
  72762. },
  72763. enumerable: true,
  72764. configurable: true
  72765. });
  72766. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  72767. /**
  72768. * Set the wrapping mode on U of all the textures we are rendering to.
  72769. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  72770. */
  72771. set: function (wrap) {
  72772. if (this._textures) {
  72773. for (var i = 0; i < this._textures.length; i++) {
  72774. this._textures[i].wrapU = wrap;
  72775. }
  72776. }
  72777. },
  72778. enumerable: true,
  72779. configurable: true
  72780. });
  72781. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  72782. /**
  72783. * Set the wrapping mode on V of all the textures we are rendering to.
  72784. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  72785. */
  72786. set: function (wrap) {
  72787. if (this._textures) {
  72788. for (var i = 0; i < this._textures.length; i++) {
  72789. this._textures[i].wrapV = wrap;
  72790. }
  72791. }
  72792. },
  72793. enumerable: true,
  72794. configurable: true
  72795. });
  72796. /** @hidden */
  72797. MultiRenderTarget.prototype._rebuild = function () {
  72798. this.releaseInternalTextures();
  72799. this._createInternalTextures();
  72800. for (var i = 0; i < this._internalTextures.length; i++) {
  72801. var texture = this._textures[i];
  72802. texture._texture = this._internalTextures[i];
  72803. }
  72804. // Keeps references to frame buffer and stencil/depth buffer
  72805. this._texture = this._internalTextures[0];
  72806. };
  72807. MultiRenderTarget.prototype._createInternalTextures = function () {
  72808. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  72809. };
  72810. MultiRenderTarget.prototype._createTextures = function () {
  72811. this._textures = [];
  72812. for (var i = 0; i < this._internalTextures.length; i++) {
  72813. var texture = new BABYLON.Texture(null, this.getScene());
  72814. texture._texture = this._internalTextures[i];
  72815. this._textures.push(texture);
  72816. }
  72817. // Keeps references to frame buffer and stencil/depth buffer
  72818. this._texture = this._internalTextures[0];
  72819. };
  72820. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  72821. /**
  72822. * Define the number of samples used if MSAA is enabled.
  72823. */
  72824. get: function () {
  72825. return this._samples;
  72826. },
  72827. set: function (value) {
  72828. if (this._samples === value) {
  72829. return;
  72830. }
  72831. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  72832. },
  72833. enumerable: true,
  72834. configurable: true
  72835. });
  72836. /**
  72837. * Resize all the textures in the multi render target.
  72838. * Be carrefull as it will recreate all the data in the new texture.
  72839. * @param size Define the new size
  72840. */
  72841. MultiRenderTarget.prototype.resize = function (size) {
  72842. this.releaseInternalTextures();
  72843. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  72844. this._createInternalTextures();
  72845. };
  72846. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  72847. var _this = this;
  72848. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  72849. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  72850. });
  72851. };
  72852. /**
  72853. * Dispose the render targets and their associated resources
  72854. */
  72855. MultiRenderTarget.prototype.dispose = function () {
  72856. this.releaseInternalTextures();
  72857. _super.prototype.dispose.call(this);
  72858. };
  72859. /**
  72860. * Release all the underlying texture used as draw buffers.
  72861. */
  72862. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  72863. if (!this._internalTextures) {
  72864. return;
  72865. }
  72866. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  72867. if (this._internalTextures[i] !== undefined) {
  72868. this._internalTextures[i].dispose();
  72869. this._internalTextures.splice(i, 1);
  72870. }
  72871. }
  72872. };
  72873. return MultiRenderTarget;
  72874. }(BABYLON.RenderTargetTexture));
  72875. BABYLON.MultiRenderTarget = MultiRenderTarget;
  72876. })(BABYLON || (BABYLON = {}));
  72877. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  72878. var BABYLON;
  72879. (function (BABYLON) {
  72880. /**
  72881. * Mirror texture can be used to simulate the view from a mirror in a scene.
  72882. * It will dynamically be rendered every frame to adapt to the camera point of view.
  72883. * You can then easily use it as a reflectionTexture on a flat surface.
  72884. * In case the surface is not a plane, please consider relying on reflection probes.
  72885. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  72886. */
  72887. var MirrorTexture = /** @class */ (function (_super) {
  72888. __extends(MirrorTexture, _super);
  72889. /**
  72890. * Instantiates a Mirror Texture.
  72891. * Mirror texture can be used to simulate the view from a mirror in a scene.
  72892. * It will dynamically be rendered every frame to adapt to the camera point of view.
  72893. * You can then easily use it as a reflectionTexture on a flat surface.
  72894. * In case the surface is not a plane, please consider relying on reflection probes.
  72895. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  72896. * @param name
  72897. * @param size
  72898. * @param scene
  72899. * @param generateMipMaps
  72900. * @param type
  72901. * @param samplingMode
  72902. * @param generateDepthBuffer
  72903. */
  72904. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  72905. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72906. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72907. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  72908. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  72909. _this.scene = scene;
  72910. /**
  72911. * Define the reflection plane we want to use. The mirrorPlane is usually set to the constructed reflector.
  72912. * It is possible to directly set the mirrorPlane by directly using a BABYLON.Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the mirrorPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the reflector as stated in the doc.
  72913. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  72914. */
  72915. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  72916. _this._transformMatrix = BABYLON.Matrix.Zero();
  72917. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  72918. _this._adaptiveBlurKernel = 0;
  72919. _this._blurKernelX = 0;
  72920. _this._blurKernelY = 0;
  72921. _this._blurRatio = 1.0;
  72922. _this.ignoreCameraViewport = true;
  72923. _this._updateGammaSpace();
  72924. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  72925. _this._updateGammaSpace;
  72926. });
  72927. _this.onBeforeRenderObservable.add(function () {
  72928. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  72929. _this._savedViewMatrix = scene.getViewMatrix();
  72930. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  72931. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  72932. scene.clipPlane = _this.mirrorPlane;
  72933. scene.getEngine().cullBackFaces = false;
  72934. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  72935. });
  72936. _this.onAfterRenderObservable.add(function () {
  72937. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  72938. scene.getEngine().cullBackFaces = true;
  72939. scene._mirroredCameraPosition = null;
  72940. delete scene.clipPlane;
  72941. });
  72942. return _this;
  72943. }
  72944. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  72945. get: function () {
  72946. return this._blurRatio;
  72947. },
  72948. /**
  72949. * Define the blur ratio used to blur the reflection if needed.
  72950. */
  72951. set: function (value) {
  72952. if (this._blurRatio === value) {
  72953. return;
  72954. }
  72955. this._blurRatio = value;
  72956. this._preparePostProcesses();
  72957. },
  72958. enumerable: true,
  72959. configurable: true
  72960. });
  72961. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  72962. /**
  72963. * Define the adaptive blur kernel used to blur the reflection if needed.
  72964. * This will autocompute the closest best match for the `blurKernel`
  72965. */
  72966. set: function (value) {
  72967. this._adaptiveBlurKernel = value;
  72968. this._autoComputeBlurKernel();
  72969. },
  72970. enumerable: true,
  72971. configurable: true
  72972. });
  72973. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  72974. /**
  72975. * Define the blur kernel used to blur the reflection if needed.
  72976. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  72977. */
  72978. set: function (value) {
  72979. this.blurKernelX = value;
  72980. this.blurKernelY = value;
  72981. },
  72982. enumerable: true,
  72983. configurable: true
  72984. });
  72985. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  72986. get: function () {
  72987. return this._blurKernelX;
  72988. },
  72989. /**
  72990. * Define the blur kernel on the X Axis used to blur the reflection if needed.
  72991. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  72992. */
  72993. set: function (value) {
  72994. if (this._blurKernelX === value) {
  72995. return;
  72996. }
  72997. this._blurKernelX = value;
  72998. this._preparePostProcesses();
  72999. },
  73000. enumerable: true,
  73001. configurable: true
  73002. });
  73003. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  73004. get: function () {
  73005. return this._blurKernelY;
  73006. },
  73007. /**
  73008. * Define the blur kernel on the Y Axis used to blur the reflection if needed.
  73009. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  73010. */
  73011. set: function (value) {
  73012. if (this._blurKernelY === value) {
  73013. return;
  73014. }
  73015. this._blurKernelY = value;
  73016. this._preparePostProcesses();
  73017. },
  73018. enumerable: true,
  73019. configurable: true
  73020. });
  73021. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  73022. var engine = this.getScene().getEngine();
  73023. var dw = this.getRenderWidth() / engine.getRenderWidth();
  73024. var dh = this.getRenderHeight() / engine.getRenderHeight();
  73025. this.blurKernelX = this._adaptiveBlurKernel * dw;
  73026. this.blurKernelY = this._adaptiveBlurKernel * dh;
  73027. };
  73028. MirrorTexture.prototype._onRatioRescale = function () {
  73029. if (this._sizeRatio) {
  73030. this.resize(this._initialSizeParameter);
  73031. if (!this._adaptiveBlurKernel) {
  73032. this._preparePostProcesses();
  73033. }
  73034. }
  73035. if (this._adaptiveBlurKernel) {
  73036. this._autoComputeBlurKernel();
  73037. }
  73038. };
  73039. MirrorTexture.prototype._updateGammaSpace = function () {
  73040. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  73041. };
  73042. MirrorTexture.prototype._preparePostProcesses = function () {
  73043. this.clearPostProcesses(true);
  73044. if (this._blurKernelX && this._blurKernelY) {
  73045. var engine = this.getScene().getEngine();
  73046. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73047. 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);
  73048. this._blurX.autoClear = false;
  73049. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  73050. this._blurX.inputTexture = this._texture;
  73051. }
  73052. else {
  73053. this._blurX.alwaysForcePOT = true;
  73054. }
  73055. 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);
  73056. this._blurY.autoClear = false;
  73057. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  73058. this.addPostProcess(this._blurX);
  73059. this.addPostProcess(this._blurY);
  73060. }
  73061. else {
  73062. if (this._blurY) {
  73063. this.removePostProcess(this._blurY);
  73064. this._blurY.dispose();
  73065. this._blurY = null;
  73066. }
  73067. if (this._blurX) {
  73068. this.removePostProcess(this._blurX);
  73069. this._blurX.dispose();
  73070. this._blurX = null;
  73071. }
  73072. }
  73073. };
  73074. /**
  73075. * Clone the mirror texture.
  73076. * @returns the cloned texture
  73077. */
  73078. MirrorTexture.prototype.clone = function () {
  73079. var scene = this.getScene();
  73080. if (!scene) {
  73081. return this;
  73082. }
  73083. var textureSize = this.getSize();
  73084. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  73085. // Base texture
  73086. newTexture.hasAlpha = this.hasAlpha;
  73087. newTexture.level = this.level;
  73088. // Mirror Texture
  73089. newTexture.mirrorPlane = this.mirrorPlane.clone();
  73090. if (this.renderList) {
  73091. newTexture.renderList = this.renderList.slice(0);
  73092. }
  73093. return newTexture;
  73094. };
  73095. /**
  73096. * Serialize the texture to a JSON representation you could use in Parse later on
  73097. * @returns the serialized JSON representation
  73098. */
  73099. MirrorTexture.prototype.serialize = function () {
  73100. if (!this.name) {
  73101. return null;
  73102. }
  73103. var serializationObject = _super.prototype.serialize.call(this);
  73104. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  73105. return serializationObject;
  73106. };
  73107. /**
  73108. * Dispose the texture and release its associated resources.
  73109. */
  73110. MirrorTexture.prototype.dispose = function () {
  73111. _super.prototype.dispose.call(this);
  73112. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  73113. };
  73114. return MirrorTexture;
  73115. }(BABYLON.RenderTargetTexture));
  73116. BABYLON.MirrorTexture = MirrorTexture;
  73117. })(BABYLON || (BABYLON = {}));
  73118. //# sourceMappingURL=babylon.mirrorTexture.js.map
  73119. var BABYLON;
  73120. (function (BABYLON) {
  73121. /**
  73122. * Creates a refraction texture used by refraction channel of the standard material.
  73123. * It is like a mirror but to see through a material.
  73124. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  73125. */
  73126. var RefractionTexture = /** @class */ (function (_super) {
  73127. __extends(RefractionTexture, _super);
  73128. /**
  73129. * Creates a refraction texture used by refraction channel of the standard material.
  73130. * It is like a mirror but to see through a material.
  73131. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  73132. * @param name Define the texture name
  73133. * @param size Define the size of the underlying texture
  73134. * @param scene Define the scene the refraction belongs to
  73135. * @param generateMipMaps Define if we need to generate mips level for the refraction
  73136. */
  73137. function RefractionTexture(name, size, scene, generateMipMaps) {
  73138. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  73139. /**
  73140. * Define the reflection plane we want to use. The refractionPlane is usually set to the constructed refractor.
  73141. * It is possible to directly set the refractionPlane by directly using a BABYLON.Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the refractionPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the refractor as stated in the doc.
  73142. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  73143. */
  73144. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  73145. /**
  73146. * Define how deep under the surface we should see.
  73147. */
  73148. _this.depth = 2.0;
  73149. _this.onBeforeRenderObservable.add(function () {
  73150. scene.clipPlane = _this.refractionPlane;
  73151. });
  73152. _this.onAfterRenderObservable.add(function () {
  73153. delete scene.clipPlane;
  73154. });
  73155. return _this;
  73156. }
  73157. /**
  73158. * Clone the refraction texture.
  73159. * @returns the cloned texture
  73160. */
  73161. RefractionTexture.prototype.clone = function () {
  73162. var scene = this.getScene();
  73163. if (!scene) {
  73164. return this;
  73165. }
  73166. var textureSize = this.getSize();
  73167. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  73168. // Base texture
  73169. newTexture.hasAlpha = this.hasAlpha;
  73170. newTexture.level = this.level;
  73171. // Refraction Texture
  73172. newTexture.refractionPlane = this.refractionPlane.clone();
  73173. if (this.renderList) {
  73174. newTexture.renderList = this.renderList.slice(0);
  73175. }
  73176. newTexture.depth = this.depth;
  73177. return newTexture;
  73178. };
  73179. /**
  73180. * Serialize the texture to a JSON representation you could use in Parse later on
  73181. * @returns the serialized JSON representation
  73182. */
  73183. RefractionTexture.prototype.serialize = function () {
  73184. if (!this.name) {
  73185. return null;
  73186. }
  73187. var serializationObject = _super.prototype.serialize.call(this);
  73188. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  73189. serializationObject.depth = this.depth;
  73190. return serializationObject;
  73191. };
  73192. return RefractionTexture;
  73193. }(BABYLON.RenderTargetTexture));
  73194. BABYLON.RefractionTexture = RefractionTexture;
  73195. })(BABYLON || (BABYLON = {}));
  73196. //# sourceMappingURL=babylon.refractionTexture.js.map
  73197. var BABYLON;
  73198. (function (BABYLON) {
  73199. /**
  73200. * A class extending Texture allowing drawing on a texture
  73201. * @see http://doc.babylonjs.com/how_to/dynamictexture
  73202. */
  73203. var DynamicTexture = /** @class */ (function (_super) {
  73204. __extends(DynamicTexture, _super);
  73205. /**
  73206. * Creates a DynamicTexture
  73207. * @param name defines the name of the texture
  73208. * @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
  73209. * @param scene defines the scene where you want the texture
  73210. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  73211. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  73212. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  73213. */
  73214. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  73215. if (scene === void 0) { scene = null; }
  73216. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73217. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  73218. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  73219. _this.name = name;
  73220. _this._engine = _this.getScene().getEngine();
  73221. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73222. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73223. _this._generateMipMaps = generateMipMaps;
  73224. if (options.getContext) {
  73225. _this._canvas = options;
  73226. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  73227. }
  73228. else {
  73229. _this._canvas = document.createElement("canvas");
  73230. if (options.width || options.width === 0) {
  73231. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  73232. }
  73233. else {
  73234. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  73235. }
  73236. }
  73237. var textureSize = _this.getSize();
  73238. _this._canvas.width = textureSize.width;
  73239. _this._canvas.height = textureSize.height;
  73240. _this._context = _this._canvas.getContext("2d");
  73241. return _this;
  73242. }
  73243. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  73244. /**
  73245. * Gets the current state of canRescale
  73246. */
  73247. get: function () {
  73248. return true;
  73249. },
  73250. enumerable: true,
  73251. configurable: true
  73252. });
  73253. DynamicTexture.prototype._recreate = function (textureSize) {
  73254. this._canvas.width = textureSize.width;
  73255. this._canvas.height = textureSize.height;
  73256. this.releaseInternalTexture();
  73257. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  73258. };
  73259. /**
  73260. * Scales the texture
  73261. * @param ratio the scale factor to apply to both width and height
  73262. */
  73263. DynamicTexture.prototype.scale = function (ratio) {
  73264. var textureSize = this.getSize();
  73265. textureSize.width *= ratio;
  73266. textureSize.height *= ratio;
  73267. this._recreate(textureSize);
  73268. };
  73269. /**
  73270. * Resizes the texture
  73271. * @param width the new width
  73272. * @param height the new height
  73273. */
  73274. DynamicTexture.prototype.scaleTo = function (width, height) {
  73275. var textureSize = this.getSize();
  73276. textureSize.width = width;
  73277. textureSize.height = height;
  73278. this._recreate(textureSize);
  73279. };
  73280. /**
  73281. * Gets the context of the canvas used by the texture
  73282. * @returns the canvas context of the dynamic texture
  73283. */
  73284. DynamicTexture.prototype.getContext = function () {
  73285. return this._context;
  73286. };
  73287. /**
  73288. * Clears the texture
  73289. */
  73290. DynamicTexture.prototype.clear = function () {
  73291. var size = this.getSize();
  73292. this._context.fillRect(0, 0, size.width, size.height);
  73293. };
  73294. /**
  73295. * Updates the texture
  73296. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  73297. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  73298. */
  73299. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  73300. if (premulAlpha === void 0) { premulAlpha = false; }
  73301. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  73302. };
  73303. /**
  73304. * Draws text onto the texture
  73305. * @param text defines the text to be drawn
  73306. * @param x defines the placement of the text from the left
  73307. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  73308. * @param font defines the font to be used with font-style, font-size, font-name
  73309. * @param color defines the color used for the text
  73310. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  73311. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  73312. * @param update defines whether texture is immediately update (default is true)
  73313. */
  73314. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  73315. if (update === void 0) { update = true; }
  73316. var size = this.getSize();
  73317. if (clearColor) {
  73318. this._context.fillStyle = clearColor;
  73319. this._context.fillRect(0, 0, size.width, size.height);
  73320. }
  73321. this._context.font = font;
  73322. if (x === null || x === undefined) {
  73323. var textSize = this._context.measureText(text);
  73324. x = (size.width - textSize.width) / 2;
  73325. }
  73326. if (y === null || y === undefined) {
  73327. var fontSize = parseInt((font.replace(/\D/g, '')));
  73328. y = (size.height / 2) + (fontSize / 3.65);
  73329. }
  73330. this._context.fillStyle = color;
  73331. this._context.fillText(text, x, y);
  73332. if (update) {
  73333. this.update(invertY);
  73334. }
  73335. };
  73336. /**
  73337. * Clones the texture
  73338. * @returns the clone of the texture.
  73339. */
  73340. DynamicTexture.prototype.clone = function () {
  73341. var scene = this.getScene();
  73342. if (!scene) {
  73343. return this;
  73344. }
  73345. var textureSize = this.getSize();
  73346. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  73347. // Base texture
  73348. newTexture.hasAlpha = this.hasAlpha;
  73349. newTexture.level = this.level;
  73350. // Dynamic Texture
  73351. newTexture.wrapU = this.wrapU;
  73352. newTexture.wrapV = this.wrapV;
  73353. return newTexture;
  73354. };
  73355. /**
  73356. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  73357. * @returns a serialized dynamic texture object
  73358. */
  73359. DynamicTexture.prototype.serialize = function () {
  73360. var scene = this.getScene();
  73361. if (scene && !scene.isReady()) {
  73362. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  73363. }
  73364. var serializationObject = _super.prototype.serialize.call(this);
  73365. serializationObject.base64String = this._canvas.toDataURL();
  73366. serializationObject.invertY = this._invertY;
  73367. serializationObject.samplingMode = this.samplingMode;
  73368. return serializationObject;
  73369. };
  73370. /** @hidden */
  73371. DynamicTexture.prototype._rebuild = function () {
  73372. this.update();
  73373. };
  73374. return DynamicTexture;
  73375. }(BABYLON.Texture));
  73376. BABYLON.DynamicTexture = DynamicTexture;
  73377. })(BABYLON || (BABYLON = {}));
  73378. //# sourceMappingURL=babylon.dynamicTexture.js.map
  73379. var BABYLON;
  73380. (function (BABYLON) {
  73381. /**
  73382. * If you want to display a video in your scene, this is the special texture for that.
  73383. * This special texture works similar to other textures, with the exception of a few parameters.
  73384. * @see https://doc.babylonjs.com/how_to/video_texture
  73385. */
  73386. var VideoTexture = /** @class */ (function (_super) {
  73387. __extends(VideoTexture, _super);
  73388. /**
  73389. * Creates a video texture.
  73390. * If you want to display a video in your scene, this is the special texture for that.
  73391. * This special texture works similar to other textures, with the exception of a few parameters.
  73392. * @see https://doc.babylonjs.com/how_to/video_texture
  73393. * @param name optional name, will detect from video source, if not defined
  73394. * @param src can be used to provide an url, array of urls or an already setup HTML video element.
  73395. * @param scene is obviously the current scene.
  73396. * @param generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  73397. * @param invertY is false by default but can be used to invert video on Y axis
  73398. * @param samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  73399. * @param settings allows finer control over video usage
  73400. */
  73401. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  73402. if (generateMipMaps === void 0) { generateMipMaps = false; }
  73403. if (invertY === void 0) { invertY = false; }
  73404. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73405. if (settings === void 0) { settings = {
  73406. autoPlay: true,
  73407. loop: true,
  73408. autoUpdateTexture: true,
  73409. }; }
  73410. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  73411. _this._onUserActionRequestedObservable = null;
  73412. _this._stillImageCaptured = false;
  73413. _this._poster = false;
  73414. _this._createInternalTexture = function () {
  73415. if (_this._texture != null) {
  73416. if (_this._poster) {
  73417. _this._texture.dispose();
  73418. _this._poster = false;
  73419. }
  73420. else {
  73421. return;
  73422. }
  73423. }
  73424. if (!_this._engine.needPOTTextures ||
  73425. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  73426. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73427. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73428. }
  73429. else {
  73430. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73431. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73432. _this._generateMipMaps = false;
  73433. }
  73434. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  73435. if (!_this.video.autoplay) {
  73436. var oldHandler_1 = _this.video.onplaying;
  73437. var error_1 = false;
  73438. _this.video.onplaying = function () {
  73439. _this.video.onplaying = oldHandler_1;
  73440. _this._texture.isReady = true;
  73441. _this._updateInternalTexture();
  73442. if (!error_1) {
  73443. _this.video.pause();
  73444. }
  73445. if (_this.onLoadObservable.hasObservers()) {
  73446. _this.onLoadObservable.notifyObservers(_this);
  73447. }
  73448. };
  73449. var playing = _this.video.play();
  73450. if (playing) {
  73451. playing.then(function () {
  73452. // Everything is good.
  73453. })
  73454. .catch(function () {
  73455. error_1 = true;
  73456. // On Chrome for instance, new policies might prevent playing without user interaction.
  73457. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  73458. _this._onUserActionRequestedObservable.notifyObservers(_this);
  73459. }
  73460. });
  73461. }
  73462. else {
  73463. _this.video.onplaying = oldHandler_1;
  73464. _this._texture.isReady = true;
  73465. _this._updateInternalTexture();
  73466. if (_this.onLoadObservable.hasObservers()) {
  73467. _this.onLoadObservable.notifyObservers(_this);
  73468. }
  73469. }
  73470. }
  73471. else {
  73472. _this._texture.isReady = true;
  73473. _this._updateInternalTexture();
  73474. if (_this.onLoadObservable.hasObservers()) {
  73475. _this.onLoadObservable.notifyObservers(_this);
  73476. }
  73477. }
  73478. };
  73479. _this.reset = function () {
  73480. if (_this._texture == null) {
  73481. return;
  73482. }
  73483. if (!_this._poster) {
  73484. _this._texture.dispose();
  73485. _this._texture = null;
  73486. }
  73487. };
  73488. _this._updateInternalTexture = function (e) {
  73489. if (_this._texture == null || !_this._texture.isReady) {
  73490. return;
  73491. }
  73492. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  73493. return;
  73494. }
  73495. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  73496. };
  73497. _this._engine = _this.getScene().getEngine();
  73498. _this._generateMipMaps = generateMipMaps;
  73499. _this._samplingMode = samplingMode;
  73500. _this.autoUpdateTexture = settings.autoUpdateTexture;
  73501. _this.name = name || _this._getName(src);
  73502. _this.video = _this._getVideo(src);
  73503. if (settings.poster) {
  73504. _this.video.poster = settings.poster;
  73505. }
  73506. if (settings.autoPlay !== undefined) {
  73507. _this.video.autoplay = settings.autoPlay;
  73508. }
  73509. if (settings.loop !== undefined) {
  73510. _this.video.loop = settings.loop;
  73511. }
  73512. _this.video.setAttribute("playsinline", "");
  73513. _this.video.addEventListener("canplay", _this._createInternalTexture);
  73514. _this.video.addEventListener("paused", _this._updateInternalTexture);
  73515. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  73516. _this.video.addEventListener("emptied", _this.reset);
  73517. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  73518. _this._createInternalTexture();
  73519. }
  73520. if (settings.poster) {
  73521. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  73522. _this._poster = true;
  73523. }
  73524. return _this;
  73525. }
  73526. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  73527. /**
  73528. * Event triggerd when a dom action is required by the user to play the video.
  73529. * This happens due to recent changes in browser policies preventing video to auto start.
  73530. */
  73531. get: function () {
  73532. if (!this._onUserActionRequestedObservable) {
  73533. this._onUserActionRequestedObservable = new BABYLON.Observable();
  73534. }
  73535. return this._onUserActionRequestedObservable;
  73536. },
  73537. enumerable: true,
  73538. configurable: true
  73539. });
  73540. VideoTexture.prototype._getName = function (src) {
  73541. if (src instanceof HTMLVideoElement) {
  73542. return src.currentSrc;
  73543. }
  73544. if (typeof src === "object") {
  73545. return src.toString();
  73546. }
  73547. return src;
  73548. };
  73549. VideoTexture.prototype._getVideo = function (src) {
  73550. if (src instanceof HTMLVideoElement) {
  73551. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  73552. return src;
  73553. }
  73554. var video = document.createElement("video");
  73555. if (typeof src === "string") {
  73556. BABYLON.Tools.SetCorsBehavior(src, video);
  73557. video.src = src;
  73558. }
  73559. else {
  73560. BABYLON.Tools.SetCorsBehavior(src[0], video);
  73561. src.forEach(function (url) {
  73562. var source = document.createElement("source");
  73563. source.src = url;
  73564. video.appendChild(source);
  73565. });
  73566. }
  73567. return video;
  73568. };
  73569. /**
  73570. * @hidden Internal method to initiate `update`.
  73571. */
  73572. VideoTexture.prototype._rebuild = function () {
  73573. this.update();
  73574. };
  73575. /**
  73576. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  73577. */
  73578. VideoTexture.prototype.update = function () {
  73579. if (!this.autoUpdateTexture) {
  73580. // Expecting user to call `updateTexture` manually
  73581. return;
  73582. }
  73583. this.updateTexture(true);
  73584. };
  73585. /**
  73586. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  73587. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  73588. */
  73589. VideoTexture.prototype.updateTexture = function (isVisible) {
  73590. if (!isVisible) {
  73591. return;
  73592. }
  73593. if (this.video.paused && this._stillImageCaptured) {
  73594. return;
  73595. }
  73596. this._stillImageCaptured = true;
  73597. this._updateInternalTexture();
  73598. };
  73599. /**
  73600. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  73601. * @param url New url.
  73602. */
  73603. VideoTexture.prototype.updateURL = function (url) {
  73604. this.video.src = url;
  73605. };
  73606. /**
  73607. * Dispose the texture and release its associated resources.
  73608. */
  73609. VideoTexture.prototype.dispose = function () {
  73610. _super.prototype.dispose.call(this);
  73611. if (this._onUserActionRequestedObservable) {
  73612. this._onUserActionRequestedObservable.clear();
  73613. this._onUserActionRequestedObservable = null;
  73614. }
  73615. this.video.removeEventListener("canplay", this._createInternalTexture);
  73616. this.video.removeEventListener("paused", this._updateInternalTexture);
  73617. this.video.removeEventListener("seeked", this._updateInternalTexture);
  73618. this.video.removeEventListener("emptied", this.reset);
  73619. this.video.pause();
  73620. };
  73621. /**
  73622. * Creates a video texture straight from your WebCam video feed.
  73623. * @param scene Define the scene the texture should be created in
  73624. * @param onReady Define a callback to triggered once the texture will be ready
  73625. * @param constraints Define the constraints to use to create the web cam feed from WebRTC
  73626. */
  73627. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  73628. var video = document.createElement("video");
  73629. video.setAttribute('autoplay', '');
  73630. video.setAttribute('muted', '');
  73631. video.setAttribute('playsinline', '');
  73632. var constraintsDeviceId;
  73633. if (constraints && constraints.deviceId) {
  73634. constraintsDeviceId = {
  73635. exact: constraints.deviceId,
  73636. };
  73637. }
  73638. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  73639. if (navigator.mediaDevices) {
  73640. navigator.mediaDevices.getUserMedia({ video: constraints })
  73641. .then(function (stream) {
  73642. if (video.mozSrcObject !== undefined) {
  73643. // hack for Firefox < 19
  73644. video.mozSrcObject = stream;
  73645. }
  73646. else {
  73647. video.srcObject = stream;
  73648. }
  73649. var onPlaying = function () {
  73650. if (onReady) {
  73651. onReady(new VideoTexture("video", video, scene, true, true));
  73652. }
  73653. video.removeEventListener("playing", onPlaying);
  73654. };
  73655. video.addEventListener("playing", onPlaying);
  73656. video.play();
  73657. })
  73658. .catch(function (err) {
  73659. BABYLON.Tools.Error(err.name);
  73660. });
  73661. }
  73662. else {
  73663. navigator.getUserMedia =
  73664. navigator.getUserMedia ||
  73665. navigator.webkitGetUserMedia ||
  73666. navigator.mozGetUserMedia ||
  73667. navigator.msGetUserMedia;
  73668. if (navigator.getUserMedia) {
  73669. navigator.getUserMedia({
  73670. video: {
  73671. deviceId: constraintsDeviceId,
  73672. width: {
  73673. min: (constraints && constraints.minWidth) || 256,
  73674. max: (constraints && constraints.maxWidth) || 640,
  73675. },
  73676. height: {
  73677. min: (constraints && constraints.minHeight) || 256,
  73678. max: (constraints && constraints.maxHeight) || 480,
  73679. },
  73680. },
  73681. }, function (stream) {
  73682. if (video.mozSrcObject !== undefined) {
  73683. // hack for Firefox < 19
  73684. video.mozSrcObject = stream;
  73685. }
  73686. else {
  73687. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  73688. }
  73689. video.play();
  73690. if (onReady) {
  73691. onReady(new VideoTexture("video", video, scene, true, true));
  73692. }
  73693. }, function (e) {
  73694. BABYLON.Tools.Error(e.name);
  73695. });
  73696. }
  73697. }
  73698. };
  73699. return VideoTexture;
  73700. }(BABYLON.Texture));
  73701. BABYLON.VideoTexture = VideoTexture;
  73702. })(BABYLON || (BABYLON = {}));
  73703. //# sourceMappingURL=babylon.videoTexture.js.map
  73704. var BABYLON;
  73705. (function (BABYLON) {
  73706. /**
  73707. * Raw texture can help creating a texture directly from an array of data.
  73708. * This can be super useful if you either get the data from an uncompressed source or
  73709. * if you wish to create your texture pixel by pixel.
  73710. */
  73711. var RawTexture = /** @class */ (function (_super) {
  73712. __extends(RawTexture, _super);
  73713. /**
  73714. * Instantiates a new RawTexture.
  73715. * Raw texture can help creating a texture directly from an array of data.
  73716. * This can be super useful if you either get the data from an uncompressed source or
  73717. * if you wish to create your texture pixel by pixel.
  73718. * @param data define the array of data to use to create the texture
  73719. * @param width define the width of the texture
  73720. * @param height define the height of the texture
  73721. * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  73722. * @param scene define the scene the texture belongs to
  73723. * @param generateMipMaps define whether mip maps should be generated or not
  73724. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73725. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73726. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73727. */
  73728. function RawTexture(data, width, height,
  73729. /**
  73730. * Define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  73731. */
  73732. format, scene, generateMipMaps, invertY, samplingMode, type) {
  73733. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73734. if (invertY === void 0) { invertY = false; }
  73735. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73736. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73737. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  73738. _this.format = format;
  73739. _this._engine = scene.getEngine();
  73740. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  73741. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73742. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73743. return _this;
  73744. }
  73745. /**
  73746. * Updates the texture underlying data.
  73747. * @param data Define the new data of the texture
  73748. */
  73749. RawTexture.prototype.update = function (data) {
  73750. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  73751. };
  73752. /**
  73753. * Creates a luminance texture from some data.
  73754. * @param data Define the texture data
  73755. * @param width Define the width of the texture
  73756. * @param height Define the height of the texture
  73757. * @param scene Define the scene the texture belongs to
  73758. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73759. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73760. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73761. * @returns the luminance texture
  73762. */
  73763. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  73764. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73765. if (invertY === void 0) { invertY = false; }
  73766. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73767. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  73768. };
  73769. /**
  73770. * Creates a luminance alpha texture from some data.
  73771. * @param data Define the texture data
  73772. * @param width Define the width of the texture
  73773. * @param height Define the height of the texture
  73774. * @param scene Define the scene the texture belongs to
  73775. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73776. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73777. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73778. * @returns the luminance alpha texture
  73779. */
  73780. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  73781. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73782. if (invertY === void 0) { invertY = false; }
  73783. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73784. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  73785. };
  73786. /**
  73787. * Creates an alpha texture from some data.
  73788. * @param data Define the texture data
  73789. * @param width Define the width of the texture
  73790. * @param height Define the height of the texture
  73791. * @param scene Define the scene the texture belongs to
  73792. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73793. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73794. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73795. * @returns the alpha texture
  73796. */
  73797. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  73798. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73799. if (invertY === void 0) { invertY = false; }
  73800. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73801. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  73802. };
  73803. /**
  73804. * Creates a RGB texture from some data.
  73805. * @param data Define the texture data
  73806. * @param width Define the width of the texture
  73807. * @param height Define the height of the texture
  73808. * @param scene Define the scene the texture belongs to
  73809. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73810. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73811. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73812. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73813. * @returns the RGB alpha texture
  73814. */
  73815. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  73816. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73817. if (invertY === void 0) { invertY = false; }
  73818. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73819. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73820. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  73821. };
  73822. /**
  73823. * Creates a RGBA texture from some data.
  73824. * @param data Define the texture data
  73825. * @param width Define the width of the texture
  73826. * @param height Define the height of the texture
  73827. * @param scene Define the scene the texture belongs to
  73828. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73829. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73830. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73831. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73832. * @returns the RGBA texture
  73833. */
  73834. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  73835. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73836. if (invertY === void 0) { invertY = false; }
  73837. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73838. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73839. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  73840. };
  73841. /**
  73842. * Creates a R texture from some data.
  73843. * @param data Define the texture data
  73844. * @param width Define the width of the texture
  73845. * @param height Define the height of the texture
  73846. * @param scene Define the scene the texture belongs to
  73847. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73848. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73849. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73850. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73851. * @returns the R texture
  73852. */
  73853. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  73854. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73855. if (invertY === void 0) { invertY = false; }
  73856. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73857. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73858. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  73859. };
  73860. return RawTexture;
  73861. }(BABYLON.Texture));
  73862. BABYLON.RawTexture = RawTexture;
  73863. })(BABYLON || (BABYLON = {}));
  73864. //# sourceMappingURL=babylon.rawTexture.js.map
  73865. var BABYLON;
  73866. (function (BABYLON) {
  73867. /**
  73868. * Class used to store 3D textures containing user data
  73869. */
  73870. var RawTexture3D = /** @class */ (function (_super) {
  73871. __extends(RawTexture3D, _super);
  73872. /**
  73873. * Create a new RawTexture3D
  73874. * @param data defines the data of the texture
  73875. * @param width defines the width of the texture
  73876. * @param height defines the height of the texture
  73877. * @param depth defines the depth of the texture
  73878. * @param format defines the texture format to use
  73879. * @param scene defines the hosting scene
  73880. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  73881. * @param invertY defines if texture must be stored with Y axis inverted
  73882. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  73883. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  73884. */
  73885. function RawTexture3D(data, width, height, depth,
  73886. /** Gets or sets the texture format to use */
  73887. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  73888. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73889. if (invertY === void 0) { invertY = false; }
  73890. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73891. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73892. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  73893. _this.format = format;
  73894. _this._engine = scene.getEngine();
  73895. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  73896. _this.is3D = true;
  73897. return _this;
  73898. }
  73899. /**
  73900. * Update the texture with new data
  73901. * @param data defines the data to store in the texture
  73902. */
  73903. RawTexture3D.prototype.update = function (data) {
  73904. if (!this._texture) {
  73905. return;
  73906. }
  73907. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  73908. };
  73909. return RawTexture3D;
  73910. }(BABYLON.Texture));
  73911. BABYLON.RawTexture3D = RawTexture3D;
  73912. })(BABYLON || (BABYLON = {}));
  73913. //# sourceMappingURL=babylon.rawTexture3D.js.map
  73914. var BABYLON;
  73915. (function (BABYLON) {
  73916. /**
  73917. * PostProcessManager is used to manage one or more post processes or post process pipelines
  73918. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  73919. */
  73920. var PostProcessManager = /** @class */ (function () {
  73921. /**
  73922. * Creates a new instance PostProcess
  73923. * @param scene The scene that the post process is associated with.
  73924. */
  73925. function PostProcessManager(scene) {
  73926. this._vertexBuffers = {};
  73927. this._scene = scene;
  73928. }
  73929. PostProcessManager.prototype._prepareBuffers = function () {
  73930. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  73931. return;
  73932. }
  73933. // VBO
  73934. var vertices = [];
  73935. vertices.push(1, 1);
  73936. vertices.push(-1, 1);
  73937. vertices.push(-1, -1);
  73938. vertices.push(1, -1);
  73939. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73940. this._buildIndexBuffer();
  73941. };
  73942. PostProcessManager.prototype._buildIndexBuffer = function () {
  73943. // Indices
  73944. var indices = [];
  73945. indices.push(0);
  73946. indices.push(1);
  73947. indices.push(2);
  73948. indices.push(0);
  73949. indices.push(2);
  73950. indices.push(3);
  73951. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  73952. };
  73953. /**
  73954. * Rebuilds the vertex buffers of the manager.
  73955. * @hidden
  73956. */
  73957. PostProcessManager.prototype._rebuild = function () {
  73958. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73959. if (!vb) {
  73960. return;
  73961. }
  73962. vb._rebuild();
  73963. this._buildIndexBuffer();
  73964. };
  73965. // Methods
  73966. /**
  73967. * Prepares a frame to be run through a post process.
  73968. * @param sourceTexture The input texture to the post procesess. (default: null)
  73969. * @param postProcesses An array of post processes to be run. (default: null)
  73970. * @returns True if the post processes were able to be run.
  73971. * @hidden
  73972. */
  73973. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  73974. if (sourceTexture === void 0) { sourceTexture = null; }
  73975. if (postProcesses === void 0) { postProcesses = null; }
  73976. var camera = this._scene.activeCamera;
  73977. if (!camera) {
  73978. return false;
  73979. }
  73980. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  73981. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  73982. return false;
  73983. }
  73984. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  73985. return true;
  73986. };
  73987. /**
  73988. * Manually render a set of post processes to a texture.
  73989. * @param postProcesses An array of post processes to be run.
  73990. * @param targetTexture The target texture to render to.
  73991. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  73992. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  73993. * @param lodLevel defines which lod of the texture to render to
  73994. */
  73995. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  73996. if (targetTexture === void 0) { targetTexture = null; }
  73997. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  73998. if (faceIndex === void 0) { faceIndex = 0; }
  73999. if (lodLevel === void 0) { lodLevel = 0; }
  74000. var engine = this._scene.getEngine();
  74001. for (var index = 0; index < postProcesses.length; index++) {
  74002. if (index < postProcesses.length - 1) {
  74003. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  74004. }
  74005. else {
  74006. if (targetTexture) {
  74007. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  74008. }
  74009. else {
  74010. engine.restoreDefaultFramebuffer();
  74011. }
  74012. }
  74013. var pp = postProcesses[index];
  74014. var effect = pp.apply();
  74015. if (effect) {
  74016. pp.onBeforeRenderObservable.notifyObservers(effect);
  74017. // VBOs
  74018. this._prepareBuffers();
  74019. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  74020. // Draw order
  74021. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74022. pp.onAfterRenderObservable.notifyObservers(effect);
  74023. }
  74024. }
  74025. // Restore depth buffer
  74026. engine.setDepthBuffer(true);
  74027. engine.setDepthWrite(true);
  74028. };
  74029. /**
  74030. * Finalize the result of the output of the postprocesses.
  74031. * @param doNotPresent If true the result will not be displayed to the screen.
  74032. * @param targetTexture The target texture to render to.
  74033. * @param faceIndex The index of the face to bind the target texture to.
  74034. * @param postProcesses The array of post processes to render.
  74035. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  74036. * @hidden
  74037. */
  74038. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  74039. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  74040. var camera = this._scene.activeCamera;
  74041. if (!camera) {
  74042. return;
  74043. }
  74044. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  74045. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  74046. return;
  74047. }
  74048. var engine = this._scene.getEngine();
  74049. for (var index = 0, len = postProcesses.length; index < len; index++) {
  74050. var pp = postProcesses[index];
  74051. if (index < len - 1) {
  74052. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  74053. }
  74054. else {
  74055. if (targetTexture) {
  74056. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  74057. pp._outputTexture = targetTexture;
  74058. }
  74059. else {
  74060. engine.restoreDefaultFramebuffer();
  74061. pp._outputTexture = null;
  74062. }
  74063. }
  74064. if (doNotPresent) {
  74065. break;
  74066. }
  74067. var effect = pp.apply();
  74068. if (effect) {
  74069. pp.onBeforeRenderObservable.notifyObservers(effect);
  74070. // VBOs
  74071. this._prepareBuffers();
  74072. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  74073. // Draw order
  74074. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74075. pp.onAfterRenderObservable.notifyObservers(effect);
  74076. }
  74077. }
  74078. // Restore states
  74079. engine.setDepthBuffer(true);
  74080. engine.setDepthWrite(true);
  74081. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  74082. };
  74083. /**
  74084. * Disposes of the post process manager.
  74085. */
  74086. PostProcessManager.prototype.dispose = function () {
  74087. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74088. if (buffer) {
  74089. buffer.dispose();
  74090. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74091. }
  74092. if (this._indexBuffer) {
  74093. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74094. this._indexBuffer = null;
  74095. }
  74096. };
  74097. return PostProcessManager;
  74098. }());
  74099. BABYLON.PostProcessManager = PostProcessManager;
  74100. })(BABYLON || (BABYLON = {}));
  74101. //# sourceMappingURL=babylon.postProcessManager.js.map
  74102. var BABYLON;
  74103. (function (BABYLON) {
  74104. /**
  74105. * PostProcess can be used to apply a shader to a texture after it has been rendered
  74106. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  74107. */
  74108. var PostProcess = /** @class */ (function () {
  74109. /**
  74110. * Creates a new instance PostProcess
  74111. * @param name The name of the PostProcess.
  74112. * @param fragmentUrl The url of the fragment shader to be used.
  74113. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  74114. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  74115. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74116. * @param camera The camera to apply the render pass to.
  74117. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74118. * @param engine The engine which the post process will be applied. (default: current engine)
  74119. * @param reusable If the post process can be reused on the same frame. (default: false)
  74120. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  74121. * @param textureType Type of textures used when performing the post process. (default: 0)
  74122. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  74123. * @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
  74124. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  74125. */
  74126. function PostProcess(
  74127. /** Name of the PostProcess. */
  74128. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  74129. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  74130. if (defines === void 0) { defines = null; }
  74131. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74132. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  74133. if (blockCompilation === void 0) { blockCompilation = false; }
  74134. this.name = name;
  74135. /**
  74136. * Width of the texture to apply the post process on
  74137. */
  74138. this.width = -1;
  74139. /**
  74140. * Height of the texture to apply the post process on
  74141. */
  74142. this.height = -1;
  74143. /**
  74144. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  74145. * @hidden
  74146. */
  74147. this._outputTexture = null;
  74148. /**
  74149. * If the buffer needs to be cleared before applying the post process. (default: true)
  74150. * Should be set to false if shader will overwrite all previous pixels.
  74151. */
  74152. this.autoClear = true;
  74153. /**
  74154. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  74155. */
  74156. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  74157. /**
  74158. * Animations to be used for the post processing
  74159. */
  74160. this.animations = new Array();
  74161. /**
  74162. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  74163. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  74164. */
  74165. this.enablePixelPerfectMode = false;
  74166. /**
  74167. * Force the postprocess to be applied without taking in account viewport
  74168. */
  74169. this.forceFullscreenViewport = true;
  74170. /**
  74171. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  74172. *
  74173. * | Value | Type | Description |
  74174. * | ----- | ----------------------------------- | ----------- |
  74175. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  74176. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  74177. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  74178. *
  74179. */
  74180. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  74181. /**
  74182. * Force textures to be a power of two (default: false)
  74183. */
  74184. this.alwaysForcePOT = false;
  74185. this._samples = 1;
  74186. /**
  74187. * Modify the scale of the post process to be the same as the viewport (default: false)
  74188. */
  74189. this.adaptScaleToCurrentViewport = false;
  74190. this._reusable = false;
  74191. /**
  74192. * Smart array of input and output textures for the post process.
  74193. * @hidden
  74194. */
  74195. this._textures = new BABYLON.SmartArray(2);
  74196. /**
  74197. * The index in _textures that corresponds to the output texture.
  74198. * @hidden
  74199. */
  74200. this._currentRenderTextureInd = 0;
  74201. this._scaleRatio = new BABYLON.Vector2(1, 1);
  74202. this._texelSize = BABYLON.Vector2.Zero();
  74203. // Events
  74204. /**
  74205. * An event triggered when the postprocess is activated.
  74206. */
  74207. this.onActivateObservable = new BABYLON.Observable();
  74208. /**
  74209. * An event triggered when the postprocess changes its size.
  74210. */
  74211. this.onSizeChangedObservable = new BABYLON.Observable();
  74212. /**
  74213. * An event triggered when the postprocess applies its effect.
  74214. */
  74215. this.onApplyObservable = new BABYLON.Observable();
  74216. /**
  74217. * An event triggered before rendering the postprocess
  74218. */
  74219. this.onBeforeRenderObservable = new BABYLON.Observable();
  74220. /**
  74221. * An event triggered after rendering the postprocess
  74222. */
  74223. this.onAfterRenderObservable = new BABYLON.Observable();
  74224. if (camera != null) {
  74225. this._camera = camera;
  74226. this._scene = camera.getScene();
  74227. camera.attachPostProcess(this);
  74228. this._engine = this._scene.getEngine();
  74229. this._scene.postProcesses.push(this);
  74230. }
  74231. else if (engine) {
  74232. this._engine = engine;
  74233. this._engine.postProcesses.push(this);
  74234. }
  74235. this._options = options;
  74236. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  74237. this._reusable = reusable || false;
  74238. this._textureType = textureType;
  74239. this._samplers = samplers || [];
  74240. this._samplers.push("textureSampler");
  74241. this._fragmentUrl = fragmentUrl;
  74242. this._vertexUrl = vertexUrl;
  74243. this._parameters = parameters || [];
  74244. this._parameters.push("scale");
  74245. this._indexParameters = indexParameters;
  74246. if (!blockCompilation) {
  74247. this.updateEffect(defines);
  74248. }
  74249. }
  74250. Object.defineProperty(PostProcess.prototype, "samples", {
  74251. /**
  74252. * Number of sample textures (default: 1)
  74253. */
  74254. get: function () {
  74255. return this._samples;
  74256. },
  74257. set: function (n) {
  74258. var _this = this;
  74259. this._samples = n;
  74260. this._textures.forEach(function (texture) {
  74261. if (texture.samples !== _this._samples) {
  74262. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  74263. }
  74264. });
  74265. },
  74266. enumerable: true,
  74267. configurable: true
  74268. });
  74269. Object.defineProperty(PostProcess.prototype, "onActivate", {
  74270. /**
  74271. * A function that is added to the onActivateObservable
  74272. */
  74273. set: function (callback) {
  74274. if (this._onActivateObserver) {
  74275. this.onActivateObservable.remove(this._onActivateObserver);
  74276. }
  74277. if (callback) {
  74278. this._onActivateObserver = this.onActivateObservable.add(callback);
  74279. }
  74280. },
  74281. enumerable: true,
  74282. configurable: true
  74283. });
  74284. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  74285. /**
  74286. * A function that is added to the onSizeChangedObservable
  74287. */
  74288. set: function (callback) {
  74289. if (this._onSizeChangedObserver) {
  74290. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  74291. }
  74292. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  74293. },
  74294. enumerable: true,
  74295. configurable: true
  74296. });
  74297. Object.defineProperty(PostProcess.prototype, "onApply", {
  74298. /**
  74299. * A function that is added to the onApplyObservable
  74300. */
  74301. set: function (callback) {
  74302. if (this._onApplyObserver) {
  74303. this.onApplyObservable.remove(this._onApplyObserver);
  74304. }
  74305. this._onApplyObserver = this.onApplyObservable.add(callback);
  74306. },
  74307. enumerable: true,
  74308. configurable: true
  74309. });
  74310. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  74311. /**
  74312. * A function that is added to the onBeforeRenderObservable
  74313. */
  74314. set: function (callback) {
  74315. if (this._onBeforeRenderObserver) {
  74316. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  74317. }
  74318. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  74319. },
  74320. enumerable: true,
  74321. configurable: true
  74322. });
  74323. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  74324. /**
  74325. * A function that is added to the onAfterRenderObservable
  74326. */
  74327. set: function (callback) {
  74328. if (this._onAfterRenderObserver) {
  74329. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  74330. }
  74331. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  74332. },
  74333. enumerable: true,
  74334. configurable: true
  74335. });
  74336. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  74337. /**
  74338. * 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
  74339. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  74340. */
  74341. get: function () {
  74342. return this._textures.data[this._currentRenderTextureInd];
  74343. },
  74344. set: function (value) {
  74345. this._forcedOutputTexture = value;
  74346. },
  74347. enumerable: true,
  74348. configurable: true
  74349. });
  74350. /**
  74351. * Gets the camera which post process is applied to.
  74352. * @returns The camera the post process is applied to.
  74353. */
  74354. PostProcess.prototype.getCamera = function () {
  74355. return this._camera;
  74356. };
  74357. Object.defineProperty(PostProcess.prototype, "texelSize", {
  74358. /**
  74359. * Gets the texel size of the postprocess.
  74360. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  74361. */
  74362. get: function () {
  74363. if (this._shareOutputWithPostProcess) {
  74364. return this._shareOutputWithPostProcess.texelSize;
  74365. }
  74366. if (this._forcedOutputTexture) {
  74367. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  74368. }
  74369. return this._texelSize;
  74370. },
  74371. enumerable: true,
  74372. configurable: true
  74373. });
  74374. /**
  74375. * Gets the engine which this post process belongs to.
  74376. * @returns The engine the post process was enabled with.
  74377. */
  74378. PostProcess.prototype.getEngine = function () {
  74379. return this._engine;
  74380. };
  74381. /**
  74382. * The effect that is created when initializing the post process.
  74383. * @returns The created effect corrisponding the the postprocess.
  74384. */
  74385. PostProcess.prototype.getEffect = function () {
  74386. return this._effect;
  74387. };
  74388. /**
  74389. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  74390. * @param postProcess The post process to share the output with.
  74391. * @returns This post process.
  74392. */
  74393. PostProcess.prototype.shareOutputWith = function (postProcess) {
  74394. this._disposeTextures();
  74395. this._shareOutputWithPostProcess = postProcess;
  74396. return this;
  74397. };
  74398. /**
  74399. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  74400. * This should be called if the post process that shares output with this post process is disabled/disposed.
  74401. */
  74402. PostProcess.prototype.useOwnOutput = function () {
  74403. if (this._textures.length == 0) {
  74404. this._textures = new BABYLON.SmartArray(2);
  74405. }
  74406. this._shareOutputWithPostProcess = null;
  74407. };
  74408. /**
  74409. * Updates the effect with the current post process compile time values and recompiles the shader.
  74410. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74411. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74412. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74413. * @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
  74414. * @param onCompiled Called when the shader has been compiled.
  74415. * @param onError Called if there is an error when compiling a shader.
  74416. */
  74417. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74418. if (defines === void 0) { defines = null; }
  74419. if (uniforms === void 0) { uniforms = null; }
  74420. if (samplers === void 0) { samplers = null; }
  74421. 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);
  74422. };
  74423. /**
  74424. * The post process is reusable if it can be used multiple times within one frame.
  74425. * @returns If the post process is reusable
  74426. */
  74427. PostProcess.prototype.isReusable = function () {
  74428. return this._reusable;
  74429. };
  74430. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  74431. PostProcess.prototype.markTextureDirty = function () {
  74432. this.width = -1;
  74433. };
  74434. /**
  74435. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  74436. * 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.
  74437. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  74438. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  74439. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  74440. * @returns The target texture that was bound to be written to.
  74441. */
  74442. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  74443. var _this = this;
  74444. if (sourceTexture === void 0) { sourceTexture = null; }
  74445. camera = camera || this._camera;
  74446. var scene = camera.getScene();
  74447. var engine = scene.getEngine();
  74448. var maxSize = engine.getCaps().maxTextureSize;
  74449. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  74450. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  74451. // 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
  74452. var webVRCamera = camera.parent;
  74453. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  74454. requiredWidth /= 2;
  74455. }
  74456. var desiredWidth = (this._options.width || requiredWidth);
  74457. var desiredHeight = this._options.height || requiredHeight;
  74458. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  74459. if (this.adaptScaleToCurrentViewport) {
  74460. var currentViewport = engine.currentViewport;
  74461. if (currentViewport) {
  74462. desiredWidth *= currentViewport.width;
  74463. desiredHeight *= currentViewport.height;
  74464. }
  74465. }
  74466. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  74467. if (!this._options.width) {
  74468. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  74469. }
  74470. if (!this._options.height) {
  74471. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  74472. }
  74473. }
  74474. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  74475. if (this._textures.length > 0) {
  74476. for (var i = 0; i < this._textures.length; i++) {
  74477. this._engine._releaseTexture(this._textures.data[i]);
  74478. }
  74479. this._textures.reset();
  74480. }
  74481. this.width = desiredWidth;
  74482. this.height = desiredHeight;
  74483. var textureSize = { width: this.width, height: this.height };
  74484. var textureOptions = {
  74485. generateMipMaps: false,
  74486. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  74487. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  74488. samplingMode: this.renderTargetSamplingMode,
  74489. type: this._textureType
  74490. };
  74491. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  74492. if (this._reusable) {
  74493. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  74494. }
  74495. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  74496. this.onSizeChangedObservable.notifyObservers(this);
  74497. }
  74498. this._textures.forEach(function (texture) {
  74499. if (texture.samples !== _this.samples) {
  74500. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  74501. }
  74502. });
  74503. }
  74504. var target;
  74505. if (this._shareOutputWithPostProcess) {
  74506. target = this._shareOutputWithPostProcess.inputTexture;
  74507. }
  74508. else if (this._forcedOutputTexture) {
  74509. target = this._forcedOutputTexture;
  74510. this.width = this._forcedOutputTexture.width;
  74511. this.height = this._forcedOutputTexture.height;
  74512. }
  74513. else {
  74514. target = this.inputTexture;
  74515. }
  74516. // Bind the input of this post process to be used as the output of the previous post process.
  74517. if (this.enablePixelPerfectMode) {
  74518. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  74519. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  74520. }
  74521. else {
  74522. this._scaleRatio.copyFromFloats(1, 1);
  74523. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  74524. }
  74525. this.onActivateObservable.notifyObservers(camera);
  74526. // Clear
  74527. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  74528. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  74529. }
  74530. if (this._reusable) {
  74531. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  74532. }
  74533. return target;
  74534. };
  74535. Object.defineProperty(PostProcess.prototype, "isSupported", {
  74536. /**
  74537. * If the post process is supported.
  74538. */
  74539. get: function () {
  74540. return this._effect.isSupported;
  74541. },
  74542. enumerable: true,
  74543. configurable: true
  74544. });
  74545. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  74546. /**
  74547. * The aspect ratio of the output texture.
  74548. */
  74549. get: function () {
  74550. if (this._shareOutputWithPostProcess) {
  74551. return this._shareOutputWithPostProcess.aspectRatio;
  74552. }
  74553. if (this._forcedOutputTexture) {
  74554. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  74555. }
  74556. return this.width / this.height;
  74557. },
  74558. enumerable: true,
  74559. configurable: true
  74560. });
  74561. /**
  74562. * Get a value indicating if the post-process is ready to be used
  74563. * @returns true if the post-process is ready (shader is compiled)
  74564. */
  74565. PostProcess.prototype.isReady = function () {
  74566. return this._effect && this._effect.isReady();
  74567. };
  74568. /**
  74569. * Binds all textures and uniforms to the shader, this will be run on every pass.
  74570. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  74571. */
  74572. PostProcess.prototype.apply = function () {
  74573. // Check
  74574. if (!this._effect || !this._effect.isReady()) {
  74575. return null;
  74576. }
  74577. // States
  74578. this._engine.enableEffect(this._effect);
  74579. this._engine.setState(false);
  74580. this._engine.setDepthBuffer(false);
  74581. this._engine.setDepthWrite(false);
  74582. // Alpha
  74583. this._engine.setAlphaMode(this.alphaMode);
  74584. if (this.alphaConstants) {
  74585. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  74586. }
  74587. // Bind the output texture of the preivous post process as the input to this post process.
  74588. var source;
  74589. if (this._shareOutputWithPostProcess) {
  74590. source = this._shareOutputWithPostProcess.inputTexture;
  74591. }
  74592. else if (this._forcedOutputTexture) {
  74593. source = this._forcedOutputTexture;
  74594. }
  74595. else {
  74596. source = this.inputTexture;
  74597. }
  74598. this._effect._bindTexture("textureSampler", source);
  74599. // Parameters
  74600. this._effect.setVector2("scale", this._scaleRatio);
  74601. this.onApplyObservable.notifyObservers(this._effect);
  74602. return this._effect;
  74603. };
  74604. PostProcess.prototype._disposeTextures = function () {
  74605. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  74606. return;
  74607. }
  74608. if (this._textures.length > 0) {
  74609. for (var i = 0; i < this._textures.length; i++) {
  74610. this._engine._releaseTexture(this._textures.data[i]);
  74611. }
  74612. }
  74613. this._textures.dispose();
  74614. };
  74615. /**
  74616. * Disposes the post process.
  74617. * @param camera The camera to dispose the post process on.
  74618. */
  74619. PostProcess.prototype.dispose = function (camera) {
  74620. camera = camera || this._camera;
  74621. this._disposeTextures();
  74622. if (this._scene) {
  74623. var index_1 = this._scene.postProcesses.indexOf(this);
  74624. if (index_1 !== -1) {
  74625. this._scene.postProcesses.splice(index_1, 1);
  74626. }
  74627. }
  74628. else {
  74629. var index_2 = this._engine.postProcesses.indexOf(this);
  74630. if (index_2 !== -1) {
  74631. this._engine.postProcesses.splice(index_2, 1);
  74632. }
  74633. }
  74634. if (!camera) {
  74635. return;
  74636. }
  74637. camera.detachPostProcess(this);
  74638. var index = camera._postProcesses.indexOf(this);
  74639. if (index === 0 && camera._postProcesses.length > 0) {
  74640. var firstPostProcess = this._camera._getFirstPostProcess();
  74641. if (firstPostProcess) {
  74642. firstPostProcess.markTextureDirty();
  74643. }
  74644. }
  74645. this.onActivateObservable.clear();
  74646. this.onAfterRenderObservable.clear();
  74647. this.onApplyObservable.clear();
  74648. this.onBeforeRenderObservable.clear();
  74649. this.onSizeChangedObservable.clear();
  74650. };
  74651. return PostProcess;
  74652. }());
  74653. BABYLON.PostProcess = PostProcess;
  74654. })(BABYLON || (BABYLON = {}));
  74655. //# sourceMappingURL=babylon.postProcess.js.map
  74656. var BABYLON;
  74657. (function (BABYLON) {
  74658. /**
  74659. * PassPostProcess which produces an output the same as it's input
  74660. */
  74661. var PassPostProcess = /** @class */ (function (_super) {
  74662. __extends(PassPostProcess, _super);
  74663. /**
  74664. * Creates the PassPostProcess
  74665. * @param name The name of the effect.
  74666. * @param options The required width/height ratio to downsize to before computing the render pass.
  74667. * @param camera The camera to apply the render pass to.
  74668. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74669. * @param engine The engine which the post process will be applied. (default: current engine)
  74670. * @param reusable If the post process can be reused on the same frame. (default: false)
  74671. * @param textureType The type of texture to be used when performing the post processing.
  74672. * @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)
  74673. */
  74674. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74675. if (camera === void 0) { camera = null; }
  74676. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74677. if (blockCompilation === void 0) { blockCompilation = false; }
  74678. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  74679. }
  74680. return PassPostProcess;
  74681. }(BABYLON.PostProcess));
  74682. BABYLON.PassPostProcess = PassPostProcess;
  74683. })(BABYLON || (BABYLON = {}));
  74684. //# sourceMappingURL=babylon.passPostProcess.js.map
  74685. var __assign = (this && this.__assign) || function () {
  74686. __assign = Object.assign || function(t) {
  74687. for (var s, i = 1, n = arguments.length; i < n; i++) {
  74688. s = arguments[i];
  74689. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  74690. t[p] = s[p];
  74691. }
  74692. return t;
  74693. };
  74694. return __assign.apply(this, arguments);
  74695. };
  74696. var BABYLON;
  74697. (function (BABYLON) {
  74698. /**
  74699. * Default implementation IShadowGenerator.
  74700. * This is the main object responsible of generating shadows in the framework.
  74701. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  74702. */
  74703. var ShadowGenerator = /** @class */ (function () {
  74704. /**
  74705. * Creates a ShadowGenerator object.
  74706. * A ShadowGenerator is the required tool to use the shadows.
  74707. * Each light casting shadows needs to use its own ShadowGenerator.
  74708. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  74709. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  74710. * @param light The light object generating the shadows.
  74711. * @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.
  74712. */
  74713. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  74714. this._bias = 0.00005;
  74715. this._normalBias = 0;
  74716. this._blurBoxOffset = 1;
  74717. this._blurScale = 2;
  74718. this._blurKernel = 1;
  74719. this._useKernelBlur = false;
  74720. this._filter = ShadowGenerator.FILTER_NONE;
  74721. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  74722. this._contactHardeningLightSizeUVRatio = 0.1;
  74723. this._darkness = 0;
  74724. this._transparencyShadow = false;
  74725. /**
  74726. * Controls the extent to which the shadows fade out at the edge of the frustum
  74727. * Used only by directionals and spots
  74728. */
  74729. this.frustumEdgeFalloff = 0;
  74730. /**
  74731. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  74732. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  74733. * It might on the other hand introduce peter panning.
  74734. */
  74735. this.forceBackFacesOnly = false;
  74736. this._lightDirection = BABYLON.Vector3.Zero();
  74737. this._viewMatrix = BABYLON.Matrix.Zero();
  74738. this._projectionMatrix = BABYLON.Matrix.Zero();
  74739. this._transformMatrix = BABYLON.Matrix.Zero();
  74740. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  74741. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  74742. this._currentFaceIndex = 0;
  74743. this._currentFaceIndexCache = 0;
  74744. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  74745. this._mapSize = mapSize;
  74746. this._light = light;
  74747. this._scene = light.getScene();
  74748. light._shadowGenerator = this;
  74749. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  74750. if (!component) {
  74751. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  74752. this._scene._addComponent(component);
  74753. }
  74754. // Texture type fallback from float to int if not supported.
  74755. var caps = this._scene.getEngine().getCaps();
  74756. if (!useFullFloatFirst) {
  74757. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  74758. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74759. }
  74760. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  74761. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74762. }
  74763. else {
  74764. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74765. }
  74766. }
  74767. else {
  74768. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  74769. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74770. }
  74771. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  74772. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74773. }
  74774. else {
  74775. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74776. }
  74777. }
  74778. this._initializeGenerator();
  74779. this._applyFilterValues();
  74780. }
  74781. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  74782. /**
  74783. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  74784. */
  74785. get: function () {
  74786. return this._bias;
  74787. },
  74788. /**
  74789. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  74790. */
  74791. set: function (bias) {
  74792. this._bias = bias;
  74793. },
  74794. enumerable: true,
  74795. configurable: true
  74796. });
  74797. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  74798. /**
  74799. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  74800. */
  74801. get: function () {
  74802. return this._normalBias;
  74803. },
  74804. /**
  74805. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  74806. */
  74807. set: function (normalBias) {
  74808. this._normalBias = normalBias;
  74809. },
  74810. enumerable: true,
  74811. configurable: true
  74812. });
  74813. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  74814. /**
  74815. * Gets the blur box offset: offset applied during the blur pass.
  74816. * Only usefull if useKernelBlur = false
  74817. */
  74818. get: function () {
  74819. return this._blurBoxOffset;
  74820. },
  74821. /**
  74822. * Sets the blur box offset: offset applied during the blur pass.
  74823. * Only usefull if useKernelBlur = false
  74824. */
  74825. set: function (value) {
  74826. if (this._blurBoxOffset === value) {
  74827. return;
  74828. }
  74829. this._blurBoxOffset = value;
  74830. this._disposeBlurPostProcesses();
  74831. },
  74832. enumerable: true,
  74833. configurable: true
  74834. });
  74835. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  74836. /**
  74837. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  74838. * 2 means half of the size.
  74839. */
  74840. get: function () {
  74841. return this._blurScale;
  74842. },
  74843. /**
  74844. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  74845. * 2 means half of the size.
  74846. */
  74847. set: function (value) {
  74848. if (this._blurScale === value) {
  74849. return;
  74850. }
  74851. this._blurScale = value;
  74852. this._disposeBlurPostProcesses();
  74853. },
  74854. enumerable: true,
  74855. configurable: true
  74856. });
  74857. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  74858. /**
  74859. * Gets the blur kernel: kernel size of the blur pass.
  74860. * Only usefull if useKernelBlur = true
  74861. */
  74862. get: function () {
  74863. return this._blurKernel;
  74864. },
  74865. /**
  74866. * Sets the blur kernel: kernel size of the blur pass.
  74867. * Only usefull if useKernelBlur = true
  74868. */
  74869. set: function (value) {
  74870. if (this._blurKernel === value) {
  74871. return;
  74872. }
  74873. this._blurKernel = value;
  74874. this._disposeBlurPostProcesses();
  74875. },
  74876. enumerable: true,
  74877. configurable: true
  74878. });
  74879. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  74880. /**
  74881. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  74882. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  74883. */
  74884. get: function () {
  74885. return this._useKernelBlur;
  74886. },
  74887. /**
  74888. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  74889. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  74890. */
  74891. set: function (value) {
  74892. if (this._useKernelBlur === value) {
  74893. return;
  74894. }
  74895. this._useKernelBlur = value;
  74896. this._disposeBlurPostProcesses();
  74897. },
  74898. enumerable: true,
  74899. configurable: true
  74900. });
  74901. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  74902. /**
  74903. * Gets the depth scale used in ESM mode.
  74904. */
  74905. get: function () {
  74906. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  74907. },
  74908. /**
  74909. * Sets the depth scale used in ESM mode.
  74910. * This can override the scale stored on the light.
  74911. */
  74912. set: function (value) {
  74913. this._depthScale = value;
  74914. },
  74915. enumerable: true,
  74916. configurable: true
  74917. });
  74918. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  74919. /**
  74920. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  74921. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  74922. */
  74923. get: function () {
  74924. return this._filter;
  74925. },
  74926. /**
  74927. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  74928. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  74929. */
  74930. set: function (value) {
  74931. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  74932. if (this._light.needCube()) {
  74933. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  74934. this.useExponentialShadowMap = true;
  74935. return;
  74936. }
  74937. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  74938. this.useCloseExponentialShadowMap = true;
  74939. return;
  74940. }
  74941. // PCF on cubemap would also be expensive
  74942. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  74943. this.usePoissonSampling = true;
  74944. return;
  74945. }
  74946. }
  74947. // Weblg1 fallback for PCF.
  74948. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  74949. if (this._scene.getEngine().webGLVersion === 1) {
  74950. this.usePoissonSampling = true;
  74951. return;
  74952. }
  74953. }
  74954. if (this._filter === value) {
  74955. return;
  74956. }
  74957. this._filter = value;
  74958. this._disposeBlurPostProcesses();
  74959. this._applyFilterValues();
  74960. this._light._markMeshesAsLightDirty();
  74961. },
  74962. enumerable: true,
  74963. configurable: true
  74964. });
  74965. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  74966. /**
  74967. * Gets if the current filter is set to Poisson Sampling.
  74968. */
  74969. get: function () {
  74970. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  74971. },
  74972. /**
  74973. * Sets the current filter to Poisson Sampling.
  74974. */
  74975. set: function (value) {
  74976. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  74977. return;
  74978. }
  74979. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  74980. },
  74981. enumerable: true,
  74982. configurable: true
  74983. });
  74984. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  74985. /**
  74986. * Gets if the current filter is set to VSM.
  74987. * DEPRECATED. Should use useExponentialShadowMap instead.
  74988. */
  74989. get: function () {
  74990. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  74991. return this.useExponentialShadowMap;
  74992. },
  74993. /**
  74994. * Sets the current filter is to VSM.
  74995. * DEPRECATED. Should use useExponentialShadowMap instead.
  74996. */
  74997. set: function (value) {
  74998. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  74999. this.useExponentialShadowMap = value;
  75000. },
  75001. enumerable: true,
  75002. configurable: true
  75003. });
  75004. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  75005. /**
  75006. * Gets if the current filter is set to blurred VSM.
  75007. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  75008. */
  75009. get: function () {
  75010. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  75011. return this.useBlurExponentialShadowMap;
  75012. },
  75013. /**
  75014. * Sets the current filter is to blurred VSM.
  75015. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  75016. */
  75017. set: function (value) {
  75018. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  75019. this.useBlurExponentialShadowMap = value;
  75020. },
  75021. enumerable: true,
  75022. configurable: true
  75023. });
  75024. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  75025. /**
  75026. * Gets if the current filter is set to ESM.
  75027. */
  75028. get: function () {
  75029. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  75030. },
  75031. /**
  75032. * Sets the current filter is to ESM.
  75033. */
  75034. set: function (value) {
  75035. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  75036. return;
  75037. }
  75038. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  75039. },
  75040. enumerable: true,
  75041. configurable: true
  75042. });
  75043. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  75044. /**
  75045. * Gets if the current filter is set to filtered ESM.
  75046. */
  75047. get: function () {
  75048. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  75049. },
  75050. /**
  75051. * Gets if the current filter is set to filtered ESM.
  75052. */
  75053. set: function (value) {
  75054. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  75055. return;
  75056. }
  75057. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  75058. },
  75059. enumerable: true,
  75060. configurable: true
  75061. });
  75062. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  75063. /**
  75064. * Gets if the current filter is set to "close ESM" (using the inverse of the
  75065. * exponential to prevent steep falloff artifacts).
  75066. */
  75067. get: function () {
  75068. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  75069. },
  75070. /**
  75071. * Sets the current filter to "close ESM" (using the inverse of the
  75072. * exponential to prevent steep falloff artifacts).
  75073. */
  75074. set: function (value) {
  75075. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  75076. return;
  75077. }
  75078. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  75079. },
  75080. enumerable: true,
  75081. configurable: true
  75082. });
  75083. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  75084. /**
  75085. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  75086. * exponential to prevent steep falloff artifacts).
  75087. */
  75088. get: function () {
  75089. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  75090. },
  75091. /**
  75092. * Sets the current filter to filtered "close ESM" (using the inverse of the
  75093. * exponential to prevent steep falloff artifacts).
  75094. */
  75095. set: function (value) {
  75096. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  75097. return;
  75098. }
  75099. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  75100. },
  75101. enumerable: true,
  75102. configurable: true
  75103. });
  75104. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  75105. /**
  75106. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  75107. */
  75108. get: function () {
  75109. return this.filter === ShadowGenerator.FILTER_PCF;
  75110. },
  75111. /**
  75112. * Sets the current filter to "PCF" (percentage closer filtering).
  75113. */
  75114. set: function (value) {
  75115. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  75116. return;
  75117. }
  75118. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  75119. },
  75120. enumerable: true,
  75121. configurable: true
  75122. });
  75123. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  75124. /**
  75125. * Gets the PCF or PCSS Quality.
  75126. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  75127. */
  75128. get: function () {
  75129. return this._filteringQuality;
  75130. },
  75131. /**
  75132. * Sets the PCF or PCSS Quality.
  75133. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  75134. */
  75135. set: function (filteringQuality) {
  75136. this._filteringQuality = filteringQuality;
  75137. },
  75138. enumerable: true,
  75139. configurable: true
  75140. });
  75141. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  75142. /**
  75143. * Gets if the current filter is set to "PCSS" (contact hardening).
  75144. */
  75145. get: function () {
  75146. return this.filter === ShadowGenerator.FILTER_PCSS;
  75147. },
  75148. /**
  75149. * Sets the current filter to "PCSS" (contact hardening).
  75150. */
  75151. set: function (value) {
  75152. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  75153. return;
  75154. }
  75155. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  75156. },
  75157. enumerable: true,
  75158. configurable: true
  75159. });
  75160. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  75161. /**
  75162. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  75163. * Using a ratio helps keeping shape stability independently of the map size.
  75164. *
  75165. * It does not account for the light projection as it was having too much
  75166. * instability during the light setup or during light position changes.
  75167. *
  75168. * Only valid if useContactHardeningShadow is true.
  75169. */
  75170. get: function () {
  75171. return this._contactHardeningLightSizeUVRatio;
  75172. },
  75173. /**
  75174. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  75175. * Using a ratio helps keeping shape stability independently of the map size.
  75176. *
  75177. * It does not account for the light projection as it was having too much
  75178. * instability during the light setup or during light position changes.
  75179. *
  75180. * Only valid if useContactHardeningShadow is true.
  75181. */
  75182. set: function (contactHardeningLightSizeUVRatio) {
  75183. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  75184. },
  75185. enumerable: true,
  75186. configurable: true
  75187. });
  75188. /**
  75189. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  75190. * 0 means strongest and 1 would means no shadow.
  75191. * @returns the darkness.
  75192. */
  75193. ShadowGenerator.prototype.getDarkness = function () {
  75194. return this._darkness;
  75195. };
  75196. /**
  75197. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  75198. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  75199. * @returns the shadow generator allowing fluent coding.
  75200. */
  75201. ShadowGenerator.prototype.setDarkness = function (darkness) {
  75202. if (darkness >= 1.0) {
  75203. this._darkness = 1.0;
  75204. }
  75205. else if (darkness <= 0.0) {
  75206. this._darkness = 0.0;
  75207. }
  75208. else {
  75209. this._darkness = darkness;
  75210. }
  75211. return this;
  75212. };
  75213. /**
  75214. * Sets the ability to have transparent shadow (boolean).
  75215. * @param transparent True if transparent else False
  75216. * @returns the shadow generator allowing fluent coding
  75217. */
  75218. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  75219. this._transparencyShadow = transparent;
  75220. return this;
  75221. };
  75222. /**
  75223. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  75224. * @returns The render target texture if present otherwise, null
  75225. */
  75226. ShadowGenerator.prototype.getShadowMap = function () {
  75227. return this._shadowMap;
  75228. };
  75229. /**
  75230. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  75231. * @returns The render target texture if the shadow map is present otherwise, null
  75232. */
  75233. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  75234. if (this._shadowMap2) {
  75235. return this._shadowMap2;
  75236. }
  75237. return this._shadowMap;
  75238. };
  75239. /**
  75240. * Helper function to add a mesh and its descendants to the list of shadow casters.
  75241. * @param mesh Mesh to add
  75242. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  75243. * @returns the Shadow Generator itself
  75244. */
  75245. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  75246. if (includeDescendants === void 0) { includeDescendants = true; }
  75247. var _a;
  75248. if (!this._shadowMap) {
  75249. return this;
  75250. }
  75251. if (!this._shadowMap.renderList) {
  75252. this._shadowMap.renderList = [];
  75253. }
  75254. this._shadowMap.renderList.push(mesh);
  75255. if (includeDescendants) {
  75256. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  75257. }
  75258. return this;
  75259. };
  75260. /**
  75261. * Helper function to remove a mesh and its descendants from the list of shadow casters
  75262. * @param mesh Mesh to remove
  75263. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  75264. * @returns the Shadow Generator itself
  75265. */
  75266. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  75267. if (includeDescendants === void 0) { includeDescendants = true; }
  75268. if (!this._shadowMap || !this._shadowMap.renderList) {
  75269. return this;
  75270. }
  75271. var index = this._shadowMap.renderList.indexOf(mesh);
  75272. if (index !== -1) {
  75273. this._shadowMap.renderList.splice(index, 1);
  75274. }
  75275. if (includeDescendants) {
  75276. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  75277. var child = _a[_i];
  75278. this.removeShadowCaster(child);
  75279. }
  75280. }
  75281. return this;
  75282. };
  75283. /**
  75284. * Returns the associated light object.
  75285. * @returns the light generating the shadow
  75286. */
  75287. ShadowGenerator.prototype.getLight = function () {
  75288. return this._light;
  75289. };
  75290. ShadowGenerator.prototype._initializeGenerator = function () {
  75291. this._light._markMeshesAsLightDirty();
  75292. this._initializeShadowMap();
  75293. };
  75294. ShadowGenerator.prototype._initializeShadowMap = function () {
  75295. var _this = this;
  75296. // Render target
  75297. var engine = this._scene.getEngine();
  75298. if (engine.webGLVersion > 1) {
  75299. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  75300. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  75301. }
  75302. else {
  75303. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  75304. }
  75305. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75306. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75307. this._shadowMap.anisotropicFilteringLevel = 1;
  75308. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75309. this._shadowMap.renderParticles = false;
  75310. this._shadowMap.ignoreCameraViewport = true;
  75311. // Record Face Index before render.
  75312. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  75313. _this._currentFaceIndex = faceIndex;
  75314. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  75315. engine.setColorWrite(false);
  75316. }
  75317. });
  75318. // Custom render function.
  75319. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  75320. // Blur if required afer render.
  75321. this._shadowMap.onAfterUnbindObservable.add(function () {
  75322. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  75323. engine.setColorWrite(true);
  75324. }
  75325. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  75326. return;
  75327. }
  75328. var shadowMap = _this.getShadowMapForRendering();
  75329. if (shadowMap) {
  75330. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  75331. }
  75332. });
  75333. // Clear according to the chosen filter.
  75334. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  75335. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  75336. this._shadowMap.onClearObservable.add(function (engine) {
  75337. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  75338. engine.clear(clearOne, false, true, false);
  75339. }
  75340. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  75341. engine.clear(clearZero, true, true, false);
  75342. }
  75343. else {
  75344. engine.clear(clearOne, true, true, false);
  75345. }
  75346. });
  75347. };
  75348. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  75349. var _this = this;
  75350. var engine = this._scene.getEngine();
  75351. var targetSize = this._mapSize / this.blurScale;
  75352. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  75353. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  75354. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75355. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75356. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75357. }
  75358. if (this.useKernelBlur) {
  75359. 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);
  75360. this._kernelBlurXPostprocess.width = targetSize;
  75361. this._kernelBlurXPostprocess.height = targetSize;
  75362. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  75363. effect.setTexture("textureSampler", _this._shadowMap);
  75364. });
  75365. 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);
  75366. this._kernelBlurXPostprocess.autoClear = false;
  75367. this._kernelBlurYPostprocess.autoClear = false;
  75368. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  75369. this._kernelBlurXPostprocess.packedFloat = true;
  75370. this._kernelBlurYPostprocess.packedFloat = true;
  75371. }
  75372. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  75373. }
  75374. else {
  75375. 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);
  75376. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  75377. effect.setFloat2("screenSize", targetSize, targetSize);
  75378. effect.setTexture("textureSampler", _this._shadowMap);
  75379. });
  75380. this._boxBlurPostprocess.autoClear = false;
  75381. this._blurPostProcesses = [this._boxBlurPostprocess];
  75382. }
  75383. };
  75384. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75385. var index;
  75386. var engine = this._scene.getEngine();
  75387. if (depthOnlySubMeshes.length) {
  75388. engine.setColorWrite(false);
  75389. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75390. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  75391. }
  75392. engine.setColorWrite(true);
  75393. }
  75394. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75395. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  75396. }
  75397. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75398. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  75399. }
  75400. if (this._transparencyShadow) {
  75401. for (index = 0; index < transparentSubMeshes.length; index++) {
  75402. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  75403. }
  75404. }
  75405. };
  75406. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  75407. var _this = this;
  75408. var mesh = subMesh.getRenderingMesh();
  75409. var scene = this._scene;
  75410. var engine = scene.getEngine();
  75411. var material = subMesh.getMaterial();
  75412. if (!material) {
  75413. return;
  75414. }
  75415. // Culling
  75416. engine.setState(material.backFaceCulling);
  75417. // Managing instances
  75418. var batch = mesh._getInstancesRenderList(subMesh._id);
  75419. if (batch.mustReturn) {
  75420. return;
  75421. }
  75422. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  75423. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  75424. engine.enableEffect(this._effect);
  75425. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  75426. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  75427. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  75428. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  75429. this._effect.setVector3("lightData", this._cachedDirection);
  75430. }
  75431. else {
  75432. this._effect.setVector3("lightData", this._cachedPosition);
  75433. }
  75434. if (scene.activeCamera) {
  75435. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  75436. }
  75437. // Alpha test
  75438. if (material && material.needAlphaTesting()) {
  75439. var alphaTexture = material.getAlphaTestTexture();
  75440. if (alphaTexture) {
  75441. this._effect.setTexture("diffuseSampler", alphaTexture);
  75442. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  75443. }
  75444. }
  75445. // Bones
  75446. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75447. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  75448. }
  75449. // Morph targets
  75450. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  75451. if (this.forceBackFacesOnly) {
  75452. engine.setState(true, 0, false, true);
  75453. }
  75454. // Draw
  75455. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  75456. if (this.forceBackFacesOnly) {
  75457. engine.setState(true, 0, false, false);
  75458. }
  75459. }
  75460. else {
  75461. // Need to reset refresh rate of the shadowMap
  75462. if (this._shadowMap) {
  75463. this._shadowMap.resetRefreshCounter();
  75464. }
  75465. }
  75466. };
  75467. ShadowGenerator.prototype._applyFilterValues = function () {
  75468. if (!this._shadowMap) {
  75469. return;
  75470. }
  75471. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  75472. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  75473. }
  75474. else {
  75475. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75476. }
  75477. };
  75478. /**
  75479. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  75480. * @param onCompiled Callback triggered at the and of the effects compilation
  75481. * @param options Sets of optional options forcing the compilation with different modes
  75482. */
  75483. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  75484. var _this = this;
  75485. var localOptions = __assign({ useInstances: false }, options);
  75486. var shadowMap = this.getShadowMap();
  75487. if (!shadowMap) {
  75488. if (onCompiled) {
  75489. onCompiled(this);
  75490. }
  75491. return;
  75492. }
  75493. var renderList = shadowMap.renderList;
  75494. if (!renderList) {
  75495. if (onCompiled) {
  75496. onCompiled(this);
  75497. }
  75498. return;
  75499. }
  75500. var subMeshes = new Array();
  75501. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  75502. var mesh = renderList_1[_i];
  75503. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  75504. }
  75505. if (subMeshes.length === 0) {
  75506. if (onCompiled) {
  75507. onCompiled(this);
  75508. }
  75509. return;
  75510. }
  75511. var currentIndex = 0;
  75512. var checkReady = function () {
  75513. if (!_this._scene || !_this._scene.getEngine()) {
  75514. return;
  75515. }
  75516. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  75517. currentIndex++;
  75518. if (currentIndex >= subMeshes.length) {
  75519. if (onCompiled) {
  75520. onCompiled(_this);
  75521. }
  75522. return;
  75523. }
  75524. }
  75525. setTimeout(checkReady, 16);
  75526. };
  75527. checkReady();
  75528. };
  75529. /**
  75530. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  75531. * @param options Sets of optional options forcing the compilation with different modes
  75532. * @returns A promise that resolves when the compilation completes
  75533. */
  75534. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  75535. var _this = this;
  75536. return new Promise(function (resolve) {
  75537. _this.forceCompilation(function () {
  75538. resolve();
  75539. }, options);
  75540. });
  75541. };
  75542. /**
  75543. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  75544. * @param subMesh The submesh we want to render in the shadow map
  75545. * @param useInstances Defines wether will draw in the map using instances
  75546. * @returns true if ready otherwise, false
  75547. */
  75548. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  75549. var defines = [];
  75550. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  75551. defines.push("#define FLOAT");
  75552. }
  75553. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  75554. defines.push("#define ESM");
  75555. }
  75556. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  75557. defines.push("#define DEPTHTEXTURE");
  75558. }
  75559. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75560. var mesh = subMesh.getMesh();
  75561. var material = subMesh.getMaterial();
  75562. // Normal bias.
  75563. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  75564. attribs.push(BABYLON.VertexBuffer.NormalKind);
  75565. defines.push("#define NORMAL");
  75566. if (mesh.nonUniformScaling) {
  75567. defines.push("#define NONUNIFORMSCALING");
  75568. }
  75569. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  75570. defines.push("#define DIRECTIONINLIGHTDATA");
  75571. }
  75572. }
  75573. // Alpha test
  75574. if (material && material.needAlphaTesting()) {
  75575. var alphaTexture = material.getAlphaTestTexture();
  75576. if (alphaTexture) {
  75577. defines.push("#define ALPHATEST");
  75578. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75579. attribs.push(BABYLON.VertexBuffer.UVKind);
  75580. defines.push("#define UV1");
  75581. }
  75582. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75583. if (alphaTexture.coordinatesIndex === 1) {
  75584. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75585. defines.push("#define UV2");
  75586. }
  75587. }
  75588. }
  75589. }
  75590. // Bones
  75591. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75592. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75593. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75594. if (mesh.numBoneInfluencers > 4) {
  75595. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75596. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75597. }
  75598. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75599. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  75600. }
  75601. else {
  75602. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75603. }
  75604. // Morph targets
  75605. var manager = mesh.morphTargetManager;
  75606. var morphInfluencers = 0;
  75607. if (manager) {
  75608. if (manager.numInfluencers > 0) {
  75609. defines.push("#define MORPHTARGETS");
  75610. morphInfluencers = manager.numInfluencers;
  75611. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  75612. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  75613. }
  75614. }
  75615. // Instances
  75616. if (useInstances) {
  75617. defines.push("#define INSTANCES");
  75618. attribs.push("world0");
  75619. attribs.push("world1");
  75620. attribs.push("world2");
  75621. attribs.push("world3");
  75622. }
  75623. // Get correct effect
  75624. var join = defines.join("\n");
  75625. if (this._cachedDefines !== join) {
  75626. this._cachedDefines = join;
  75627. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  75628. }
  75629. if (!this._effect.isReady()) {
  75630. return false;
  75631. }
  75632. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  75633. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  75634. this._initializeBlurRTTAndPostProcesses();
  75635. }
  75636. }
  75637. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  75638. return false;
  75639. }
  75640. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  75641. return false;
  75642. }
  75643. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  75644. return false;
  75645. }
  75646. return true;
  75647. };
  75648. /**
  75649. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  75650. * @param defines Defines of the material we want to update
  75651. * @param lightIndex Index of the light in the enabled light list of the material
  75652. */
  75653. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  75654. var scene = this._scene;
  75655. var light = this._light;
  75656. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  75657. return;
  75658. }
  75659. defines["SHADOW" + lightIndex] = true;
  75660. if (this.useContactHardeningShadow) {
  75661. defines["SHADOWPCSS" + lightIndex] = true;
  75662. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  75663. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  75664. }
  75665. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  75666. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  75667. }
  75668. // else default to high.
  75669. }
  75670. if (this.usePercentageCloserFiltering) {
  75671. defines["SHADOWPCF" + lightIndex] = true;
  75672. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  75673. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  75674. }
  75675. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  75676. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  75677. }
  75678. // else default to high.
  75679. }
  75680. else if (this.usePoissonSampling) {
  75681. defines["SHADOWPOISSON" + lightIndex] = true;
  75682. }
  75683. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  75684. defines["SHADOWESM" + lightIndex] = true;
  75685. }
  75686. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  75687. defines["SHADOWCLOSEESM" + lightIndex] = true;
  75688. }
  75689. if (light.needCube()) {
  75690. defines["SHADOWCUBE" + lightIndex] = true;
  75691. }
  75692. };
  75693. /**
  75694. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  75695. * defined in the generator but impacting the effect).
  75696. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  75697. * @param effect The effect we are binfing the information for
  75698. */
  75699. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  75700. var light = this._light;
  75701. var scene = this._scene;
  75702. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  75703. return;
  75704. }
  75705. var camera = scene.activeCamera;
  75706. if (!camera) {
  75707. return;
  75708. }
  75709. var shadowMap = this.getShadowMap();
  75710. if (!shadowMap) {
  75711. return;
  75712. }
  75713. if (!light.needCube()) {
  75714. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  75715. }
  75716. // Only PCF uses depth stencil texture.
  75717. if (this._filter === ShadowGenerator.FILTER_PCF) {
  75718. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  75719. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  75720. }
  75721. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  75722. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  75723. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  75724. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  75725. }
  75726. else {
  75727. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  75728. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  75729. }
  75730. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  75731. };
  75732. /**
  75733. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  75734. * (eq to shadow prjection matrix * light transform matrix)
  75735. * @returns The transform matrix used to create the shadow map
  75736. */
  75737. ShadowGenerator.prototype.getTransformMatrix = function () {
  75738. var scene = this._scene;
  75739. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  75740. return this._transformMatrix;
  75741. }
  75742. this._currentRenderID = scene.getRenderId();
  75743. this._currentFaceIndexCache = this._currentFaceIndex;
  75744. var lightPosition = this._light.position;
  75745. if (this._light.computeTransformedInformation()) {
  75746. lightPosition = this._light.transformedPosition;
  75747. }
  75748. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  75749. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  75750. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  75751. }
  75752. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  75753. this._cachedPosition.copyFrom(lightPosition);
  75754. this._cachedDirection.copyFrom(this._lightDirection);
  75755. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  75756. var shadowMap = this.getShadowMap();
  75757. if (shadowMap) {
  75758. var renderList = shadowMap.renderList;
  75759. if (renderList) {
  75760. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  75761. }
  75762. }
  75763. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  75764. }
  75765. return this._transformMatrix;
  75766. };
  75767. /**
  75768. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  75769. * Cube and 2D textures for instance.
  75770. */
  75771. ShadowGenerator.prototype.recreateShadowMap = function () {
  75772. var shadowMap = this._shadowMap;
  75773. if (!shadowMap) {
  75774. return;
  75775. }
  75776. // Track render list.
  75777. var renderList = shadowMap.renderList;
  75778. // Clean up existing data.
  75779. this._disposeRTTandPostProcesses();
  75780. // Reinitializes.
  75781. this._initializeGenerator();
  75782. // Reaffect the filter to ensure a correct fallback if necessary.
  75783. this.filter = this.filter;
  75784. // Reaffect the filter.
  75785. this._applyFilterValues();
  75786. // Reaffect Render List.
  75787. this._shadowMap.renderList = renderList;
  75788. };
  75789. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  75790. if (this._shadowMap2) {
  75791. this._shadowMap2.dispose();
  75792. this._shadowMap2 = null;
  75793. }
  75794. if (this._boxBlurPostprocess) {
  75795. this._boxBlurPostprocess.dispose();
  75796. this._boxBlurPostprocess = null;
  75797. }
  75798. if (this._kernelBlurXPostprocess) {
  75799. this._kernelBlurXPostprocess.dispose();
  75800. this._kernelBlurXPostprocess = null;
  75801. }
  75802. if (this._kernelBlurYPostprocess) {
  75803. this._kernelBlurYPostprocess.dispose();
  75804. this._kernelBlurYPostprocess = null;
  75805. }
  75806. this._blurPostProcesses = [];
  75807. };
  75808. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  75809. if (this._shadowMap) {
  75810. this._shadowMap.dispose();
  75811. this._shadowMap = null;
  75812. }
  75813. this._disposeBlurPostProcesses();
  75814. };
  75815. /**
  75816. * Disposes the ShadowGenerator.
  75817. * Returns nothing.
  75818. */
  75819. ShadowGenerator.prototype.dispose = function () {
  75820. this._disposeRTTandPostProcesses();
  75821. if (this._light) {
  75822. this._light._shadowGenerator = null;
  75823. this._light._markMeshesAsLightDirty();
  75824. }
  75825. };
  75826. /**
  75827. * Serializes the shadow generator setup to a json object.
  75828. * @returns The serialized JSON object
  75829. */
  75830. ShadowGenerator.prototype.serialize = function () {
  75831. var serializationObject = {};
  75832. var shadowMap = this.getShadowMap();
  75833. if (!shadowMap) {
  75834. return serializationObject;
  75835. }
  75836. serializationObject.lightId = this._light.id;
  75837. serializationObject.mapSize = shadowMap.getRenderSize();
  75838. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  75839. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  75840. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  75841. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  75842. serializationObject.usePoissonSampling = this.usePoissonSampling;
  75843. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  75844. serializationObject.depthScale = this.depthScale;
  75845. serializationObject.darkness = this.getDarkness();
  75846. serializationObject.blurBoxOffset = this.blurBoxOffset;
  75847. serializationObject.blurKernel = this.blurKernel;
  75848. serializationObject.blurScale = this.blurScale;
  75849. serializationObject.useKernelBlur = this.useKernelBlur;
  75850. serializationObject.transparencyShadow = this._transparencyShadow;
  75851. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  75852. serializationObject.bias = this.bias;
  75853. serializationObject.normalBias = this.normalBias;
  75854. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  75855. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  75856. serializationObject.filteringQuality = this.filteringQuality;
  75857. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  75858. serializationObject.renderList = [];
  75859. if (shadowMap.renderList) {
  75860. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  75861. var mesh = shadowMap.renderList[meshIndex];
  75862. serializationObject.renderList.push(mesh.id);
  75863. }
  75864. }
  75865. return serializationObject;
  75866. };
  75867. /**
  75868. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  75869. * @param parsedShadowGenerator The JSON object to parse
  75870. * @param scene The scene to create the shadow map for
  75871. * @returns The parsed shadow generator
  75872. */
  75873. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  75874. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  75875. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  75876. var shadowMap = shadowGenerator.getShadowMap();
  75877. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  75878. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  75879. meshes.forEach(function (mesh) {
  75880. if (!shadowMap) {
  75881. return;
  75882. }
  75883. if (!shadowMap.renderList) {
  75884. shadowMap.renderList = [];
  75885. }
  75886. shadowMap.renderList.push(mesh);
  75887. });
  75888. }
  75889. if (parsedShadowGenerator.usePoissonSampling) {
  75890. shadowGenerator.usePoissonSampling = true;
  75891. }
  75892. else if (parsedShadowGenerator.useExponentialShadowMap) {
  75893. shadowGenerator.useExponentialShadowMap = true;
  75894. }
  75895. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  75896. shadowGenerator.useBlurExponentialShadowMap = true;
  75897. }
  75898. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  75899. shadowGenerator.useCloseExponentialShadowMap = true;
  75900. }
  75901. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  75902. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  75903. }
  75904. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  75905. shadowGenerator.usePercentageCloserFiltering = true;
  75906. }
  75907. else if (parsedShadowGenerator.useContactHardeningShadow) {
  75908. shadowGenerator.useContactHardeningShadow = true;
  75909. }
  75910. if (parsedShadowGenerator.filteringQuality) {
  75911. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  75912. }
  75913. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  75914. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  75915. }
  75916. // Backward compat
  75917. else if (parsedShadowGenerator.useVarianceShadowMap) {
  75918. shadowGenerator.useExponentialShadowMap = true;
  75919. }
  75920. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  75921. shadowGenerator.useBlurExponentialShadowMap = true;
  75922. }
  75923. if (parsedShadowGenerator.depthScale) {
  75924. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  75925. }
  75926. if (parsedShadowGenerator.blurScale) {
  75927. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  75928. }
  75929. if (parsedShadowGenerator.blurBoxOffset) {
  75930. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  75931. }
  75932. if (parsedShadowGenerator.useKernelBlur) {
  75933. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  75934. }
  75935. if (parsedShadowGenerator.blurKernel) {
  75936. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  75937. }
  75938. if (parsedShadowGenerator.bias !== undefined) {
  75939. shadowGenerator.bias = parsedShadowGenerator.bias;
  75940. }
  75941. if (parsedShadowGenerator.normalBias !== undefined) {
  75942. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  75943. }
  75944. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  75945. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  75946. }
  75947. if (parsedShadowGenerator.darkness) {
  75948. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  75949. }
  75950. if (parsedShadowGenerator.transparencyShadow) {
  75951. shadowGenerator.setTransparencyShadow(true);
  75952. }
  75953. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  75954. return shadowGenerator;
  75955. };
  75956. /**
  75957. * Shadow generator mode None: no filtering applied.
  75958. */
  75959. ShadowGenerator.FILTER_NONE = 0;
  75960. /**
  75961. * Shadow generator mode ESM: Exponential Shadow Mapping.
  75962. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  75963. */
  75964. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  75965. /**
  75966. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  75967. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  75968. */
  75969. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  75970. /**
  75971. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  75972. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  75973. */
  75974. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  75975. /**
  75976. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  75977. * edge artifacts on steep falloff.
  75978. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  75979. */
  75980. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  75981. /**
  75982. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  75983. * edge artifacts on steep falloff.
  75984. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  75985. */
  75986. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  75987. /**
  75988. * Shadow generator mode PCF: Percentage Closer Filtering
  75989. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  75990. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  75991. */
  75992. ShadowGenerator.FILTER_PCF = 6;
  75993. /**
  75994. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  75995. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  75996. * Contact Hardening
  75997. */
  75998. ShadowGenerator.FILTER_PCSS = 7;
  75999. /**
  76000. * Reserved for PCF and PCSS
  76001. * Highest Quality.
  76002. *
  76003. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  76004. *
  76005. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  76006. */
  76007. ShadowGenerator.QUALITY_HIGH = 0;
  76008. /**
  76009. * Reserved for PCF and PCSS
  76010. * Good tradeoff for quality/perf cross devices
  76011. *
  76012. * Execute PCF on a 3*3 kernel.
  76013. *
  76014. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  76015. */
  76016. ShadowGenerator.QUALITY_MEDIUM = 1;
  76017. /**
  76018. * Reserved for PCF and PCSS
  76019. * The lowest quality but the fastest.
  76020. *
  76021. * Execute PCF on a 1*1 kernel.
  76022. *
  76023. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  76024. */
  76025. ShadowGenerator.QUALITY_LOW = 2;
  76026. return ShadowGenerator;
  76027. }());
  76028. BABYLON.ShadowGenerator = ShadowGenerator;
  76029. })(BABYLON || (BABYLON = {}));
  76030. //# sourceMappingURL=babylon.shadowGenerator.js.map
  76031. var BABYLON;
  76032. (function (BABYLON) {
  76033. // Adds the parser to the scene parsers.
  76034. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  76035. // Shadows
  76036. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  76037. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  76038. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  76039. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  76040. // SG would be available on their associated lights
  76041. }
  76042. }
  76043. });
  76044. /**
  76045. * Defines the shadow generator component responsible to manage any shadow generators
  76046. * in a given scene.
  76047. */
  76048. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  76049. /**
  76050. * Creates a new instance of the component for the given scene
  76051. * @param scene Defines the scene to register the component in
  76052. */
  76053. function ShadowGeneratorSceneComponent(scene) {
  76054. /**
  76055. * The component name helpfull to identify the component in the list of scene components.
  76056. */
  76057. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  76058. this.scene = scene;
  76059. }
  76060. /**
  76061. * Registers the component in a given scene
  76062. */
  76063. ShadowGeneratorSceneComponent.prototype.register = function () {
  76064. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  76065. };
  76066. /**
  76067. * Rebuilds the elements related to this component in case of
  76068. * context lost for instance.
  76069. */
  76070. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  76071. // Nothing To Do Here.
  76072. };
  76073. /**
  76074. * Serializes the component data to the specified json object
  76075. * @param serializationObject The object to serialize to
  76076. */
  76077. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  76078. // Shadows
  76079. serializationObject.shadowGenerators = [];
  76080. var lights = this.scene.lights;
  76081. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  76082. var light = lights_1[_i];
  76083. var shadowGenerator = light.getShadowGenerator();
  76084. if (shadowGenerator) {
  76085. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  76086. }
  76087. }
  76088. };
  76089. /**
  76090. * Adds all the element from the container to the scene
  76091. * @param container the container holding the elements
  76092. */
  76093. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  76094. // Nothing To Do Here. (directly attached to a light)
  76095. };
  76096. /**
  76097. * Removes all the elements in the container from the scene
  76098. * @param container contains the elements to remove
  76099. */
  76100. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  76101. // Nothing To Do Here. (directly attached to a light)
  76102. };
  76103. /**
  76104. * Rebuilds the elements related to this component in case of
  76105. * context lost for instance.
  76106. */
  76107. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  76108. // Nothing To Do Here.
  76109. };
  76110. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  76111. // Shadows
  76112. var scene = this.scene;
  76113. if (this.scene.shadowsEnabled) {
  76114. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  76115. var light = scene.lights[lightIndex];
  76116. var shadowGenerator = light.getShadowGenerator();
  76117. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  76118. var shadowMap = (shadowGenerator.getShadowMap());
  76119. if (scene.textures.indexOf(shadowMap) !== -1) {
  76120. renderTargets.push(shadowMap);
  76121. }
  76122. }
  76123. }
  76124. }
  76125. };
  76126. return ShadowGeneratorSceneComponent;
  76127. }());
  76128. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  76129. })(BABYLON || (BABYLON = {}));
  76130. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  76131. var BABYLON;
  76132. (function (BABYLON) {
  76133. /**
  76134. * Class used for the default loading screen
  76135. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  76136. */
  76137. var DefaultLoadingScreen = /** @class */ (function () {
  76138. /**
  76139. * Creates a new default loading screen
  76140. * @param _renderingCanvas defines the canvas used to render the scene
  76141. * @param _loadingText defines the default text to display
  76142. * @param _loadingDivBackgroundColor defines the default background color
  76143. */
  76144. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  76145. if (_loadingText === void 0) { _loadingText = ""; }
  76146. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  76147. var _this = this;
  76148. this._renderingCanvas = _renderingCanvas;
  76149. this._loadingText = _loadingText;
  76150. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  76151. // Resize
  76152. this._resizeLoadingUI = function () {
  76153. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  76154. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  76155. if (!_this._loadingDiv) {
  76156. return;
  76157. }
  76158. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  76159. _this._loadingDiv.style.left = canvasRect.left + "px";
  76160. _this._loadingDiv.style.top = canvasRect.top + "px";
  76161. _this._loadingDiv.style.width = canvasRect.width + "px";
  76162. _this._loadingDiv.style.height = canvasRect.height + "px";
  76163. };
  76164. }
  76165. /**
  76166. * Function called to display the loading screen
  76167. */
  76168. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  76169. if (this._loadingDiv) {
  76170. // Do not add a loading screen if there is already one
  76171. return;
  76172. }
  76173. this._loadingDiv = document.createElement("div");
  76174. this._loadingDiv.id = "babylonjsLoadingDiv";
  76175. this._loadingDiv.style.opacity = "0";
  76176. this._loadingDiv.style.transition = "opacity 1.5s ease";
  76177. this._loadingDiv.style.pointerEvents = "none";
  76178. // Loading text
  76179. this._loadingTextDiv = document.createElement("div");
  76180. this._loadingTextDiv.style.position = "absolute";
  76181. this._loadingTextDiv.style.left = "0";
  76182. this._loadingTextDiv.style.top = "50%";
  76183. this._loadingTextDiv.style.marginTop = "80px";
  76184. this._loadingTextDiv.style.width = "100%";
  76185. this._loadingTextDiv.style.height = "20px";
  76186. this._loadingTextDiv.style.fontFamily = "Arial";
  76187. this._loadingTextDiv.style.fontSize = "14px";
  76188. this._loadingTextDiv.style.color = "white";
  76189. this._loadingTextDiv.style.textAlign = "center";
  76190. this._loadingTextDiv.innerHTML = "Loading";
  76191. this._loadingDiv.appendChild(this._loadingTextDiv);
  76192. //set the predefined text
  76193. this._loadingTextDiv.innerHTML = this._loadingText;
  76194. // Generating keyframes
  76195. var style = document.createElement('style');
  76196. style.type = 'text/css';
  76197. 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 }";
  76198. style.innerHTML = keyFrames;
  76199. document.getElementsByTagName('head')[0].appendChild(style);
  76200. // Loading img
  76201. var imgBack = new Image();
  76202. 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";
  76203. imgBack.style.position = "absolute";
  76204. imgBack.style.left = "50%";
  76205. imgBack.style.top = "50%";
  76206. imgBack.style.marginLeft = "-60px";
  76207. imgBack.style.marginTop = "-60px";
  76208. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  76209. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  76210. imgBack.style.transformOrigin = "50% 50%";
  76211. imgBack.style.webkitTransformOrigin = "50% 50%";
  76212. this._loadingDiv.appendChild(imgBack);
  76213. this._resizeLoadingUI();
  76214. window.addEventListener("resize", this._resizeLoadingUI);
  76215. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  76216. document.body.appendChild(this._loadingDiv);
  76217. this._loadingDiv.style.opacity = "1";
  76218. };
  76219. /**
  76220. * Function called to hide the loading screen
  76221. */
  76222. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  76223. var _this = this;
  76224. if (!this._loadingDiv) {
  76225. return;
  76226. }
  76227. var onTransitionEnd = function () {
  76228. if (!_this._loadingDiv) {
  76229. return;
  76230. }
  76231. document.body.removeChild(_this._loadingDiv);
  76232. window.removeEventListener("resize", _this._resizeLoadingUI);
  76233. _this._loadingDiv = null;
  76234. };
  76235. this._loadingDiv.style.opacity = "0";
  76236. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  76237. };
  76238. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  76239. get: function () {
  76240. return this._loadingText;
  76241. },
  76242. /**
  76243. * Gets or sets the text to display while loading
  76244. */
  76245. set: function (text) {
  76246. this._loadingText = text;
  76247. if (this._loadingTextDiv) {
  76248. this._loadingTextDiv.innerHTML = this._loadingText;
  76249. }
  76250. },
  76251. enumerable: true,
  76252. configurable: true
  76253. });
  76254. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  76255. /**
  76256. * Gets or sets the color to use for the background
  76257. */
  76258. get: function () {
  76259. return this._loadingDivBackgroundColor;
  76260. },
  76261. set: function (color) {
  76262. this._loadingDivBackgroundColor = color;
  76263. if (!this._loadingDiv) {
  76264. return;
  76265. }
  76266. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  76267. },
  76268. enumerable: true,
  76269. configurable: true
  76270. });
  76271. return DefaultLoadingScreen;
  76272. }());
  76273. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  76274. })(BABYLON || (BABYLON = {}));
  76275. //# sourceMappingURL=babylon.loadingScreen.js.map
  76276. var BABYLON;
  76277. (function (BABYLON) {
  76278. /**
  76279. * Class used to represent data loading progression
  76280. */
  76281. var SceneLoaderProgressEvent = /** @class */ (function () {
  76282. /**
  76283. * Create a new progress event
  76284. * @param lengthComputable defines if data length to load can be evaluated
  76285. * @param loaded defines the loaded data length
  76286. * @param total defines the data length to load
  76287. */
  76288. function SceneLoaderProgressEvent(
  76289. /** defines if data length to load can be evaluated */
  76290. lengthComputable,
  76291. /** defines the loaded data length */
  76292. loaded,
  76293. /** defines the data length to load */
  76294. total) {
  76295. this.lengthComputable = lengthComputable;
  76296. this.loaded = loaded;
  76297. this.total = total;
  76298. }
  76299. /**
  76300. * Creates a new SceneLoaderProgressEvent from a ProgressEvent
  76301. * @param event defines the source event
  76302. * @returns a new SceneLoaderProgressEvent
  76303. */
  76304. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  76305. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  76306. };
  76307. return SceneLoaderProgressEvent;
  76308. }());
  76309. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  76310. /**
  76311. * Class used to load scene from various file formats using registered plugins
  76312. * @see http://doc.babylonjs.com/how_to/load_from_any_file_type
  76313. */
  76314. var SceneLoader = /** @class */ (function () {
  76315. function SceneLoader() {
  76316. }
  76317. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  76318. /**
  76319. * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data
  76320. */
  76321. get: function () {
  76322. return SceneLoader._ForceFullSceneLoadingForIncremental;
  76323. },
  76324. set: function (value) {
  76325. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  76326. },
  76327. enumerable: true,
  76328. configurable: true
  76329. });
  76330. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  76331. /**
  76332. * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene
  76333. */
  76334. get: function () {
  76335. return SceneLoader._ShowLoadingScreen;
  76336. },
  76337. set: function (value) {
  76338. SceneLoader._ShowLoadingScreen = value;
  76339. },
  76340. enumerable: true,
  76341. configurable: true
  76342. });
  76343. Object.defineProperty(SceneLoader, "loggingLevel", {
  76344. /**
  76345. * Defines the current logging level (while loading the scene)
  76346. * @ignorenaming
  76347. */
  76348. get: function () {
  76349. return SceneLoader._loggingLevel;
  76350. },
  76351. set: function (value) {
  76352. SceneLoader._loggingLevel = value;
  76353. },
  76354. enumerable: true,
  76355. configurable: true
  76356. });
  76357. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  76358. /**
  76359. * Gets or set a boolean indicating if matrix weights must be cleaned upon loading
  76360. */
  76361. get: function () {
  76362. return SceneLoader._CleanBoneMatrixWeights;
  76363. },
  76364. set: function (value) {
  76365. SceneLoader._CleanBoneMatrixWeights = value;
  76366. },
  76367. enumerable: true,
  76368. configurable: true
  76369. });
  76370. SceneLoader._getDefaultPlugin = function () {
  76371. return SceneLoader._registeredPlugins[".babylon"];
  76372. };
  76373. SceneLoader._getPluginForExtension = function (extension) {
  76374. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  76375. if (registeredPlugin) {
  76376. return registeredPlugin;
  76377. }
  76378. 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");
  76379. return SceneLoader._getDefaultPlugin();
  76380. };
  76381. SceneLoader._getPluginForDirectLoad = function (data) {
  76382. for (var extension in SceneLoader._registeredPlugins) {
  76383. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  76384. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  76385. return SceneLoader._registeredPlugins[extension];
  76386. }
  76387. }
  76388. return SceneLoader._getDefaultPlugin();
  76389. };
  76390. SceneLoader._getPluginForFilename = function (sceneFilename) {
  76391. var queryStringPosition = sceneFilename.indexOf("?");
  76392. if (queryStringPosition !== -1) {
  76393. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  76394. }
  76395. var dotPosition = sceneFilename.lastIndexOf(".");
  76396. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  76397. return SceneLoader._getPluginForExtension(extension);
  76398. };
  76399. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  76400. SceneLoader._getDirectLoad = function (sceneFilename) {
  76401. if (sceneFilename.substr(0, 5) === "data:") {
  76402. return sceneFilename.substr(5);
  76403. }
  76404. return null;
  76405. };
  76406. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  76407. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  76408. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  76409. var plugin;
  76410. if (registeredPlugin.plugin.createPlugin) {
  76411. plugin = registeredPlugin.plugin.createPlugin();
  76412. }
  76413. else {
  76414. plugin = registeredPlugin.plugin;
  76415. }
  76416. var useArrayBuffer = registeredPlugin.isBinary;
  76417. var database;
  76418. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  76419. var dataCallback = function (data, responseURL) {
  76420. if (scene.isDisposed) {
  76421. onError("Scene has been disposed");
  76422. return;
  76423. }
  76424. scene.database = database;
  76425. onSuccess(plugin, data, responseURL);
  76426. };
  76427. var request = null;
  76428. var pluginDisposed = false;
  76429. var onDisposeObservable = plugin.onDisposeObservable;
  76430. if (onDisposeObservable) {
  76431. onDisposeObservable.add(function () {
  76432. pluginDisposed = true;
  76433. if (request) {
  76434. request.abort();
  76435. request = null;
  76436. }
  76437. onDispose();
  76438. });
  76439. }
  76440. var manifestChecked = function () {
  76441. if (pluginDisposed) {
  76442. return;
  76443. }
  76444. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  76445. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  76446. } : undefined, database, useArrayBuffer, function (request, exception) {
  76447. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  76448. });
  76449. };
  76450. if (directLoad) {
  76451. dataCallback(directLoad);
  76452. return plugin;
  76453. }
  76454. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  76455. var engine = scene.getEngine();
  76456. var canUseOfflineSupport = engine.enableOfflineSupport;
  76457. if (canUseOfflineSupport) {
  76458. // Also check for exceptions
  76459. var exceptionFound = false;
  76460. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  76461. var regex = _a[_i];
  76462. if (regex.test(fileInfo.url)) {
  76463. exceptionFound = true;
  76464. break;
  76465. }
  76466. }
  76467. canUseOfflineSupport = !exceptionFound;
  76468. }
  76469. if (canUseOfflineSupport) {
  76470. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  76471. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  76472. }
  76473. else {
  76474. manifestChecked();
  76475. }
  76476. }
  76477. // Loading file from disk via input file or drag'n'drop
  76478. else {
  76479. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  76480. if (file) {
  76481. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  76482. }
  76483. else {
  76484. onError("Unable to find file named " + fileInfo.name);
  76485. }
  76486. }
  76487. return plugin;
  76488. };
  76489. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  76490. var url;
  76491. var name;
  76492. if (!sceneFilename) {
  76493. url = rootUrl;
  76494. name = BABYLON.Tools.GetFilename(rootUrl);
  76495. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  76496. }
  76497. else {
  76498. if (sceneFilename.substr(0, 1) === "/") {
  76499. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  76500. return null;
  76501. }
  76502. url = rootUrl + sceneFilename;
  76503. name = sceneFilename;
  76504. }
  76505. return {
  76506. url: url,
  76507. rootUrl: rootUrl,
  76508. name: name
  76509. };
  76510. };
  76511. // Public functions
  76512. /**
  76513. * Gets a plugin that can load the given extension
  76514. * @param extension defines the extension to load
  76515. * @returns a plugin or null if none works
  76516. */
  76517. SceneLoader.GetPluginForExtension = function (extension) {
  76518. return SceneLoader._getPluginForExtension(extension).plugin;
  76519. };
  76520. /**
  76521. * Gets a boolean indicating that the given extension can be loaded
  76522. * @param extension defines the extension to load
  76523. * @returns true if the extension is supported
  76524. */
  76525. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  76526. return !!SceneLoader._registeredPlugins[extension];
  76527. };
  76528. /**
  76529. * Adds a new plugin to the list of registered plugins
  76530. * @param plugin defines the plugin to add
  76531. */
  76532. SceneLoader.RegisterPlugin = function (plugin) {
  76533. if (typeof plugin.extensions === "string") {
  76534. var extension = plugin.extensions;
  76535. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  76536. plugin: plugin,
  76537. isBinary: false
  76538. };
  76539. }
  76540. else {
  76541. var extensions = plugin.extensions;
  76542. Object.keys(extensions).forEach(function (extension) {
  76543. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  76544. plugin: plugin,
  76545. isBinary: extensions[extension].isBinary
  76546. };
  76547. });
  76548. }
  76549. };
  76550. /**
  76551. * Import meshes into a scene
  76552. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  76553. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  76554. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  76555. * @param scene the instance of BABYLON.Scene to append to
  76556. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  76557. * @param onProgress a callback with a progress event for each file being loaded
  76558. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76559. * @param pluginExtension the extension used to determine the plugin
  76560. * @returns The loaded plugin
  76561. */
  76562. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  76563. if (sceneFilename === void 0) { sceneFilename = ""; }
  76564. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76565. if (onSuccess === void 0) { onSuccess = null; }
  76566. if (onProgress === void 0) { onProgress = null; }
  76567. if (onError === void 0) { onError = null; }
  76568. if (pluginExtension === void 0) { pluginExtension = null; }
  76569. if (!scene) {
  76570. BABYLON.Tools.Error("No scene available to import mesh to");
  76571. return null;
  76572. }
  76573. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  76574. if (!fileInfo) {
  76575. return null;
  76576. }
  76577. var loadingToken = {};
  76578. scene._addPendingData(loadingToken);
  76579. var disposeHandler = function () {
  76580. scene._removePendingData(loadingToken);
  76581. };
  76582. var errorHandler = function (message, exception) {
  76583. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  76584. if (onError) {
  76585. onError(scene, errorMessage, exception);
  76586. }
  76587. else {
  76588. BABYLON.Tools.Error(errorMessage);
  76589. // should the exception be thrown?
  76590. }
  76591. disposeHandler();
  76592. };
  76593. var progressHandler = onProgress ? function (event) {
  76594. try {
  76595. onProgress(event);
  76596. }
  76597. catch (e) {
  76598. errorHandler("Error in onProgress callback", e);
  76599. }
  76600. } : undefined;
  76601. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  76602. scene.importedMeshesFiles.push(fileInfo.url);
  76603. if (onSuccess) {
  76604. try {
  76605. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  76606. }
  76607. catch (e) {
  76608. errorHandler("Error in onSuccess callback", e);
  76609. }
  76610. }
  76611. scene._removePendingData(loadingToken);
  76612. };
  76613. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  76614. if (plugin.rewriteRootURL) {
  76615. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  76616. }
  76617. if (plugin.importMesh) {
  76618. var syncedPlugin = plugin;
  76619. var meshes = new Array();
  76620. var particleSystems = new Array();
  76621. var skeletons = new Array();
  76622. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  76623. return;
  76624. }
  76625. scene.loadingPluginName = plugin.name;
  76626. successHandler(meshes, particleSystems, skeletons, []);
  76627. }
  76628. else {
  76629. var asyncedPlugin = plugin;
  76630. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  76631. scene.loadingPluginName = plugin.name;
  76632. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  76633. }).catch(function (error) {
  76634. errorHandler(error.message, error);
  76635. });
  76636. }
  76637. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  76638. };
  76639. /**
  76640. * Import meshes into a scene
  76641. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  76642. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  76643. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  76644. * @param scene the instance of BABYLON.Scene to append to
  76645. * @param onProgress a callback with a progress event for each file being loaded
  76646. * @param pluginExtension the extension used to determine the plugin
  76647. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  76648. */
  76649. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  76650. if (sceneFilename === void 0) { sceneFilename = ""; }
  76651. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76652. if (onProgress === void 0) { onProgress = null; }
  76653. if (pluginExtension === void 0) { pluginExtension = null; }
  76654. return new Promise(function (resolve, reject) {
  76655. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  76656. resolve({
  76657. meshes: meshes,
  76658. particleSystems: particleSystems,
  76659. skeletons: skeletons,
  76660. animationGroups: animationGroups
  76661. });
  76662. }, onProgress, function (scene, message, exception) {
  76663. reject(exception || new Error(message));
  76664. }, pluginExtension);
  76665. });
  76666. };
  76667. /**
  76668. * Load a scene
  76669. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  76670. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  76671. * @param engine is the instance of BABYLON.Engine to use to create the scene
  76672. * @param onSuccess a callback with the scene when import succeeds
  76673. * @param onProgress a callback with a progress event for each file being loaded
  76674. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76675. * @param pluginExtension the extension used to determine the plugin
  76676. * @returns The loaded plugin
  76677. */
  76678. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  76679. if (onSuccess === void 0) { onSuccess = null; }
  76680. if (onProgress === void 0) { onProgress = null; }
  76681. if (onError === void 0) { onError = null; }
  76682. if (pluginExtension === void 0) { pluginExtension = null; }
  76683. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  76684. };
  76685. /**
  76686. * Load a scene
  76687. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  76688. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  76689. * @param engine is the instance of BABYLON.Engine to use to create the scene
  76690. * @param onProgress a callback with a progress event for each file being loaded
  76691. * @param pluginExtension the extension used to determine the plugin
  76692. * @returns The loaded scene
  76693. */
  76694. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  76695. if (onProgress === void 0) { onProgress = null; }
  76696. if (pluginExtension === void 0) { pluginExtension = null; }
  76697. return new Promise(function (resolve, reject) {
  76698. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  76699. resolve(scene);
  76700. }, onProgress, function (scene, message, exception) {
  76701. reject(exception || new Error(message));
  76702. }, pluginExtension);
  76703. });
  76704. };
  76705. /**
  76706. * Append a scene
  76707. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  76708. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  76709. * @param scene is the instance of BABYLON.Scene to append to
  76710. * @param onSuccess a callback with the scene when import succeeds
  76711. * @param onProgress a callback with a progress event for each file being loaded
  76712. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76713. * @param pluginExtension the extension used to determine the plugin
  76714. * @returns The loaded plugin
  76715. */
  76716. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  76717. if (sceneFilename === void 0) { sceneFilename = ""; }
  76718. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76719. if (onSuccess === void 0) { onSuccess = null; }
  76720. if (onProgress === void 0) { onProgress = null; }
  76721. if (onError === void 0) { onError = null; }
  76722. if (pluginExtension === void 0) { pluginExtension = null; }
  76723. if (!scene) {
  76724. BABYLON.Tools.Error("No scene available to append to");
  76725. return null;
  76726. }
  76727. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  76728. if (!fileInfo) {
  76729. return null;
  76730. }
  76731. if (SceneLoader.ShowLoadingScreen) {
  76732. scene.getEngine().displayLoadingUI();
  76733. }
  76734. var loadingToken = {};
  76735. scene._addPendingData(loadingToken);
  76736. var disposeHandler = function () {
  76737. scene._removePendingData(loadingToken);
  76738. scene.getEngine().hideLoadingUI();
  76739. };
  76740. var errorHandler = function (message, exception) {
  76741. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  76742. if (onError) {
  76743. onError(scene, errorMessage, exception);
  76744. }
  76745. else {
  76746. BABYLON.Tools.Error(errorMessage);
  76747. // should the exception be thrown?
  76748. }
  76749. disposeHandler();
  76750. };
  76751. var progressHandler = onProgress ? function (event) {
  76752. try {
  76753. onProgress(event);
  76754. }
  76755. catch (e) {
  76756. errorHandler("Error in onProgress callback", e);
  76757. }
  76758. } : undefined;
  76759. var successHandler = function () {
  76760. if (onSuccess) {
  76761. try {
  76762. onSuccess(scene);
  76763. }
  76764. catch (e) {
  76765. errorHandler("Error in onSuccess callback", e);
  76766. }
  76767. }
  76768. scene._removePendingData(loadingToken);
  76769. };
  76770. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  76771. if (plugin.load) {
  76772. var syncedPlugin = plugin;
  76773. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  76774. return;
  76775. }
  76776. scene.loadingPluginName = plugin.name;
  76777. successHandler();
  76778. }
  76779. else {
  76780. var asyncedPlugin = plugin;
  76781. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  76782. scene.loadingPluginName = plugin.name;
  76783. successHandler();
  76784. }).catch(function (error) {
  76785. errorHandler(error.message, error);
  76786. });
  76787. }
  76788. if (SceneLoader.ShowLoadingScreen) {
  76789. scene.executeWhenReady(function () {
  76790. scene.getEngine().hideLoadingUI();
  76791. });
  76792. }
  76793. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  76794. };
  76795. /**
  76796. * Append a scene
  76797. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  76798. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  76799. * @param scene is the instance of BABYLON.Scene to append to
  76800. * @param onProgress a callback with a progress event for each file being loaded
  76801. * @param pluginExtension the extension used to determine the plugin
  76802. * @returns The given scene
  76803. */
  76804. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  76805. if (sceneFilename === void 0) { sceneFilename = ""; }
  76806. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76807. if (onProgress === void 0) { onProgress = null; }
  76808. if (pluginExtension === void 0) { pluginExtension = null; }
  76809. return new Promise(function (resolve, reject) {
  76810. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  76811. resolve(scene);
  76812. }, onProgress, function (scene, message, exception) {
  76813. reject(exception || new Error(message));
  76814. }, pluginExtension);
  76815. });
  76816. };
  76817. /**
  76818. * Load a scene into an asset container
  76819. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  76820. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  76821. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  76822. * @param onSuccess a callback with the scene when import succeeds
  76823. * @param onProgress a callback with a progress event for each file being loaded
  76824. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76825. * @param pluginExtension the extension used to determine the plugin
  76826. * @returns The loaded plugin
  76827. */
  76828. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  76829. if (sceneFilename === void 0) { sceneFilename = ""; }
  76830. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76831. if (onSuccess === void 0) { onSuccess = null; }
  76832. if (onProgress === void 0) { onProgress = null; }
  76833. if (onError === void 0) { onError = null; }
  76834. if (pluginExtension === void 0) { pluginExtension = null; }
  76835. if (!scene) {
  76836. BABYLON.Tools.Error("No scene available to load asset container to");
  76837. return null;
  76838. }
  76839. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  76840. if (!fileInfo) {
  76841. return null;
  76842. }
  76843. var loadingToken = {};
  76844. scene._addPendingData(loadingToken);
  76845. var disposeHandler = function () {
  76846. scene._removePendingData(loadingToken);
  76847. };
  76848. var errorHandler = function (message, exception) {
  76849. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  76850. if (onError) {
  76851. onError(scene, errorMessage, exception);
  76852. }
  76853. else {
  76854. BABYLON.Tools.Error(errorMessage);
  76855. // should the exception be thrown?
  76856. }
  76857. disposeHandler();
  76858. };
  76859. var progressHandler = onProgress ? function (event) {
  76860. try {
  76861. onProgress(event);
  76862. }
  76863. catch (e) {
  76864. errorHandler("Error in onProgress callback", e);
  76865. }
  76866. } : undefined;
  76867. var successHandler = function (assets) {
  76868. if (onSuccess) {
  76869. try {
  76870. onSuccess(assets);
  76871. }
  76872. catch (e) {
  76873. errorHandler("Error in onSuccess callback", e);
  76874. }
  76875. }
  76876. scene._removePendingData(loadingToken);
  76877. };
  76878. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  76879. if (plugin.loadAssetContainer) {
  76880. var syncedPlugin = plugin;
  76881. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  76882. if (!assetContainer) {
  76883. return;
  76884. }
  76885. scene.loadingPluginName = plugin.name;
  76886. successHandler(assetContainer);
  76887. }
  76888. else if (plugin.loadAssetContainerAsync) {
  76889. var asyncedPlugin = plugin;
  76890. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  76891. scene.loadingPluginName = plugin.name;
  76892. successHandler(assetContainer);
  76893. }).catch(function (error) {
  76894. errorHandler(error.message, error);
  76895. });
  76896. }
  76897. else {
  76898. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  76899. }
  76900. if (SceneLoader.ShowLoadingScreen) {
  76901. scene.executeWhenReady(function () {
  76902. scene.getEngine().hideLoadingUI();
  76903. });
  76904. }
  76905. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  76906. };
  76907. /**
  76908. * Load a scene into an asset container
  76909. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  76910. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  76911. * @param scene is the instance of BABYLON.Scene to append to
  76912. * @param onProgress a callback with a progress event for each file being loaded
  76913. * @param pluginExtension the extension used to determine the plugin
  76914. * @returns The loaded asset container
  76915. */
  76916. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  76917. if (sceneFilename === void 0) { sceneFilename = ""; }
  76918. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76919. if (onProgress === void 0) { onProgress = null; }
  76920. if (pluginExtension === void 0) { pluginExtension = null; }
  76921. return new Promise(function (resolve, reject) {
  76922. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  76923. resolve(assetContainer);
  76924. }, onProgress, function (scene, message, exception) {
  76925. reject(exception || new Error(message));
  76926. }, pluginExtension);
  76927. });
  76928. };
  76929. // Flags
  76930. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  76931. SceneLoader._ShowLoadingScreen = true;
  76932. SceneLoader._CleanBoneMatrixWeights = false;
  76933. /**
  76934. * No logging while loading
  76935. */
  76936. SceneLoader.NO_LOGGING = 0;
  76937. /**
  76938. * Minimal logging while loading
  76939. */
  76940. SceneLoader.MINIMAL_LOGGING = 1;
  76941. /**
  76942. * Summary logging while loading
  76943. */
  76944. SceneLoader.SUMMARY_LOGGING = 2;
  76945. /**
  76946. * Detailled logging while loading
  76947. */
  76948. SceneLoader.DETAILED_LOGGING = 3;
  76949. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  76950. // Members
  76951. /**
  76952. * Event raised when a plugin is used to load a scene
  76953. */
  76954. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  76955. SceneLoader._registeredPlugins = {};
  76956. return SceneLoader;
  76957. }());
  76958. BABYLON.SceneLoader = SceneLoader;
  76959. })(BABYLON || (BABYLON = {}));
  76960. //# sourceMappingURL=babylon.sceneLoader.js.map
  76961. var BABYLON;
  76962. (function (BABYLON) {
  76963. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  76964. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  76965. var parsedMaterial = parsedData.materials[index];
  76966. if (parsedMaterial.id === id) {
  76967. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  76968. }
  76969. }
  76970. return null;
  76971. };
  76972. var isDescendantOf = function (mesh, names, hierarchyIds) {
  76973. for (var i in names) {
  76974. if (mesh.name === names[i]) {
  76975. hierarchyIds.push(mesh.id);
  76976. return true;
  76977. }
  76978. }
  76979. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  76980. hierarchyIds.push(mesh.id);
  76981. return true;
  76982. }
  76983. return false;
  76984. };
  76985. var logOperation = function (operation, producer) {
  76986. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  76987. };
  76988. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  76989. if (addToScene === void 0) { addToScene = false; }
  76990. var container = new BABYLON.AssetContainer(scene);
  76991. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  76992. // when SceneLoader.debugLogging = true (default), or exception encountered.
  76993. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  76994. // and avoid problems with multiple concurrent .babylon loads.
  76995. var log = "importScene has failed JSON parse";
  76996. try {
  76997. var parsedData = JSON.parse(data);
  76998. log = "";
  76999. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  77000. var index;
  77001. var cache;
  77002. // Lights
  77003. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  77004. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  77005. var parsedLight = parsedData.lights[index];
  77006. var light = BABYLON.Light.Parse(parsedLight, scene);
  77007. if (light) {
  77008. container.lights.push(light);
  77009. log += (index === 0 ? "\n\tLights:" : "");
  77010. log += "\n\t\t" + light.toString(fullDetails);
  77011. }
  77012. }
  77013. }
  77014. // Animations
  77015. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  77016. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  77017. var parsedAnimation = parsedData.animations[index];
  77018. var animation = BABYLON.Animation.Parse(parsedAnimation);
  77019. scene.animations.push(animation);
  77020. container.animations.push(animation);
  77021. log += (index === 0 ? "\n\tAnimations:" : "");
  77022. log += "\n\t\t" + animation.toString(fullDetails);
  77023. }
  77024. }
  77025. // Materials
  77026. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  77027. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  77028. var parsedMaterial = parsedData.materials[index];
  77029. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  77030. container.materials.push(mat);
  77031. log += (index === 0 ? "\n\tMaterials:" : "");
  77032. log += "\n\t\t" + mat.toString(fullDetails);
  77033. }
  77034. }
  77035. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  77036. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  77037. var parsedMultiMaterial = parsedData.multiMaterials[index];
  77038. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  77039. container.multiMaterials.push(mmat);
  77040. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  77041. log += "\n\t\t" + mmat.toString(fullDetails);
  77042. }
  77043. }
  77044. // Morph targets
  77045. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  77046. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  77047. var managerData = _a[_i];
  77048. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  77049. }
  77050. }
  77051. // Skeletons
  77052. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  77053. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  77054. var parsedSkeleton = parsedData.skeletons[index];
  77055. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  77056. container.skeletons.push(skeleton);
  77057. log += (index === 0 ? "\n\tSkeletons:" : "");
  77058. log += "\n\t\t" + skeleton.toString(fullDetails);
  77059. }
  77060. }
  77061. // Geometries
  77062. var geometries = parsedData.geometries;
  77063. if (geometries !== undefined && geometries !== null) {
  77064. var addedGeometry = new Array();
  77065. // Boxes
  77066. var boxes = geometries.boxes;
  77067. if (boxes !== undefined && boxes !== null) {
  77068. for (index = 0, cache = boxes.length; index < cache; index++) {
  77069. var parsedBox = boxes[index];
  77070. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  77071. }
  77072. }
  77073. // Spheres
  77074. var spheres = geometries.spheres;
  77075. if (spheres !== undefined && spheres !== null) {
  77076. for (index = 0, cache = spheres.length; index < cache; index++) {
  77077. var parsedSphere = spheres[index];
  77078. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  77079. }
  77080. }
  77081. // Cylinders
  77082. var cylinders = geometries.cylinders;
  77083. if (cylinders !== undefined && cylinders !== null) {
  77084. for (index = 0, cache = cylinders.length; index < cache; index++) {
  77085. var parsedCylinder = cylinders[index];
  77086. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  77087. }
  77088. }
  77089. // Toruses
  77090. var toruses = geometries.toruses;
  77091. if (toruses !== undefined && toruses !== null) {
  77092. for (index = 0, cache = toruses.length; index < cache; index++) {
  77093. var parsedTorus = toruses[index];
  77094. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  77095. }
  77096. }
  77097. // Grounds
  77098. var grounds = geometries.grounds;
  77099. if (grounds !== undefined && grounds !== null) {
  77100. for (index = 0, cache = grounds.length; index < cache; index++) {
  77101. var parsedGround = grounds[index];
  77102. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  77103. }
  77104. }
  77105. // Planes
  77106. var planes = geometries.planes;
  77107. if (planes !== undefined && planes !== null) {
  77108. for (index = 0, cache = planes.length; index < cache; index++) {
  77109. var parsedPlane = planes[index];
  77110. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  77111. }
  77112. }
  77113. // TorusKnots
  77114. var torusKnots = geometries.torusKnots;
  77115. if (torusKnots !== undefined && torusKnots !== null) {
  77116. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  77117. var parsedTorusKnot = torusKnots[index];
  77118. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  77119. }
  77120. }
  77121. // VertexData
  77122. var vertexData = geometries.vertexData;
  77123. if (vertexData !== undefined && vertexData !== null) {
  77124. for (index = 0, cache = vertexData.length; index < cache; index++) {
  77125. var parsedVertexData = vertexData[index];
  77126. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  77127. }
  77128. }
  77129. addedGeometry.forEach(function (g) {
  77130. if (g) {
  77131. container.geometries.push(g);
  77132. }
  77133. });
  77134. }
  77135. // Transform nodes
  77136. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  77137. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  77138. var parsedTransformNode = parsedData.transformNodes[index];
  77139. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  77140. container.transformNodes.push(node);
  77141. }
  77142. }
  77143. // Meshes
  77144. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  77145. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  77146. var parsedMesh = parsedData.meshes[index];
  77147. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  77148. container.meshes.push(mesh);
  77149. log += (index === 0 ? "\n\tMeshes:" : "");
  77150. log += "\n\t\t" + mesh.toString(fullDetails);
  77151. }
  77152. }
  77153. // Cameras
  77154. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  77155. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  77156. var parsedCamera = parsedData.cameras[index];
  77157. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  77158. container.cameras.push(camera);
  77159. log += (index === 0 ? "\n\tCameras:" : "");
  77160. log += "\n\t\t" + camera.toString(fullDetails);
  77161. }
  77162. }
  77163. // Animation Groups
  77164. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  77165. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  77166. var parsedAnimationGroup = parsedData.animationGroups[index];
  77167. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  77168. container.animationGroups.push(animationGroup);
  77169. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  77170. log += "\n\t\t" + animationGroup.toString(fullDetails);
  77171. }
  77172. }
  77173. // Browsing all the graph to connect the dots
  77174. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  77175. var camera = scene.cameras[index];
  77176. if (camera._waitingParentId) {
  77177. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  77178. camera._waitingParentId = null;
  77179. }
  77180. }
  77181. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  77182. var light_1 = scene.lights[index];
  77183. if (light_1 && light_1._waitingParentId) {
  77184. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  77185. light_1._waitingParentId = null;
  77186. }
  77187. }
  77188. // Connect parents & children and parse actions
  77189. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  77190. var transformNode = scene.transformNodes[index];
  77191. if (transformNode._waitingParentId) {
  77192. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  77193. transformNode._waitingParentId = null;
  77194. }
  77195. }
  77196. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77197. var mesh = scene.meshes[index];
  77198. if (mesh._waitingParentId) {
  77199. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  77200. mesh._waitingParentId = null;
  77201. }
  77202. }
  77203. // freeze world matrix application
  77204. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77205. var currentMesh = scene.meshes[index];
  77206. if (currentMesh._waitingFreezeWorldMatrix) {
  77207. currentMesh.freezeWorldMatrix();
  77208. currentMesh._waitingFreezeWorldMatrix = null;
  77209. }
  77210. else {
  77211. currentMesh.computeWorldMatrix(true);
  77212. }
  77213. }
  77214. // Lights exclusions / inclusions
  77215. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  77216. var light_2 = scene.lights[index];
  77217. // Excluded check
  77218. if (light_2._excludedMeshesIds.length > 0) {
  77219. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  77220. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  77221. if (excludedMesh) {
  77222. light_2.excludedMeshes.push(excludedMesh);
  77223. }
  77224. }
  77225. light_2._excludedMeshesIds = [];
  77226. }
  77227. // Included check
  77228. if (light_2._includedOnlyMeshesIds.length > 0) {
  77229. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  77230. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  77231. if (includedOnlyMesh) {
  77232. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  77233. }
  77234. }
  77235. light_2._includedOnlyMeshesIds = [];
  77236. }
  77237. }
  77238. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  77239. // Actions (scene) Done last as it can access other objects.
  77240. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77241. var mesh = scene.meshes[index];
  77242. if (mesh._waitingActions) {
  77243. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  77244. mesh._waitingActions = null;
  77245. }
  77246. }
  77247. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  77248. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  77249. }
  77250. if (!addToScene) {
  77251. container.removeAllFromScene();
  77252. }
  77253. }
  77254. catch (err) {
  77255. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  77256. if (onError) {
  77257. onError(msg, err);
  77258. }
  77259. else {
  77260. BABYLON.Tools.Log(msg);
  77261. throw err;
  77262. }
  77263. }
  77264. finally {
  77265. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  77266. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  77267. }
  77268. }
  77269. return container;
  77270. };
  77271. BABYLON.SceneLoader.RegisterPlugin({
  77272. name: "babylon.js",
  77273. extensions: ".babylon",
  77274. canDirectLoad: function (data) {
  77275. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  77276. return true;
  77277. }
  77278. return false;
  77279. },
  77280. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  77281. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  77282. // when SceneLoader.debugLogging = true (default), or exception encountered.
  77283. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  77284. // and avoid problems with multiple concurrent .babylon loads.
  77285. var log = "importMesh has failed JSON parse";
  77286. try {
  77287. var parsedData = JSON.parse(data);
  77288. log = "";
  77289. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  77290. if (!meshesNames) {
  77291. meshesNames = null;
  77292. }
  77293. else if (!Array.isArray(meshesNames)) {
  77294. meshesNames = [meshesNames];
  77295. }
  77296. var hierarchyIds = new Array();
  77297. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  77298. var loadedSkeletonsIds = [];
  77299. var loadedMaterialsIds = [];
  77300. var index;
  77301. var cache;
  77302. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  77303. var parsedMesh = parsedData.meshes[index];
  77304. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  77305. if (meshesNames !== null) {
  77306. // Remove found mesh name from list.
  77307. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  77308. }
  77309. //Geometry?
  77310. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  77311. //does the file contain geometries?
  77312. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  77313. //find the correct geometry and add it to the scene
  77314. var found = false;
  77315. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  77316. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  77317. return;
  77318. }
  77319. else {
  77320. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  77321. if (parsedGeometryData.id === parsedMesh.geometryId) {
  77322. switch (geometryType) {
  77323. case "boxes":
  77324. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  77325. break;
  77326. case "spheres":
  77327. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  77328. break;
  77329. case "cylinders":
  77330. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  77331. break;
  77332. case "toruses":
  77333. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  77334. break;
  77335. case "grounds":
  77336. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  77337. break;
  77338. case "planes":
  77339. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  77340. break;
  77341. case "torusKnots":
  77342. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  77343. break;
  77344. case "vertexData":
  77345. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  77346. break;
  77347. }
  77348. found = true;
  77349. }
  77350. });
  77351. }
  77352. });
  77353. if (found === false) {
  77354. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  77355. }
  77356. }
  77357. }
  77358. // Material ?
  77359. if (parsedMesh.materialId) {
  77360. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  77361. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  77362. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  77363. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  77364. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  77365. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  77366. var subMatId = parsedMultiMaterial.materials[matIndex];
  77367. loadedMaterialsIds.push(subMatId);
  77368. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  77369. if (mat) {
  77370. log += "\n\tMaterial " + mat.toString(fullDetails);
  77371. }
  77372. }
  77373. loadedMaterialsIds.push(parsedMultiMaterial.id);
  77374. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  77375. if (mmat) {
  77376. materialFound = true;
  77377. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  77378. }
  77379. break;
  77380. }
  77381. }
  77382. }
  77383. if (materialFound === false) {
  77384. loadedMaterialsIds.push(parsedMesh.materialId);
  77385. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  77386. if (!mat) {
  77387. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  77388. }
  77389. else {
  77390. log += "\n\tMaterial " + mat.toString(fullDetails);
  77391. }
  77392. }
  77393. }
  77394. // Skeleton ?
  77395. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  77396. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  77397. if (skeletonAlreadyLoaded === false) {
  77398. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  77399. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  77400. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  77401. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  77402. skeletons.push(skeleton);
  77403. loadedSkeletonsIds.push(parsedSkeleton.id);
  77404. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  77405. }
  77406. }
  77407. }
  77408. }
  77409. // Morph targets ?
  77410. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  77411. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  77412. var managerData = _a[_i];
  77413. BABYLON.MorphTargetManager.Parse(managerData, scene);
  77414. }
  77415. }
  77416. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  77417. meshes.push(mesh);
  77418. log += "\n\tMesh " + mesh.toString(fullDetails);
  77419. }
  77420. }
  77421. // Connecting parents
  77422. var currentMesh;
  77423. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77424. currentMesh = scene.meshes[index];
  77425. if (currentMesh._waitingParentId) {
  77426. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  77427. currentMesh._waitingParentId = null;
  77428. }
  77429. }
  77430. // freeze and compute world matrix application
  77431. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77432. currentMesh = scene.meshes[index];
  77433. if (currentMesh._waitingFreezeWorldMatrix) {
  77434. currentMesh.freezeWorldMatrix();
  77435. currentMesh._waitingFreezeWorldMatrix = null;
  77436. }
  77437. else {
  77438. currentMesh.computeWorldMatrix(true);
  77439. }
  77440. }
  77441. }
  77442. // Particles
  77443. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  77444. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  77445. if (parser) {
  77446. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  77447. var parsedParticleSystem = parsedData.particleSystems[index];
  77448. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  77449. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  77450. }
  77451. }
  77452. }
  77453. }
  77454. return true;
  77455. }
  77456. catch (err) {
  77457. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  77458. if (onError) {
  77459. onError(msg, err);
  77460. }
  77461. else {
  77462. BABYLON.Tools.Log(msg);
  77463. throw err;
  77464. }
  77465. }
  77466. finally {
  77467. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  77468. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  77469. }
  77470. }
  77471. return false;
  77472. },
  77473. load: function (scene, data, rootUrl, onError) {
  77474. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  77475. // when SceneLoader.debugLogging = true (default), or exception encountered.
  77476. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  77477. // and avoid problems with multiple concurrent .babylon loads.
  77478. var log = "importScene has failed JSON parse";
  77479. try {
  77480. var parsedData = JSON.parse(data);
  77481. log = "";
  77482. // Scene
  77483. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  77484. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  77485. }
  77486. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  77487. scene.autoClear = parsedData.autoClear;
  77488. }
  77489. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  77490. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  77491. }
  77492. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  77493. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  77494. }
  77495. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  77496. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  77497. }
  77498. // Fog
  77499. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  77500. scene.fogMode = parsedData.fogMode;
  77501. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  77502. scene.fogStart = parsedData.fogStart;
  77503. scene.fogEnd = parsedData.fogEnd;
  77504. scene.fogDensity = parsedData.fogDensity;
  77505. log += "\tFog mode for scene: ";
  77506. switch (scene.fogMode) {
  77507. // getters not compiling, so using hardcoded
  77508. case 1:
  77509. log += "exp\n";
  77510. break;
  77511. case 2:
  77512. log += "exp2\n";
  77513. break;
  77514. case 3:
  77515. log += "linear\n";
  77516. break;
  77517. }
  77518. }
  77519. //Physics
  77520. if (parsedData.physicsEnabled) {
  77521. var physicsPlugin;
  77522. if (parsedData.physicsEngine === "cannon") {
  77523. physicsPlugin = new BABYLON.CannonJSPlugin();
  77524. }
  77525. else if (parsedData.physicsEngine === "oimo") {
  77526. physicsPlugin = new BABYLON.OimoJSPlugin();
  77527. }
  77528. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  77529. //else - default engine, which is currently oimo
  77530. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  77531. scene.enablePhysics(physicsGravity, physicsPlugin);
  77532. }
  77533. // Metadata
  77534. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  77535. scene.metadata = parsedData.metadata;
  77536. }
  77537. //collisions, if defined. otherwise, default is true
  77538. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  77539. scene.collisionsEnabled = parsedData.collisionsEnabled;
  77540. }
  77541. scene.workerCollisions = !!parsedData.workerCollisions;
  77542. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  77543. if (!container) {
  77544. return false;
  77545. }
  77546. if (parsedData.autoAnimate) {
  77547. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  77548. }
  77549. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  77550. scene.setActiveCameraByID(parsedData.activeCameraID);
  77551. }
  77552. // Environment texture
  77553. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  77554. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  77555. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  77556. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  77557. if (parsedData.environmentTextureRotationY) {
  77558. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  77559. }
  77560. scene.environmentTexture = hdrTexture;
  77561. }
  77562. else {
  77563. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  77564. if (parsedData.environmentTextureRotationY) {
  77565. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  77566. }
  77567. scene.environmentTexture = cubeTexture;
  77568. }
  77569. if (parsedData.createDefaultSkybox === true) {
  77570. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  77571. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  77572. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  77573. }
  77574. }
  77575. // Finish
  77576. return true;
  77577. }
  77578. catch (err) {
  77579. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  77580. if (onError) {
  77581. onError(msg, err);
  77582. }
  77583. else {
  77584. BABYLON.Tools.Log(msg);
  77585. throw err;
  77586. }
  77587. }
  77588. finally {
  77589. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  77590. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  77591. }
  77592. }
  77593. return false;
  77594. },
  77595. loadAssetContainer: function (scene, data, rootUrl, onError) {
  77596. var container = loadAssetContainer(scene, data, rootUrl, onError);
  77597. return container;
  77598. }
  77599. });
  77600. })(BABYLON || (BABYLON = {}));
  77601. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  77602. var BABYLON;
  77603. (function (BABYLON) {
  77604. /**
  77605. * Class used to help managing file picking and drag'n'drop
  77606. */
  77607. var FilesInput = /** @class */ (function () {
  77608. /**
  77609. * Creates a new FilesInput
  77610. * @param engine defines the rendering engine
  77611. * @param scene defines the hosting scene
  77612. * @param sceneLoadedCallback callback called when scene is loaded
  77613. * @param progressCallback callback called to track progress
  77614. * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop
  77615. * @param textureLoadingCallback callback called when a texture is loading
  77616. * @param startingProcessingFilesCallback callback called when the system is about to process all files
  77617. * @param onReloadCallback callback called when a reload is requested
  77618. * @param errorCallback callback call if an error occurs
  77619. */
  77620. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  77621. /**
  77622. * Callback called when a file is processed
  77623. */
  77624. this.onProcessFileCallback = function () { return true; };
  77625. this._engine = engine;
  77626. this._currentScene = scene;
  77627. this._sceneLoadedCallback = sceneLoadedCallback;
  77628. this._progressCallback = progressCallback;
  77629. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  77630. this._textureLoadingCallback = textureLoadingCallback;
  77631. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  77632. this._onReloadCallback = onReloadCallback;
  77633. this._errorCallback = errorCallback;
  77634. }
  77635. /**
  77636. * Calls this function to listen to drag'n'drop events on a specific DOM element
  77637. * @param elementToMonitor defines the DOM element to track
  77638. */
  77639. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  77640. var _this = this;
  77641. if (elementToMonitor) {
  77642. this._elementToMonitor = elementToMonitor;
  77643. this._dragEnterHandler = function (e) { _this.drag(e); };
  77644. this._dragOverHandler = function (e) { _this.drag(e); };
  77645. this._dropHandler = function (e) { _this.drop(e); };
  77646. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  77647. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  77648. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  77649. }
  77650. };
  77651. /**
  77652. * Release all associated resources
  77653. */
  77654. FilesInput.prototype.dispose = function () {
  77655. if (!this._elementToMonitor) {
  77656. return;
  77657. }
  77658. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  77659. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  77660. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  77661. };
  77662. FilesInput.prototype.renderFunction = function () {
  77663. if (this._additionalRenderLoopLogicCallback) {
  77664. this._additionalRenderLoopLogicCallback();
  77665. }
  77666. if (this._currentScene) {
  77667. if (this._textureLoadingCallback) {
  77668. var remaining = this._currentScene.getWaitingItemsCount();
  77669. if (remaining > 0) {
  77670. this._textureLoadingCallback(remaining);
  77671. }
  77672. }
  77673. this._currentScene.render();
  77674. }
  77675. };
  77676. FilesInput.prototype.drag = function (e) {
  77677. e.stopPropagation();
  77678. e.preventDefault();
  77679. };
  77680. FilesInput.prototype.drop = function (eventDrop) {
  77681. eventDrop.stopPropagation();
  77682. eventDrop.preventDefault();
  77683. this.loadFiles(eventDrop);
  77684. };
  77685. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  77686. var _this = this;
  77687. var reader = folder.createReader();
  77688. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  77689. reader.readEntries(function (entries) {
  77690. remaining.count += entries.length;
  77691. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  77692. var entry = entries_1[_i];
  77693. if (entry.isFile) {
  77694. entry.file(function (file) {
  77695. file.correctName = relativePath + file.name;
  77696. files.push(file);
  77697. if (--remaining.count === 0) {
  77698. callback();
  77699. }
  77700. });
  77701. }
  77702. else if (entry.isDirectory) {
  77703. _this._traverseFolder(entry, files, remaining, callback);
  77704. }
  77705. }
  77706. if (--remaining.count) {
  77707. callback();
  77708. }
  77709. });
  77710. };
  77711. FilesInput.prototype._processFiles = function (files) {
  77712. for (var i = 0; i < files.length; i++) {
  77713. var name = files[i].correctName.toLowerCase();
  77714. var extension = name.split('.').pop();
  77715. if (!this.onProcessFileCallback(files[i], name, extension)) {
  77716. continue;
  77717. }
  77718. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  77719. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  77720. this._sceneFileToLoad = files[i];
  77721. }
  77722. FilesInput.FilesToLoad[name] = files[i];
  77723. }
  77724. };
  77725. /**
  77726. * Load files from a drop event
  77727. * @param event defines the drop event to use as source
  77728. */
  77729. FilesInput.prototype.loadFiles = function (event) {
  77730. var _this = this;
  77731. // Handling data transfer via drag'n'drop
  77732. if (event && event.dataTransfer && event.dataTransfer.files) {
  77733. this._filesToLoad = event.dataTransfer.files;
  77734. }
  77735. // Handling files from input files
  77736. if (event && event.target && event.target.files) {
  77737. this._filesToLoad = event.target.files;
  77738. }
  77739. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  77740. return;
  77741. }
  77742. if (this._startingProcessingFilesCallback) {
  77743. this._startingProcessingFilesCallback(this._filesToLoad);
  77744. }
  77745. if (this._filesToLoad && this._filesToLoad.length > 0) {
  77746. var files_1 = new Array();
  77747. var folders = [];
  77748. var items = event.dataTransfer ? event.dataTransfer.items : null;
  77749. for (var i = 0; i < this._filesToLoad.length; i++) {
  77750. var fileToLoad = this._filesToLoad[i];
  77751. var name_1 = fileToLoad.name.toLowerCase();
  77752. var entry = void 0;
  77753. fileToLoad.correctName = name_1;
  77754. if (items) {
  77755. var item = items[i];
  77756. if (item.getAsEntry) {
  77757. entry = item.getAsEntry();
  77758. }
  77759. else if (item.webkitGetAsEntry) {
  77760. entry = item.webkitGetAsEntry();
  77761. }
  77762. }
  77763. if (!entry) {
  77764. files_1.push(fileToLoad);
  77765. }
  77766. else {
  77767. if (entry.isDirectory) {
  77768. folders.push(entry);
  77769. }
  77770. else {
  77771. files_1.push(fileToLoad);
  77772. }
  77773. }
  77774. }
  77775. if (folders.length === 0) {
  77776. this._processFiles(files_1);
  77777. this._processReload();
  77778. }
  77779. else {
  77780. var remaining = { count: folders.length };
  77781. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  77782. var folder = folders_1[_i];
  77783. this._traverseFolder(folder, files_1, remaining, function () {
  77784. _this._processFiles(files_1);
  77785. if (remaining.count === 0) {
  77786. _this._processReload();
  77787. }
  77788. });
  77789. }
  77790. }
  77791. }
  77792. };
  77793. FilesInput.prototype._processReload = function () {
  77794. if (this._onReloadCallback) {
  77795. this._onReloadCallback(this._sceneFileToLoad);
  77796. }
  77797. else {
  77798. this.reload();
  77799. }
  77800. };
  77801. /**
  77802. * Reload the current scene from the loaded files
  77803. */
  77804. FilesInput.prototype.reload = function () {
  77805. var _this = this;
  77806. // If a scene file has been provided
  77807. if (this._sceneFileToLoad) {
  77808. if (this._currentScene) {
  77809. if (BABYLON.Tools.errorsCount > 0) {
  77810. BABYLON.Tools.ClearLogCache();
  77811. }
  77812. this._engine.stopRenderLoop();
  77813. }
  77814. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  77815. if (_this._progressCallback) {
  77816. _this._progressCallback(progress);
  77817. }
  77818. }).then(function (scene) {
  77819. if (_this._currentScene) {
  77820. _this._currentScene.dispose();
  77821. }
  77822. _this._currentScene = scene;
  77823. if (_this._sceneLoadedCallback) {
  77824. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  77825. }
  77826. // Wait for textures and shaders to be ready
  77827. _this._currentScene.executeWhenReady(function () {
  77828. _this._engine.runRenderLoop(function () {
  77829. _this.renderFunction();
  77830. });
  77831. });
  77832. }).catch(function (error) {
  77833. if (_this._errorCallback) {
  77834. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  77835. }
  77836. });
  77837. }
  77838. else {
  77839. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  77840. }
  77841. };
  77842. /**
  77843. * List of files ready to be loaded
  77844. */
  77845. FilesInput.FilesToLoad = {};
  77846. return FilesInput;
  77847. }());
  77848. BABYLON.FilesInput = FilesInput;
  77849. })(BABYLON || (BABYLON = {}));
  77850. //# sourceMappingURL=babylon.filesInput.js.map
  77851. var BABYLON;
  77852. (function (BABYLON) {
  77853. /**
  77854. * Class used to store custom tags
  77855. */
  77856. var Tags = /** @class */ (function () {
  77857. function Tags() {
  77858. }
  77859. /**
  77860. * Adds support for tags on the given object
  77861. * @param obj defines the object to use
  77862. */
  77863. Tags.EnableFor = function (obj) {
  77864. obj._tags = obj._tags || {};
  77865. obj.hasTags = function () {
  77866. return Tags.HasTags(obj);
  77867. };
  77868. obj.addTags = function (tagsString) {
  77869. return Tags.AddTagsTo(obj, tagsString);
  77870. };
  77871. obj.removeTags = function (tagsString) {
  77872. return Tags.RemoveTagsFrom(obj, tagsString);
  77873. };
  77874. obj.matchesTagsQuery = function (tagsQuery) {
  77875. return Tags.MatchesQuery(obj, tagsQuery);
  77876. };
  77877. };
  77878. /**
  77879. * Removes tags support
  77880. * @param obj defines the object to use
  77881. */
  77882. Tags.DisableFor = function (obj) {
  77883. delete obj._tags;
  77884. delete obj.hasTags;
  77885. delete obj.addTags;
  77886. delete obj.removeTags;
  77887. delete obj.matchesTagsQuery;
  77888. };
  77889. /**
  77890. * Gets a boolean indicating if the given object has tags
  77891. * @param obj defines the object to use
  77892. * @returns a boolean
  77893. */
  77894. Tags.HasTags = function (obj) {
  77895. if (!obj._tags) {
  77896. return false;
  77897. }
  77898. return !BABYLON.Tools.IsEmpty(obj._tags);
  77899. };
  77900. /**
  77901. * Gets the tags available on a given object
  77902. * @param obj defines the object to use
  77903. * @param asString defines if the tags must be returned as a string instead of an array of strings
  77904. * @returns the tags
  77905. */
  77906. Tags.GetTags = function (obj, asString) {
  77907. if (asString === void 0) { asString = true; }
  77908. if (!obj._tags) {
  77909. return null;
  77910. }
  77911. if (asString) {
  77912. var tagsArray = [];
  77913. for (var tag in obj._tags) {
  77914. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  77915. tagsArray.push(tag);
  77916. }
  77917. }
  77918. return tagsArray.join(" ");
  77919. }
  77920. else {
  77921. return obj._tags;
  77922. }
  77923. };
  77924. /**
  77925. * Adds tags to an object
  77926. * @param obj defines the object to use
  77927. * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.
  77928. * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces
  77929. */
  77930. Tags.AddTagsTo = function (obj, tagsString) {
  77931. if (!tagsString) {
  77932. return;
  77933. }
  77934. if (typeof tagsString !== "string") {
  77935. return;
  77936. }
  77937. var tags = tagsString.split(" ");
  77938. tags.forEach(function (tag, index, array) {
  77939. Tags._AddTagTo(obj, tag);
  77940. });
  77941. };
  77942. /**
  77943. * @hidden
  77944. */
  77945. Tags._AddTagTo = function (obj, tag) {
  77946. tag = tag.trim();
  77947. if (tag === "" || tag === "true" || tag === "false") {
  77948. return;
  77949. }
  77950. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  77951. return;
  77952. }
  77953. Tags.EnableFor(obj);
  77954. obj._tags[tag] = true;
  77955. };
  77956. /**
  77957. * Removes specific tags from a specific object
  77958. * @param obj defines the object to use
  77959. * @param tagsString defines the tags to remove
  77960. */
  77961. Tags.RemoveTagsFrom = function (obj, tagsString) {
  77962. if (!Tags.HasTags(obj)) {
  77963. return;
  77964. }
  77965. var tags = tagsString.split(" ");
  77966. for (var t in tags) {
  77967. Tags._RemoveTagFrom(obj, tags[t]);
  77968. }
  77969. };
  77970. /**
  77971. * @hidden
  77972. */
  77973. Tags._RemoveTagFrom = function (obj, tag) {
  77974. delete obj._tags[tag];
  77975. };
  77976. /**
  77977. * Defines if tags hosted on an object match a given query
  77978. * @param obj defines the object to use
  77979. * @param tagsQuery defines the tag query
  77980. * @returns a boolean
  77981. */
  77982. Tags.MatchesQuery = function (obj, tagsQuery) {
  77983. if (tagsQuery === undefined) {
  77984. return true;
  77985. }
  77986. if (tagsQuery === "") {
  77987. return Tags.HasTags(obj);
  77988. }
  77989. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  77990. };
  77991. return Tags;
  77992. }());
  77993. BABYLON.Tags = Tags;
  77994. })(BABYLON || (BABYLON = {}));
  77995. //# sourceMappingURL=babylon.tags.js.map
  77996. var BABYLON;
  77997. (function (BABYLON) {
  77998. /**
  77999. * Class used to evalaute queries containing `and` and `or` operators
  78000. */
  78001. var AndOrNotEvaluator = /** @class */ (function () {
  78002. function AndOrNotEvaluator() {
  78003. }
  78004. /**
  78005. * Evaluate a query
  78006. * @param query defines the query to evaluate
  78007. * @param evaluateCallback defines the callback used to filter result
  78008. * @returns true if the query matches
  78009. */
  78010. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  78011. if (!query.match(/\([^\(\)]*\)/g)) {
  78012. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  78013. }
  78014. else {
  78015. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  78016. // remove parenthesis
  78017. r = r.slice(1, r.length - 1);
  78018. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  78019. });
  78020. }
  78021. if (query === "true") {
  78022. return true;
  78023. }
  78024. if (query === "false") {
  78025. return false;
  78026. }
  78027. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  78028. };
  78029. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  78030. evaluateCallback = evaluateCallback || (function (r) {
  78031. return r === "true" ? true : false;
  78032. });
  78033. var result;
  78034. var or = parenthesisContent.split("||");
  78035. for (var i in or) {
  78036. if (or.hasOwnProperty(i)) {
  78037. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  78038. var and = ori.split("&&");
  78039. if (and.length > 1) {
  78040. for (var j = 0; j < and.length; ++j) {
  78041. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  78042. if (andj !== "true" && andj !== "false") {
  78043. if (andj[0] === "!") {
  78044. result = !evaluateCallback(andj.substring(1));
  78045. }
  78046. else {
  78047. result = evaluateCallback(andj);
  78048. }
  78049. }
  78050. else {
  78051. result = andj === "true" ? true : false;
  78052. }
  78053. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  78054. ori = "false";
  78055. break;
  78056. }
  78057. }
  78058. }
  78059. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  78060. result = true;
  78061. break;
  78062. }
  78063. // result equals false (or undefined)
  78064. if (ori !== "true" && ori !== "false") {
  78065. if (ori[0] === "!") {
  78066. result = !evaluateCallback(ori.substring(1));
  78067. }
  78068. else {
  78069. result = evaluateCallback(ori);
  78070. }
  78071. }
  78072. else {
  78073. result = ori === "true" ? true : false;
  78074. }
  78075. }
  78076. }
  78077. // the whole parenthesis scope is replaced by 'true' or 'false'
  78078. return result ? "true" : "false";
  78079. };
  78080. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  78081. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  78082. // remove whitespaces
  78083. r = r.replace(/[\s]/g, function () { return ""; });
  78084. return r.length % 2 ? "!" : "";
  78085. });
  78086. booleanString = booleanString.trim();
  78087. if (booleanString === "!true") {
  78088. booleanString = "false";
  78089. }
  78090. else if (booleanString === "!false") {
  78091. booleanString = "true";
  78092. }
  78093. return booleanString;
  78094. };
  78095. return AndOrNotEvaluator;
  78096. }());
  78097. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  78098. })(BABYLON || (BABYLON = {}));
  78099. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  78100. var BABYLON;
  78101. (function (BABYLON) {
  78102. /**
  78103. * Class used to enable access to IndexedDB
  78104. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  78105. */
  78106. var Database = /** @class */ (function () {
  78107. /**
  78108. * Creates a new Database
  78109. * @param urlToScene defines the url to load the scene
  78110. * @param callbackManifestChecked defines the callback to use when manifest is checked
  78111. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  78112. */
  78113. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  78114. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  78115. var _this = this;
  78116. // Handling various flavors of prefixed version of IndexedDB
  78117. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  78118. this.callbackManifestChecked = callbackManifestChecked;
  78119. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  78120. this.db = null;
  78121. this._enableSceneOffline = false;
  78122. this._enableTexturesOffline = false;
  78123. this.manifestVersionFound = 0;
  78124. this.mustUpdateRessources = false;
  78125. this.hasReachedQuota = false;
  78126. if (!Database.IDBStorageEnabled) {
  78127. this.callbackManifestChecked(true);
  78128. }
  78129. else {
  78130. if (disableManifestCheck) {
  78131. this._enableSceneOffline = true;
  78132. this._enableTexturesOffline = true;
  78133. this.manifestVersionFound = 1;
  78134. BABYLON.Tools.SetImmediate(function () {
  78135. _this.callbackManifestChecked(true);
  78136. });
  78137. }
  78138. else {
  78139. this._checkManifestFile();
  78140. }
  78141. }
  78142. }
  78143. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  78144. /**
  78145. * Gets a boolean indicating if scene must be saved in the database
  78146. */
  78147. get: function () {
  78148. return this._enableSceneOffline;
  78149. },
  78150. enumerable: true,
  78151. configurable: true
  78152. });
  78153. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  78154. /**
  78155. * Gets a boolean indicating if textures must be saved in the database
  78156. */
  78157. get: function () {
  78158. return this._enableTexturesOffline;
  78159. },
  78160. enumerable: true,
  78161. configurable: true
  78162. });
  78163. Database.prototype._checkManifestFile = function () {
  78164. var _this = this;
  78165. var noManifestFile = function () {
  78166. _this._enableSceneOffline = false;
  78167. _this._enableTexturesOffline = false;
  78168. _this.callbackManifestChecked(false);
  78169. };
  78170. var timeStampUsed = false;
  78171. var manifestURL = this.currentSceneUrl + ".manifest";
  78172. var xhr = new XMLHttpRequest();
  78173. if (navigator.onLine) {
  78174. // Adding a timestamp to by-pass browsers' cache
  78175. timeStampUsed = true;
  78176. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  78177. }
  78178. xhr.open("GET", manifestURL, true);
  78179. xhr.addEventListener("load", function () {
  78180. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  78181. try {
  78182. var manifestFile = JSON.parse(xhr.response);
  78183. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  78184. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  78185. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  78186. _this.manifestVersionFound = manifestFile.version;
  78187. }
  78188. if (_this.callbackManifestChecked) {
  78189. _this.callbackManifestChecked(true);
  78190. }
  78191. }
  78192. catch (ex) {
  78193. noManifestFile();
  78194. }
  78195. }
  78196. else {
  78197. noManifestFile();
  78198. }
  78199. }, false);
  78200. xhr.addEventListener("error", function (event) {
  78201. if (timeStampUsed) {
  78202. timeStampUsed = false;
  78203. // Let's retry without the timeStamp
  78204. // It could fail when coupled with HTML5 Offline API
  78205. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  78206. xhr.open("GET", retryManifestURL, true);
  78207. xhr.send();
  78208. }
  78209. else {
  78210. noManifestFile();
  78211. }
  78212. }, false);
  78213. try {
  78214. xhr.send();
  78215. }
  78216. catch (ex) {
  78217. BABYLON.Tools.Error("Error on XHR send request.");
  78218. this.callbackManifestChecked(false);
  78219. }
  78220. };
  78221. /**
  78222. * Open the database and make it available
  78223. * @param successCallback defines the callback to call on success
  78224. * @param errorCallback defines the callback to call on error
  78225. */
  78226. Database.prototype.openAsync = function (successCallback, errorCallback) {
  78227. var _this = this;
  78228. var handleError = function () {
  78229. _this.isSupported = false;
  78230. if (errorCallback) {
  78231. errorCallback();
  78232. }
  78233. };
  78234. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  78235. // Your browser doesn't support IndexedDB
  78236. this.isSupported = false;
  78237. if (errorCallback) {
  78238. errorCallback();
  78239. }
  78240. }
  78241. else {
  78242. // If the DB hasn't been opened or created yet
  78243. if (!this.db) {
  78244. this.hasReachedQuota = false;
  78245. this.isSupported = true;
  78246. var request = this.idbFactory.open("babylonjs", 1);
  78247. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  78248. request.onerror = function (event) {
  78249. handleError();
  78250. };
  78251. // executes when a version change transaction cannot complete due to other active transactions
  78252. request.onblocked = function (event) {
  78253. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  78254. handleError();
  78255. };
  78256. // DB has been opened successfully
  78257. request.onsuccess = function (event) {
  78258. _this.db = request.result;
  78259. successCallback();
  78260. };
  78261. // Initialization of the DB. Creating Scenes & Textures stores
  78262. request.onupgradeneeded = function (event) {
  78263. _this.db = (event.target).result;
  78264. if (_this.db) {
  78265. try {
  78266. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  78267. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  78268. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  78269. }
  78270. catch (ex) {
  78271. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  78272. handleError();
  78273. }
  78274. }
  78275. };
  78276. }
  78277. // DB has already been created and opened
  78278. else {
  78279. if (successCallback) {
  78280. successCallback();
  78281. }
  78282. }
  78283. }
  78284. };
  78285. /**
  78286. * Loads an image from the database
  78287. * @param url defines the url to load from
  78288. * @param image defines the target DOM image
  78289. */
  78290. Database.prototype.loadImageFromDB = function (url, image) {
  78291. var _this = this;
  78292. var completeURL = Database._ReturnFullUrlLocation(url);
  78293. var saveAndLoadImage = function () {
  78294. if (!_this.hasReachedQuota && _this.db !== null) {
  78295. // the texture is not yet in the DB, let's try to save it
  78296. _this._saveImageIntoDBAsync(completeURL, image);
  78297. }
  78298. // If the texture is not in the DB and we've reached the DB quota limit
  78299. // let's load it directly from the web
  78300. else {
  78301. image.src = url;
  78302. }
  78303. };
  78304. if (!this.mustUpdateRessources) {
  78305. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  78306. }
  78307. // First time we're download the images or update requested in the manifest file by a version change
  78308. else {
  78309. saveAndLoadImage();
  78310. }
  78311. };
  78312. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  78313. if (this.isSupported && this.db !== null) {
  78314. var texture;
  78315. var transaction = this.db.transaction(["textures"]);
  78316. transaction.onabort = function (event) {
  78317. image.src = url;
  78318. };
  78319. transaction.oncomplete = function (event) {
  78320. var blobTextureURL;
  78321. if (texture) {
  78322. var URL = window.URL || window.webkitURL;
  78323. blobTextureURL = URL.createObjectURL(texture.data);
  78324. image.onerror = function () {
  78325. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  78326. image.src = url;
  78327. };
  78328. image.src = blobTextureURL;
  78329. }
  78330. else {
  78331. notInDBCallback();
  78332. }
  78333. };
  78334. var getRequest = transaction.objectStore("textures").get(url);
  78335. getRequest.onsuccess = function (event) {
  78336. texture = (event.target).result;
  78337. };
  78338. getRequest.onerror = function (event) {
  78339. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  78340. image.src = url;
  78341. };
  78342. }
  78343. else {
  78344. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78345. image.src = url;
  78346. }
  78347. };
  78348. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  78349. var _this = this;
  78350. if (this.isSupported) {
  78351. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  78352. var generateBlobUrl = function () {
  78353. var blobTextureURL;
  78354. if (blob) {
  78355. var URL = window.URL || window.webkitURL;
  78356. try {
  78357. blobTextureURL = URL.createObjectURL(blob);
  78358. }
  78359. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  78360. catch (ex) {
  78361. blobTextureURL = URL.createObjectURL(blob);
  78362. }
  78363. }
  78364. if (blobTextureURL) {
  78365. image.src = blobTextureURL;
  78366. }
  78367. };
  78368. if (Database.IsUASupportingBlobStorage) { // Create XHR
  78369. var xhr = new XMLHttpRequest(), blob;
  78370. xhr.open("GET", url, true);
  78371. xhr.responseType = "blob";
  78372. xhr.addEventListener("load", function () {
  78373. if (xhr.status === 200 && _this.db) {
  78374. // Blob as response (XHR2)
  78375. blob = xhr.response;
  78376. var transaction = _this.db.transaction(["textures"], "readwrite");
  78377. // the transaction could abort because of a QuotaExceededError error
  78378. transaction.onabort = function (event) {
  78379. try {
  78380. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  78381. var srcElement = (event.srcElement || event.target);
  78382. var error = srcElement.error;
  78383. if (error && error.name === "QuotaExceededError") {
  78384. _this.hasReachedQuota = true;
  78385. }
  78386. }
  78387. catch (ex) { }
  78388. generateBlobUrl();
  78389. };
  78390. transaction.oncomplete = function (event) {
  78391. generateBlobUrl();
  78392. };
  78393. var newTexture = { textureUrl: url, data: blob };
  78394. try {
  78395. // Put the blob into the dabase
  78396. var addRequest = transaction.objectStore("textures").put(newTexture);
  78397. addRequest.onsuccess = function (event) {
  78398. };
  78399. addRequest.onerror = function (event) {
  78400. generateBlobUrl();
  78401. };
  78402. }
  78403. catch (ex) {
  78404. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  78405. if (ex.code === 25) {
  78406. Database.IsUASupportingBlobStorage = false;
  78407. }
  78408. image.src = url;
  78409. }
  78410. }
  78411. else {
  78412. image.src = url;
  78413. }
  78414. }, false);
  78415. xhr.addEventListener("error", function (event) {
  78416. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  78417. image.src = url;
  78418. }, false);
  78419. xhr.send();
  78420. }
  78421. else {
  78422. image.src = url;
  78423. }
  78424. }
  78425. else {
  78426. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78427. image.src = url;
  78428. }
  78429. };
  78430. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  78431. var _this = this;
  78432. var updateVersion = function () {
  78433. // the version is not yet in the DB or we need to update it
  78434. _this._saveVersionIntoDBAsync(url, versionLoaded);
  78435. };
  78436. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  78437. };
  78438. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  78439. var _this = this;
  78440. if (this.isSupported && this.db) {
  78441. var version;
  78442. try {
  78443. var transaction = this.db.transaction(["versions"]);
  78444. transaction.oncomplete = function (event) {
  78445. if (version) {
  78446. // If the version in the JSON file is different from the version in DB
  78447. if (_this.manifestVersionFound !== version.data) {
  78448. _this.mustUpdateRessources = true;
  78449. updateInDBCallback();
  78450. }
  78451. else {
  78452. callback(version.data);
  78453. }
  78454. }
  78455. // version was not found in DB
  78456. else {
  78457. _this.mustUpdateRessources = true;
  78458. updateInDBCallback();
  78459. }
  78460. };
  78461. transaction.onabort = function (event) {
  78462. callback(-1);
  78463. };
  78464. var getRequest = transaction.objectStore("versions").get(url);
  78465. getRequest.onsuccess = function (event) {
  78466. version = (event.target).result;
  78467. };
  78468. getRequest.onerror = function (event) {
  78469. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  78470. callback(-1);
  78471. };
  78472. }
  78473. catch (ex) {
  78474. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  78475. callback(-1);
  78476. }
  78477. }
  78478. else {
  78479. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78480. callback(-1);
  78481. }
  78482. };
  78483. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  78484. var _this = this;
  78485. if (this.isSupported && !this.hasReachedQuota && this.db) {
  78486. try {
  78487. // Open a transaction to the database
  78488. var transaction = this.db.transaction(["versions"], "readwrite");
  78489. // the transaction could abort because of a QuotaExceededError error
  78490. transaction.onabort = function (event) {
  78491. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  78492. var error = event.srcElement['error'];
  78493. if (error && error.name === "QuotaExceededError") {
  78494. _this.hasReachedQuota = true;
  78495. }
  78496. }
  78497. catch (ex) { }
  78498. callback(-1);
  78499. };
  78500. transaction.oncomplete = function (event) {
  78501. callback(_this.manifestVersionFound);
  78502. };
  78503. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  78504. // Put the scene into the database
  78505. var addRequest = transaction.objectStore("versions").put(newVersion);
  78506. addRequest.onsuccess = function (event) {
  78507. };
  78508. addRequest.onerror = function (event) {
  78509. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  78510. };
  78511. }
  78512. catch (ex) {
  78513. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  78514. callback(-1);
  78515. }
  78516. }
  78517. else {
  78518. callback(-1);
  78519. }
  78520. };
  78521. /**
  78522. * Loads a file from database
  78523. * @param url defines the URL to load from
  78524. * @param sceneLoaded defines a callback to call on success
  78525. * @param progressCallBack defines a callback to call when progress changed
  78526. * @param errorCallback defines a callback to call on error
  78527. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  78528. */
  78529. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  78530. var _this = this;
  78531. var completeUrl = Database._ReturnFullUrlLocation(url);
  78532. var saveAndLoadFile = function () {
  78533. // the scene is not yet in the DB, let's try to save it
  78534. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  78535. };
  78536. this._checkVersionFromDB(completeUrl, function (version) {
  78537. if (version !== -1) {
  78538. if (!_this.mustUpdateRessources) {
  78539. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  78540. }
  78541. else {
  78542. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  78543. }
  78544. }
  78545. else {
  78546. if (errorCallback) {
  78547. errorCallback();
  78548. }
  78549. }
  78550. });
  78551. };
  78552. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  78553. if (this.isSupported && this.db) {
  78554. var targetStore;
  78555. if (url.indexOf(".babylon") !== -1) {
  78556. targetStore = "scenes";
  78557. }
  78558. else {
  78559. targetStore = "textures";
  78560. }
  78561. var file;
  78562. var transaction = this.db.transaction([targetStore]);
  78563. transaction.oncomplete = function (event) {
  78564. if (file) {
  78565. callback(file.data);
  78566. }
  78567. // file was not found in DB
  78568. else {
  78569. notInDBCallback();
  78570. }
  78571. };
  78572. transaction.onabort = function (event) {
  78573. notInDBCallback();
  78574. };
  78575. var getRequest = transaction.objectStore(targetStore).get(url);
  78576. getRequest.onsuccess = function (event) {
  78577. file = (event.target).result;
  78578. };
  78579. getRequest.onerror = function (event) {
  78580. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  78581. notInDBCallback();
  78582. };
  78583. }
  78584. else {
  78585. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78586. callback();
  78587. }
  78588. };
  78589. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  78590. var _this = this;
  78591. if (this.isSupported) {
  78592. var targetStore;
  78593. if (url.indexOf(".babylon") !== -1) {
  78594. targetStore = "scenes";
  78595. }
  78596. else {
  78597. targetStore = "textures";
  78598. }
  78599. // Create XHR
  78600. var xhr = new XMLHttpRequest();
  78601. var fileData;
  78602. xhr.open("GET", url + "?" + Date.now(), true);
  78603. if (useArrayBuffer) {
  78604. xhr.responseType = "arraybuffer";
  78605. }
  78606. if (progressCallback) {
  78607. xhr.onprogress = progressCallback;
  78608. }
  78609. xhr.addEventListener("load", function () {
  78610. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  78611. // Blob as response (XHR2)
  78612. //fileData = xhr.responseText;
  78613. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  78614. if (!_this.hasReachedQuota && _this.db) {
  78615. // Open a transaction to the database
  78616. var transaction = _this.db.transaction([targetStore], "readwrite");
  78617. // the transaction could abort because of a QuotaExceededError error
  78618. transaction.onabort = function (event) {
  78619. try {
  78620. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  78621. var error = event.srcElement['error'];
  78622. if (error && error.name === "QuotaExceededError") {
  78623. _this.hasReachedQuota = true;
  78624. }
  78625. }
  78626. catch (ex) { }
  78627. callback(fileData);
  78628. };
  78629. transaction.oncomplete = function (event) {
  78630. callback(fileData);
  78631. };
  78632. var newFile;
  78633. if (targetStore === "scenes") {
  78634. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  78635. }
  78636. else {
  78637. newFile = { textureUrl: url, data: fileData };
  78638. }
  78639. try {
  78640. // Put the scene into the database
  78641. var addRequest = transaction.objectStore(targetStore).put(newFile);
  78642. addRequest.onsuccess = function (event) {
  78643. };
  78644. addRequest.onerror = function (event) {
  78645. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  78646. };
  78647. }
  78648. catch (ex) {
  78649. callback(fileData);
  78650. }
  78651. }
  78652. else {
  78653. callback(fileData);
  78654. }
  78655. }
  78656. else {
  78657. if (xhr.status >= 400 && errorCallback) {
  78658. errorCallback(xhr);
  78659. }
  78660. else {
  78661. callback();
  78662. }
  78663. }
  78664. }, false);
  78665. xhr.addEventListener("error", function (event) {
  78666. BABYLON.Tools.Error("error on XHR request.");
  78667. callback();
  78668. }, false);
  78669. xhr.send();
  78670. }
  78671. else {
  78672. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78673. callback();
  78674. }
  78675. };
  78676. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  78677. Database.IsUASupportingBlobStorage = true;
  78678. /** Gets a boolean indicating if Database storate is enabled */
  78679. Database.IDBStorageEnabled = true;
  78680. Database._ParseURL = function (url) {
  78681. var a = document.createElement('a');
  78682. a.href = url;
  78683. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  78684. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  78685. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  78686. return absLocation;
  78687. };
  78688. Database._ReturnFullUrlLocation = function (url) {
  78689. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  78690. return (Database._ParseURL(window.location.href) + url);
  78691. }
  78692. else {
  78693. return url;
  78694. }
  78695. };
  78696. return Database;
  78697. }());
  78698. BABYLON.Database = Database;
  78699. })(BABYLON || (BABYLON = {}));
  78700. //# sourceMappingURL=babylon.database.js.map
  78701. var BABYLON;
  78702. (function (BABYLON) {
  78703. /**
  78704. * This represents all the required information to add a fresnel effect on a material:
  78705. * @see http://doc.babylonjs.com/how_to/how_to_use_fresnelparameters
  78706. */
  78707. var FresnelParameters = /** @class */ (function () {
  78708. function FresnelParameters() {
  78709. this._isEnabled = true;
  78710. /**
  78711. * Define the color used on edges (grazing angle)
  78712. */
  78713. this.leftColor = BABYLON.Color3.White();
  78714. /**
  78715. * Define the color used on center
  78716. */
  78717. this.rightColor = BABYLON.Color3.Black();
  78718. /**
  78719. * Define bias applied to computed fresnel term
  78720. */
  78721. this.bias = 0;
  78722. /**
  78723. * Defined the power exponent applied to fresnel term
  78724. */
  78725. this.power = 1;
  78726. }
  78727. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  78728. /**
  78729. * Define if the fresnel effect is enable or not.
  78730. */
  78731. get: function () {
  78732. return this._isEnabled;
  78733. },
  78734. set: function (value) {
  78735. if (this._isEnabled === value) {
  78736. return;
  78737. }
  78738. this._isEnabled = value;
  78739. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  78740. },
  78741. enumerable: true,
  78742. configurable: true
  78743. });
  78744. /**
  78745. * Clones the current fresnel and its valuues
  78746. * @returns a clone fresnel configuration
  78747. */
  78748. FresnelParameters.prototype.clone = function () {
  78749. var newFresnelParameters = new FresnelParameters();
  78750. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  78751. return newFresnelParameters;
  78752. };
  78753. /**
  78754. * Serializes the current fresnel parameters to a JSON representation.
  78755. * @return the JSON serialization
  78756. */
  78757. FresnelParameters.prototype.serialize = function () {
  78758. var serializationObject = {};
  78759. serializationObject.isEnabled = this.isEnabled;
  78760. serializationObject.leftColor = this.leftColor.asArray();
  78761. serializationObject.rightColor = this.rightColor.asArray();
  78762. serializationObject.bias = this.bias;
  78763. serializationObject.power = this.power;
  78764. return serializationObject;
  78765. };
  78766. /**
  78767. * Parse a JSON object and deserialize it to a new Fresnel parameter object.
  78768. * @param parsedFresnelParameters Define the JSON representation
  78769. * @returns the parsed parameters
  78770. */
  78771. FresnelParameters.Parse = function (parsedFresnelParameters) {
  78772. var fresnelParameters = new FresnelParameters();
  78773. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  78774. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  78775. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  78776. fresnelParameters.bias = parsedFresnelParameters.bias;
  78777. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  78778. return fresnelParameters;
  78779. };
  78780. return FresnelParameters;
  78781. }());
  78782. BABYLON.FresnelParameters = FresnelParameters;
  78783. })(BABYLON || (BABYLON = {}));
  78784. //# sourceMappingURL=babylon.fresnelParameters.js.map
  78785. var BABYLON;
  78786. (function (BABYLON) {
  78787. /**
  78788. * A multi-material is used to apply different materials to different parts of the same object without the need of
  78789. * separate meshes. This can be use to improve performances.
  78790. * @see http://doc.babylonjs.com/how_to/multi_materials
  78791. */
  78792. var MultiMaterial = /** @class */ (function (_super) {
  78793. __extends(MultiMaterial, _super);
  78794. /**
  78795. * Instantiates a new Multi Material
  78796. * A multi-material is used to apply different materials to different parts of the same object without the need of
  78797. * separate meshes. This can be use to improve performances.
  78798. * @see http://doc.babylonjs.com/how_to/multi_materials
  78799. * @param name Define the name in the scene
  78800. * @param scene Define the scene the material belongs to
  78801. */
  78802. function MultiMaterial(name, scene) {
  78803. var _this = _super.call(this, name, scene, true) || this;
  78804. scene.multiMaterials.push(_this);
  78805. _this.subMaterials = new Array();
  78806. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  78807. return _this;
  78808. }
  78809. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  78810. /**
  78811. * Gets or Sets the list of Materials used within the multi material.
  78812. * They need to be ordered according to the submeshes order in the associated mesh
  78813. */
  78814. get: function () {
  78815. return this._subMaterials;
  78816. },
  78817. set: function (value) {
  78818. this._subMaterials = value;
  78819. this._hookArray(value);
  78820. },
  78821. enumerable: true,
  78822. configurable: true
  78823. });
  78824. MultiMaterial.prototype._hookArray = function (array) {
  78825. var _this = this;
  78826. var oldPush = array.push;
  78827. array.push = function () {
  78828. var items = [];
  78829. for (var _i = 0; _i < arguments.length; _i++) {
  78830. items[_i] = arguments[_i];
  78831. }
  78832. var result = oldPush.apply(array, items);
  78833. _this._markAllSubMeshesAsTexturesDirty();
  78834. return result;
  78835. };
  78836. var oldSplice = array.splice;
  78837. array.splice = function (index, deleteCount) {
  78838. var deleted = oldSplice.apply(array, [index, deleteCount]);
  78839. _this._markAllSubMeshesAsTexturesDirty();
  78840. return deleted;
  78841. };
  78842. };
  78843. /**
  78844. * Get one of the submaterial by its index in the submaterials array
  78845. * @param index The index to look the sub material at
  78846. * @returns The Material if the index has been defined
  78847. */
  78848. MultiMaterial.prototype.getSubMaterial = function (index) {
  78849. if (index < 0 || index >= this.subMaterials.length) {
  78850. return this.getScene().defaultMaterial;
  78851. }
  78852. return this.subMaterials[index];
  78853. };
  78854. /**
  78855. * Get the list of active textures for the whole sub materials list.
  78856. * @returns All the textures that will be used during the rendering
  78857. */
  78858. MultiMaterial.prototype.getActiveTextures = function () {
  78859. var _a;
  78860. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  78861. if (subMaterial) {
  78862. return subMaterial.getActiveTextures();
  78863. }
  78864. else {
  78865. return [];
  78866. }
  78867. }));
  78868. };
  78869. /**
  78870. * Gets the current class name of the material e.g. "MultiMaterial"
  78871. * Mainly use in serialization.
  78872. * @returns the class name
  78873. */
  78874. MultiMaterial.prototype.getClassName = function () {
  78875. return "MultiMaterial";
  78876. };
  78877. /**
  78878. * Checks if the material is ready to render the requested sub mesh
  78879. * @param mesh Define the mesh the submesh belongs to
  78880. * @param subMesh Define the sub mesh to look readyness for
  78881. * @param useInstances Define whether or not the material is used with instances
  78882. * @returns true if ready, otherwise false
  78883. */
  78884. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  78885. for (var index = 0; index < this.subMaterials.length; index++) {
  78886. var subMaterial = this.subMaterials[index];
  78887. if (subMaterial) {
  78888. if (subMaterial.storeEffectOnSubMeshes) {
  78889. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  78890. return false;
  78891. }
  78892. continue;
  78893. }
  78894. if (!subMaterial.isReady(mesh)) {
  78895. return false;
  78896. }
  78897. }
  78898. }
  78899. return true;
  78900. };
  78901. /**
  78902. * Clones the current material and its related sub materials
  78903. * @param name Define the name of the newly cloned material
  78904. * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance
  78905. * @returns the cloned material
  78906. */
  78907. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  78908. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  78909. for (var index = 0; index < this.subMaterials.length; index++) {
  78910. var subMaterial = null;
  78911. var current = this.subMaterials[index];
  78912. if (cloneChildren && current) {
  78913. subMaterial = current.clone(name + "-" + current.name);
  78914. }
  78915. else {
  78916. subMaterial = this.subMaterials[index];
  78917. }
  78918. newMultiMaterial.subMaterials.push(subMaterial);
  78919. }
  78920. return newMultiMaterial;
  78921. };
  78922. /**
  78923. * Serializes the materials into a JSON representation.
  78924. * @returns the JSON representation
  78925. */
  78926. MultiMaterial.prototype.serialize = function () {
  78927. var serializationObject = {};
  78928. serializationObject.name = this.name;
  78929. serializationObject.id = this.id;
  78930. if (BABYLON.Tags) {
  78931. serializationObject.tags = BABYLON.Tags.GetTags(this);
  78932. }
  78933. serializationObject.materials = [];
  78934. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  78935. var subMat = this.subMaterials[matIndex];
  78936. if (subMat) {
  78937. serializationObject.materials.push(subMat.id);
  78938. }
  78939. else {
  78940. serializationObject.materials.push(null);
  78941. }
  78942. }
  78943. return serializationObject;
  78944. };
  78945. /**
  78946. * Dispose the material and release its associated resources
  78947. * @param forceDisposeEffect Define if we want to force disposing the associated effect (if false the shader is not released and could be reuse later on)
  78948. * @param forceDisposeTextures Define if we want to force disposing the associated textures (if false, they will not be disposed and can still be use elsewhere in the app)
  78949. */
  78950. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  78951. var scene = this.getScene();
  78952. if (!scene) {
  78953. return;
  78954. }
  78955. var index = scene.multiMaterials.indexOf(this);
  78956. if (index >= 0) {
  78957. scene.multiMaterials.splice(index, 1);
  78958. }
  78959. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  78960. };
  78961. return MultiMaterial;
  78962. }(BABYLON.Material));
  78963. BABYLON.MultiMaterial = MultiMaterial;
  78964. })(BABYLON || (BABYLON = {}));
  78965. //# sourceMappingURL=babylon.multiMaterial.js.map
  78966. var BABYLON;
  78967. (function (BABYLON) {
  78968. /**
  78969. * Manage the touch inputs to control the movement of a free camera.
  78970. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  78971. */
  78972. var FreeCameraTouchInput = /** @class */ (function () {
  78973. function FreeCameraTouchInput() {
  78974. /**
  78975. * Defines the touch sensibility for rotation.
  78976. * The higher the faster.
  78977. */
  78978. this.touchAngularSensibility = 200000.0;
  78979. /**
  78980. * Defines the touch sensibility for move.
  78981. * The higher the faster.
  78982. */
  78983. this.touchMoveSensibility = 250.0;
  78984. this._offsetX = null;
  78985. this._offsetY = null;
  78986. this._pointerPressed = new Array();
  78987. }
  78988. /**
  78989. * Attach the input controls to a specific dom element to get the input from.
  78990. * @param element Defines the element the controls should be listened from
  78991. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  78992. */
  78993. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  78994. var _this = this;
  78995. var previousPosition = null;
  78996. if (this._pointerInput === undefined) {
  78997. this._onLostFocus = function (evt) {
  78998. _this._offsetX = null;
  78999. _this._offsetY = null;
  79000. };
  79001. this._pointerInput = function (p, s) {
  79002. var evt = p.event;
  79003. if (evt.pointerType === "mouse") {
  79004. return;
  79005. }
  79006. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  79007. if (!noPreventDefault) {
  79008. evt.preventDefault();
  79009. }
  79010. _this._pointerPressed.push(evt.pointerId);
  79011. if (_this._pointerPressed.length !== 1) {
  79012. return;
  79013. }
  79014. previousPosition = {
  79015. x: evt.clientX,
  79016. y: evt.clientY
  79017. };
  79018. }
  79019. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  79020. if (!noPreventDefault) {
  79021. evt.preventDefault();
  79022. }
  79023. var index = _this._pointerPressed.indexOf(evt.pointerId);
  79024. if (index === -1) {
  79025. return;
  79026. }
  79027. _this._pointerPressed.splice(index, 1);
  79028. if (index != 0) {
  79029. return;
  79030. }
  79031. previousPosition = null;
  79032. _this._offsetX = null;
  79033. _this._offsetY = null;
  79034. }
  79035. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  79036. if (!noPreventDefault) {
  79037. evt.preventDefault();
  79038. }
  79039. if (!previousPosition) {
  79040. return;
  79041. }
  79042. var index = _this._pointerPressed.indexOf(evt.pointerId);
  79043. if (index != 0) {
  79044. return;
  79045. }
  79046. _this._offsetX = evt.clientX - previousPosition.x;
  79047. _this._offsetY = -(evt.clientY - previousPosition.y);
  79048. }
  79049. };
  79050. }
  79051. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  79052. if (this._onLostFocus) {
  79053. element.addEventListener("blur", this._onLostFocus);
  79054. }
  79055. };
  79056. /**
  79057. * Detach the current controls from the specified dom element.
  79058. * @param element Defines the element to stop listening the inputs from
  79059. */
  79060. FreeCameraTouchInput.prototype.detachControl = function (element) {
  79061. if (this._pointerInput && element) {
  79062. if (this._observer) {
  79063. this.camera.getScene().onPointerObservable.remove(this._observer);
  79064. this._observer = null;
  79065. }
  79066. if (this._onLostFocus) {
  79067. element.removeEventListener("blur", this._onLostFocus);
  79068. this._onLostFocus = null;
  79069. }
  79070. this._pointerPressed = [];
  79071. this._offsetX = null;
  79072. this._offsetY = null;
  79073. }
  79074. };
  79075. /**
  79076. * Update the current camera state depending on the inputs that have been used this frame.
  79077. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  79078. */
  79079. FreeCameraTouchInput.prototype.checkInputs = function () {
  79080. if (this._offsetX && this._offsetY) {
  79081. var camera = this.camera;
  79082. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  79083. if (this._pointerPressed.length > 1) {
  79084. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  79085. }
  79086. else {
  79087. var speed = camera._computeLocalCameraSpeed();
  79088. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  79089. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  79090. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  79091. }
  79092. }
  79093. };
  79094. /**
  79095. * Gets the class name of the current intput.
  79096. * @returns the class name
  79097. */
  79098. FreeCameraTouchInput.prototype.getClassName = function () {
  79099. return "FreeCameraTouchInput";
  79100. };
  79101. /**
  79102. * Get the friendly name associated with the input class.
  79103. * @returns the input friendly name
  79104. */
  79105. FreeCameraTouchInput.prototype.getSimpleName = function () {
  79106. return "touch";
  79107. };
  79108. __decorate([
  79109. BABYLON.serialize()
  79110. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  79111. __decorate([
  79112. BABYLON.serialize()
  79113. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  79114. return FreeCameraTouchInput;
  79115. }());
  79116. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  79117. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  79118. })(BABYLON || (BABYLON = {}));
  79119. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  79120. var BABYLON;
  79121. (function (BABYLON) {
  79122. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  79123. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  79124. });
  79125. /**
  79126. * This represents a FPS type of camera controlled by touch.
  79127. * This is like a universal camera minus the Gamepad controls.
  79128. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79129. */
  79130. var TouchCamera = /** @class */ (function (_super) {
  79131. __extends(TouchCamera, _super);
  79132. /**
  79133. * Instantiates a new touch camera.
  79134. * This represents a FPS type of camera controlled by touch.
  79135. * This is like a universal camera minus the Gamepad controls.
  79136. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79137. * @param name Define the name of the camera in the scene
  79138. * @param position Define the start position of the camera in the scene
  79139. * @param scene Define the scene the camera belongs to
  79140. */
  79141. function TouchCamera(name, position, scene) {
  79142. var _this = _super.call(this, name, position, scene) || this;
  79143. _this.inputs.addTouch();
  79144. _this._setupInputs();
  79145. return _this;
  79146. }
  79147. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  79148. /**
  79149. * Defines the touch sensibility for rotation.
  79150. * The higher the faster.
  79151. */
  79152. get: function () {
  79153. var touch = this.inputs.attached["touch"];
  79154. if (touch) {
  79155. return touch.touchAngularSensibility;
  79156. }
  79157. return 0;
  79158. },
  79159. set: function (value) {
  79160. var touch = this.inputs.attached["touch"];
  79161. if (touch) {
  79162. touch.touchAngularSensibility = value;
  79163. }
  79164. },
  79165. enumerable: true,
  79166. configurable: true
  79167. });
  79168. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  79169. /**
  79170. * Defines the touch sensibility for move.
  79171. * The higher the faster.
  79172. */
  79173. get: function () {
  79174. var touch = this.inputs.attached["touch"];
  79175. if (touch) {
  79176. return touch.touchMoveSensibility;
  79177. }
  79178. return 0;
  79179. },
  79180. set: function (value) {
  79181. var touch = this.inputs.attached["touch"];
  79182. if (touch) {
  79183. touch.touchMoveSensibility = value;
  79184. }
  79185. },
  79186. enumerable: true,
  79187. configurable: true
  79188. });
  79189. /**
  79190. * Gets the current object class name.
  79191. * @return the class name
  79192. */
  79193. TouchCamera.prototype.getClassName = function () {
  79194. return "TouchCamera";
  79195. };
  79196. /** @hidden */
  79197. TouchCamera.prototype._setupInputs = function () {
  79198. var mouse = this.inputs.attached["mouse"];
  79199. if (mouse) {
  79200. mouse.touchEnabled = false;
  79201. }
  79202. };
  79203. return TouchCamera;
  79204. }(BABYLON.FreeCamera));
  79205. BABYLON.TouchCamera = TouchCamera;
  79206. })(BABYLON || (BABYLON = {}));
  79207. //# sourceMappingURL=babylon.touchCamera.js.map
  79208. var BABYLON;
  79209. (function (BABYLON) {
  79210. /**
  79211. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  79212. * This is the base class of any Procedural texture and contains most of the shareable code.
  79213. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  79214. */
  79215. var ProceduralTexture = /** @class */ (function (_super) {
  79216. __extends(ProceduralTexture, _super);
  79217. /**
  79218. * Instantiates a new procedural texture.
  79219. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  79220. * This is the base class of any Procedural texture and contains most of the shareable code.
  79221. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  79222. * @param name Define the name of the texture
  79223. * @param size Define the size of the texture to create
  79224. * @param fragment Define the fragment shader to use to generate the texture or null if it is defined later
  79225. * @param scene Define the scene the texture belongs to
  79226. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  79227. * @param generateMipMaps Define if the texture should creates mip maps or not
  79228. * @param isCube Define if the texture is a cube texture or not (this will render each faces of the cube)
  79229. */
  79230. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  79231. if (fallbackTexture === void 0) { fallbackTexture = null; }
  79232. if (generateMipMaps === void 0) { generateMipMaps = true; }
  79233. if (isCube === void 0) { isCube = false; }
  79234. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  79235. _this.isCube = isCube;
  79236. /**
  79237. * Define if the texture is enabled or not (disabled texture will not render)
  79238. */
  79239. _this.isEnabled = true;
  79240. /**
  79241. * Event raised when the texture is generated
  79242. */
  79243. _this.onGeneratedObservable = new BABYLON.Observable();
  79244. /** @hidden */
  79245. _this._textures = {};
  79246. _this._currentRefreshId = -1;
  79247. _this._refreshRate = 1;
  79248. _this._vertexBuffers = {};
  79249. _this._uniforms = new Array();
  79250. _this._samplers = new Array();
  79251. _this._floats = {};
  79252. _this._ints = {};
  79253. _this._floatsArrays = {};
  79254. _this._colors3 = {};
  79255. _this._colors4 = {};
  79256. _this._vectors2 = {};
  79257. _this._vectors3 = {};
  79258. _this._matrices = {};
  79259. _this._fallbackTextureUsed = false;
  79260. _this._cachedDefines = "";
  79261. _this._contentUpdateId = -1;
  79262. scene = _this.getScene();
  79263. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  79264. if (!component) {
  79265. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  79266. scene._addComponent(component);
  79267. }
  79268. scene.proceduralTextures.push(_this);
  79269. _this._engine = scene.getEngine();
  79270. _this.name = name;
  79271. _this.isRenderTarget = true;
  79272. _this._size = size;
  79273. _this._generateMipMaps = generateMipMaps;
  79274. _this.setFragment(fragment);
  79275. _this._fallbackTexture = fallbackTexture;
  79276. if (isCube) {
  79277. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  79278. _this.setFloat("face", 0);
  79279. }
  79280. else {
  79281. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  79282. }
  79283. // VBO
  79284. var vertices = [];
  79285. vertices.push(1, 1);
  79286. vertices.push(-1, 1);
  79287. vertices.push(-1, -1);
  79288. vertices.push(1, -1);
  79289. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  79290. _this._createIndexBuffer();
  79291. return _this;
  79292. }
  79293. /**
  79294. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  79295. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  79296. */
  79297. ProceduralTexture.prototype.getContent = function () {
  79298. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  79299. return this._contentData;
  79300. }
  79301. this._contentData = this.readPixels(0, 0, this._contentData);
  79302. this._contentUpdateId = this._currentRefreshId;
  79303. return this._contentData;
  79304. };
  79305. ProceduralTexture.prototype._createIndexBuffer = function () {
  79306. var engine = this._engine;
  79307. // Indices
  79308. var indices = [];
  79309. indices.push(0);
  79310. indices.push(1);
  79311. indices.push(2);
  79312. indices.push(0);
  79313. indices.push(2);
  79314. indices.push(3);
  79315. this._indexBuffer = engine.createIndexBuffer(indices);
  79316. };
  79317. /** @hidden */
  79318. ProceduralTexture.prototype._rebuild = function () {
  79319. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79320. if (vb) {
  79321. vb._rebuild();
  79322. }
  79323. this._createIndexBuffer();
  79324. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  79325. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  79326. }
  79327. };
  79328. /**
  79329. * Resets the texture in order to recreate its associated resources.
  79330. * This can be called in case of context loss
  79331. */
  79332. ProceduralTexture.prototype.reset = function () {
  79333. if (this._effect === undefined) {
  79334. return;
  79335. }
  79336. var engine = this._engine;
  79337. engine._releaseEffect(this._effect);
  79338. };
  79339. ProceduralTexture.prototype._getDefines = function () {
  79340. return "";
  79341. };
  79342. /**
  79343. * Is the texture ready to be used ? (rendered at least once)
  79344. * @returns true if ready, otherwise, false.
  79345. */
  79346. ProceduralTexture.prototype.isReady = function () {
  79347. var _this = this;
  79348. var engine = this._engine;
  79349. var shaders;
  79350. if (!this._fragment) {
  79351. return false;
  79352. }
  79353. if (this._fallbackTextureUsed) {
  79354. return true;
  79355. }
  79356. var defines = this._getDefines();
  79357. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  79358. return true;
  79359. }
  79360. if (this._fragment.fragmentElement !== undefined) {
  79361. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  79362. }
  79363. else {
  79364. shaders = { vertex: "procedural", fragment: this._fragment };
  79365. }
  79366. this._cachedDefines = defines;
  79367. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  79368. _this.releaseInternalTexture();
  79369. if (_this._fallbackTexture) {
  79370. _this._texture = _this._fallbackTexture._texture;
  79371. if (_this._texture) {
  79372. _this._texture.incrementReferences();
  79373. }
  79374. }
  79375. _this._fallbackTextureUsed = true;
  79376. });
  79377. return this._effect.isReady();
  79378. };
  79379. /**
  79380. * Resets the refresh counter of the texture and start bak from scratch.
  79381. * Could be usefull to regenerate the texture if it is setup to render only once.
  79382. */
  79383. ProceduralTexture.prototype.resetRefreshCounter = function () {
  79384. this._currentRefreshId = -1;
  79385. };
  79386. /**
  79387. * Set the fragment shader to use in order to render the texture.
  79388. * @param fragment This can be set to a path (into the shader store) or to a json object containing a fragmentElement property.
  79389. */
  79390. ProceduralTexture.prototype.setFragment = function (fragment) {
  79391. this._fragment = fragment;
  79392. };
  79393. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  79394. /**
  79395. * Define the refresh rate of the texture or the rendering frequency.
  79396. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  79397. */
  79398. get: function () {
  79399. return this._refreshRate;
  79400. },
  79401. set: function (value) {
  79402. this._refreshRate = value;
  79403. this.resetRefreshCounter();
  79404. },
  79405. enumerable: true,
  79406. configurable: true
  79407. });
  79408. /** @hidden */
  79409. ProceduralTexture.prototype._shouldRender = function () {
  79410. if (!this.isEnabled || !this.isReady() || !this._texture) {
  79411. if (this._texture) {
  79412. this._texture.isReady = false;
  79413. }
  79414. return false;
  79415. }
  79416. if (this._fallbackTextureUsed) {
  79417. return false;
  79418. }
  79419. if (this._currentRefreshId === -1) { // At least render once
  79420. this._currentRefreshId = 1;
  79421. return true;
  79422. }
  79423. if (this.refreshRate === this._currentRefreshId) {
  79424. this._currentRefreshId = 1;
  79425. return true;
  79426. }
  79427. this._currentRefreshId++;
  79428. return false;
  79429. };
  79430. /**
  79431. * Get the size the texture is rendering at.
  79432. * @returns the size (texture is always squared)
  79433. */
  79434. ProceduralTexture.prototype.getRenderSize = function () {
  79435. return this._size;
  79436. };
  79437. /**
  79438. * Resize the texture to new value.
  79439. * @param size Define the new size the texture should have
  79440. * @param generateMipMaps Define whether the new texture should create mip maps
  79441. */
  79442. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  79443. if (this._fallbackTextureUsed) {
  79444. return;
  79445. }
  79446. this.releaseInternalTexture();
  79447. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  79448. // Update properties
  79449. this._size = size;
  79450. this._generateMipMaps = generateMipMaps;
  79451. };
  79452. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  79453. if (this._uniforms.indexOf(uniformName) === -1) {
  79454. this._uniforms.push(uniformName);
  79455. }
  79456. };
  79457. /**
  79458. * Set a texture in the shader program used to render.
  79459. * @param name Define the name of the uniform samplers as defined in the shader
  79460. * @param texture Define the texture to bind to this sampler
  79461. * @return the texture itself allowing "fluent" like uniform updates
  79462. */
  79463. ProceduralTexture.prototype.setTexture = function (name, texture) {
  79464. if (this._samplers.indexOf(name) === -1) {
  79465. this._samplers.push(name);
  79466. }
  79467. this._textures[name] = texture;
  79468. return this;
  79469. };
  79470. /**
  79471. * Set a float in the shader.
  79472. * @param name Define the name of the uniform as defined in the shader
  79473. * @param value Define the value to give to the uniform
  79474. * @return the texture itself allowing "fluent" like uniform updates
  79475. */
  79476. ProceduralTexture.prototype.setFloat = function (name, value) {
  79477. this._checkUniform(name);
  79478. this._floats[name] = value;
  79479. return this;
  79480. };
  79481. /**
  79482. * Set a int in the shader.
  79483. * @param name Define the name of the uniform as defined in the shader
  79484. * @param value Define the value to give to the uniform
  79485. * @return the texture itself allowing "fluent" like uniform updates
  79486. */
  79487. ProceduralTexture.prototype.setInt = function (name, value) {
  79488. this._checkUniform(name);
  79489. this._ints[name] = value;
  79490. return this;
  79491. };
  79492. /**
  79493. * Set an array of floats in the shader.
  79494. * @param name Define the name of the uniform as defined in the shader
  79495. * @param value Define the value to give to the uniform
  79496. * @return the texture itself allowing "fluent" like uniform updates
  79497. */
  79498. ProceduralTexture.prototype.setFloats = function (name, value) {
  79499. this._checkUniform(name);
  79500. this._floatsArrays[name] = value;
  79501. return this;
  79502. };
  79503. /**
  79504. * Set a vec3 in the shader from a Color3.
  79505. * @param name Define the name of the uniform as defined in the shader
  79506. * @param value Define the value to give to the uniform
  79507. * @return the texture itself allowing "fluent" like uniform updates
  79508. */
  79509. ProceduralTexture.prototype.setColor3 = function (name, value) {
  79510. this._checkUniform(name);
  79511. this._colors3[name] = value;
  79512. return this;
  79513. };
  79514. /**
  79515. * Set a vec4 in the shader from a Color4.
  79516. * @param name Define the name of the uniform as defined in the shader
  79517. * @param value Define the value to give to the uniform
  79518. * @return the texture itself allowing "fluent" like uniform updates
  79519. */
  79520. ProceduralTexture.prototype.setColor4 = function (name, value) {
  79521. this._checkUniform(name);
  79522. this._colors4[name] = value;
  79523. return this;
  79524. };
  79525. /**
  79526. * Set a vec2 in the shader from a Vector2.
  79527. * @param name Define the name of the uniform as defined in the shader
  79528. * @param value Define the value to give to the uniform
  79529. * @return the texture itself allowing "fluent" like uniform updates
  79530. */
  79531. ProceduralTexture.prototype.setVector2 = function (name, value) {
  79532. this._checkUniform(name);
  79533. this._vectors2[name] = value;
  79534. return this;
  79535. };
  79536. /**
  79537. * Set a vec3 in the shader from a Vector3.
  79538. * @param name Define the name of the uniform as defined in the shader
  79539. * @param value Define the value to give to the uniform
  79540. * @return the texture itself allowing "fluent" like uniform updates
  79541. */
  79542. ProceduralTexture.prototype.setVector3 = function (name, value) {
  79543. this._checkUniform(name);
  79544. this._vectors3[name] = value;
  79545. return this;
  79546. };
  79547. /**
  79548. * Set a mat4 in the shader from a MAtrix.
  79549. * @param name Define the name of the uniform as defined in the shader
  79550. * @param value Define the value to give to the uniform
  79551. * @return the texture itself allowing "fluent" like uniform updates
  79552. */
  79553. ProceduralTexture.prototype.setMatrix = function (name, value) {
  79554. this._checkUniform(name);
  79555. this._matrices[name] = value;
  79556. return this;
  79557. };
  79558. /**
  79559. * Render the texture to its associated render target.
  79560. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  79561. */
  79562. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  79563. var scene = this.getScene();
  79564. if (!scene) {
  79565. return;
  79566. }
  79567. var engine = this._engine;
  79568. // Render
  79569. engine.enableEffect(this._effect);
  79570. engine.setState(false);
  79571. // Texture
  79572. for (var name in this._textures) {
  79573. this._effect.setTexture(name, this._textures[name]);
  79574. }
  79575. // Float
  79576. for (name in this._ints) {
  79577. this._effect.setInt(name, this._ints[name]);
  79578. }
  79579. // Float
  79580. for (name in this._floats) {
  79581. this._effect.setFloat(name, this._floats[name]);
  79582. }
  79583. // Floats
  79584. for (name in this._floatsArrays) {
  79585. this._effect.setArray(name, this._floatsArrays[name]);
  79586. }
  79587. // Color3
  79588. for (name in this._colors3) {
  79589. this._effect.setColor3(name, this._colors3[name]);
  79590. }
  79591. // Color4
  79592. for (name in this._colors4) {
  79593. var color = this._colors4[name];
  79594. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  79595. }
  79596. // Vector2
  79597. for (name in this._vectors2) {
  79598. this._effect.setVector2(name, this._vectors2[name]);
  79599. }
  79600. // Vector3
  79601. for (name in this._vectors3) {
  79602. this._effect.setVector3(name, this._vectors3[name]);
  79603. }
  79604. // Matrix
  79605. for (name in this._matrices) {
  79606. this._effect.setMatrix(name, this._matrices[name]);
  79607. }
  79608. if (!this._texture) {
  79609. return;
  79610. }
  79611. if (this.isCube) {
  79612. for (var face = 0; face < 6; face++) {
  79613. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  79614. // VBOs
  79615. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  79616. this._effect.setFloat("face", face);
  79617. // Clear
  79618. engine.clear(scene.clearColor, true, true, true);
  79619. // Draw order
  79620. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79621. // Mipmaps
  79622. if (face === 5) {
  79623. engine.generateMipMapsForCubemap(this._texture);
  79624. }
  79625. }
  79626. }
  79627. else {
  79628. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  79629. // VBOs
  79630. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  79631. // Clear
  79632. engine.clear(scene.clearColor, true, true, true);
  79633. // Draw order
  79634. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79635. }
  79636. // Unbind
  79637. engine.unBindFramebuffer(this._texture, this.isCube);
  79638. if (this.onGenerated) {
  79639. this.onGenerated();
  79640. }
  79641. this.onGeneratedObservable.notifyObservers(this);
  79642. };
  79643. /**
  79644. * Clone the texture.
  79645. * @returns the cloned texture
  79646. */
  79647. ProceduralTexture.prototype.clone = function () {
  79648. var textureSize = this.getSize();
  79649. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  79650. // Base texture
  79651. newTexture.hasAlpha = this.hasAlpha;
  79652. newTexture.level = this.level;
  79653. // RenderTarget Texture
  79654. newTexture.coordinatesMode = this.coordinatesMode;
  79655. return newTexture;
  79656. };
  79657. /**
  79658. * Dispose the texture and release its asoociated resources.
  79659. */
  79660. ProceduralTexture.prototype.dispose = function () {
  79661. var scene = this.getScene();
  79662. if (!scene) {
  79663. return;
  79664. }
  79665. var index = scene.proceduralTextures.indexOf(this);
  79666. if (index >= 0) {
  79667. scene.proceduralTextures.splice(index, 1);
  79668. }
  79669. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79670. if (vertexBuffer) {
  79671. vertexBuffer.dispose();
  79672. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79673. }
  79674. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  79675. this._indexBuffer = null;
  79676. }
  79677. _super.prototype.dispose.call(this);
  79678. };
  79679. __decorate([
  79680. BABYLON.serialize()
  79681. ], ProceduralTexture.prototype, "isEnabled", void 0);
  79682. __decorate([
  79683. BABYLON.serialize()
  79684. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  79685. __decorate([
  79686. BABYLON.serialize()
  79687. ], ProceduralTexture.prototype, "_size", void 0);
  79688. __decorate([
  79689. BABYLON.serialize()
  79690. ], ProceduralTexture.prototype, "refreshRate", null);
  79691. return ProceduralTexture;
  79692. }(BABYLON.Texture));
  79693. BABYLON.ProceduralTexture = ProceduralTexture;
  79694. })(BABYLON || (BABYLON = {}));
  79695. //# sourceMappingURL=babylon.proceduralTexture.js.map
  79696. var BABYLON;
  79697. (function (BABYLON) {
  79698. /**
  79699. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  79700. * in a given scene.
  79701. */
  79702. var ProceduralTextureSceneComponent = /** @class */ (function () {
  79703. /**
  79704. * Creates a new instance of the component for the given scene
  79705. * @param scene Defines the scene to register the component in
  79706. */
  79707. function ProceduralTextureSceneComponent(scene) {
  79708. /**
  79709. * The component name helpfull to identify the component in the list of scene components.
  79710. */
  79711. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  79712. this.scene = scene;
  79713. this.scene.proceduralTextures = new Array();
  79714. scene.layers = new Array();
  79715. }
  79716. /**
  79717. * Registers the component in a given scene
  79718. */
  79719. ProceduralTextureSceneComponent.prototype.register = function () {
  79720. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  79721. };
  79722. /**
  79723. * Rebuilds the elements related to this component in case of
  79724. * context lost for instance.
  79725. */
  79726. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  79727. // Nothing to do here.
  79728. };
  79729. /**
  79730. * Disposes the component and the associated ressources.
  79731. */
  79732. ProceduralTextureSceneComponent.prototype.dispose = function () {
  79733. // Nothing to do here.
  79734. };
  79735. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  79736. if (this.scene.proceduralTexturesEnabled) {
  79737. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  79738. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  79739. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  79740. if (proceduralTexture._shouldRender()) {
  79741. proceduralTexture.render();
  79742. }
  79743. }
  79744. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  79745. }
  79746. };
  79747. return ProceduralTextureSceneComponent;
  79748. }());
  79749. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  79750. })(BABYLON || (BABYLON = {}));
  79751. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  79752. var BABYLON;
  79753. (function (BABYLON) {
  79754. /**
  79755. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  79756. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  79757. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  79758. */
  79759. var CustomProceduralTexture = /** @class */ (function (_super) {
  79760. __extends(CustomProceduralTexture, _super);
  79761. /**
  79762. * Instantiates a new Custom Procedural Texture.
  79763. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  79764. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  79765. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  79766. * @param name Define the name of the texture
  79767. * @param texturePath Define the folder path containing all the cutom texture related files (config, shaders...)
  79768. * @param size Define the size of the texture to create
  79769. * @param scene Define the scene the texture belongs to
  79770. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  79771. * @param generateMipMaps Define if the texture should creates mip maps or not
  79772. */
  79773. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  79774. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  79775. _this._animate = true;
  79776. _this._time = 0;
  79777. _this._texturePath = texturePath;
  79778. //Try to load json
  79779. _this._loadJson(texturePath);
  79780. _this.refreshRate = 1;
  79781. return _this;
  79782. }
  79783. CustomProceduralTexture.prototype._loadJson = function (jsonUrl) {
  79784. var _this = this;
  79785. var noConfigFile = function () {
  79786. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  79787. try {
  79788. _this.setFragment(_this._texturePath);
  79789. }
  79790. catch (ex) {
  79791. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  79792. }
  79793. };
  79794. var configFileUrl = jsonUrl + "/config.json";
  79795. var xhr = new XMLHttpRequest();
  79796. xhr.open("GET", configFileUrl, true);
  79797. xhr.addEventListener("load", function () {
  79798. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  79799. try {
  79800. _this._config = JSON.parse(xhr.response);
  79801. _this.updateShaderUniforms();
  79802. _this.updateTextures();
  79803. _this.setFragment(_this._texturePath + "/custom");
  79804. _this._animate = _this._config.animate;
  79805. _this.refreshRate = _this._config.refreshrate;
  79806. }
  79807. catch (ex) {
  79808. noConfigFile();
  79809. }
  79810. }
  79811. else {
  79812. noConfigFile();
  79813. }
  79814. }, false);
  79815. xhr.addEventListener("error", function () {
  79816. noConfigFile();
  79817. }, false);
  79818. try {
  79819. xhr.send();
  79820. }
  79821. catch (ex) {
  79822. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  79823. }
  79824. };
  79825. /**
  79826. * Is the texture ready to be used ? (rendered at least once)
  79827. * @returns true if ready, otherwise, false.
  79828. */
  79829. CustomProceduralTexture.prototype.isReady = function () {
  79830. if (!_super.prototype.isReady.call(this)) {
  79831. return false;
  79832. }
  79833. for (var name in this._textures) {
  79834. var texture = this._textures[name];
  79835. if (!texture.isReady()) {
  79836. return false;
  79837. }
  79838. }
  79839. return true;
  79840. };
  79841. /**
  79842. * Render the texture to its associated render target.
  79843. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  79844. */
  79845. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  79846. var scene = this.getScene();
  79847. if (this._animate && scene) {
  79848. this._time += scene.getAnimationRatio() * 0.03;
  79849. this.updateShaderUniforms();
  79850. }
  79851. _super.prototype.render.call(this, useCameraPostProcess);
  79852. };
  79853. /**
  79854. * Update the list of dependant textures samplers in the shader.
  79855. */
  79856. CustomProceduralTexture.prototype.updateTextures = function () {
  79857. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  79858. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  79859. }
  79860. };
  79861. /**
  79862. * Update the uniform values of the procedural texture in the shader.
  79863. */
  79864. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  79865. if (this._config) {
  79866. for (var j = 0; j < this._config.uniforms.length; j++) {
  79867. var uniform = this._config.uniforms[j];
  79868. switch (uniform.type) {
  79869. case "float":
  79870. this.setFloat(uniform.name, uniform.value);
  79871. break;
  79872. case "color3":
  79873. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  79874. break;
  79875. case "color4":
  79876. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  79877. break;
  79878. case "vector2":
  79879. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  79880. break;
  79881. case "vector3":
  79882. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  79883. break;
  79884. }
  79885. }
  79886. }
  79887. this.setFloat("time", this._time);
  79888. };
  79889. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  79890. /**
  79891. * Define if the texture animates or not.
  79892. */
  79893. get: function () {
  79894. return this._animate;
  79895. },
  79896. set: function (value) {
  79897. this._animate = value;
  79898. },
  79899. enumerable: true,
  79900. configurable: true
  79901. });
  79902. return CustomProceduralTexture;
  79903. }(BABYLON.ProceduralTexture));
  79904. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  79905. })(BABYLON || (BABYLON = {}));
  79906. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  79907. var BABYLON;
  79908. (function (BABYLON) {
  79909. /**
  79910. * Manage the gamepad inputs to control a free camera.
  79911. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  79912. */
  79913. var FreeCameraGamepadInput = /** @class */ (function () {
  79914. function FreeCameraGamepadInput() {
  79915. /**
  79916. * Defines the gamepad rotation sensiblity.
  79917. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  79918. */
  79919. this.gamepadAngularSensibility = 200;
  79920. /**
  79921. * Defines the gamepad move sensiblity.
  79922. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  79923. */
  79924. this.gamepadMoveSensibility = 40;
  79925. this._cameraTransform = BABYLON.Matrix.Identity();
  79926. this._deltaTransform = BABYLON.Vector3.Zero();
  79927. this._vector3 = BABYLON.Vector3.Zero();
  79928. this._vector2 = BABYLON.Vector2.Zero();
  79929. }
  79930. /**
  79931. * Attach the input controls to a specific dom element to get the input from.
  79932. * @param element Defines the element the controls should be listened from
  79933. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  79934. */
  79935. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  79936. var _this = this;
  79937. var manager = this.camera.getScene().gamepadManager;
  79938. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  79939. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  79940. // prioritize XBOX gamepads.
  79941. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  79942. _this.gamepad = gamepad;
  79943. }
  79944. }
  79945. });
  79946. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  79947. if (_this.gamepad === gamepad) {
  79948. _this.gamepad = null;
  79949. }
  79950. });
  79951. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  79952. };
  79953. /**
  79954. * Detach the current controls from the specified dom element.
  79955. * @param element Defines the element to stop listening the inputs from
  79956. */
  79957. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  79958. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  79959. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  79960. this.gamepad = null;
  79961. };
  79962. /**
  79963. * Update the current camera state depending on the inputs that have been used this frame.
  79964. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  79965. */
  79966. FreeCameraGamepadInput.prototype.checkInputs = function () {
  79967. if (this.gamepad && this.gamepad.leftStick) {
  79968. var camera = this.camera;
  79969. var LSValues = this.gamepad.leftStick;
  79970. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  79971. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  79972. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  79973. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  79974. var RSValues = this.gamepad.rightStick;
  79975. if (RSValues) {
  79976. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  79977. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  79978. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  79979. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  79980. }
  79981. else {
  79982. RSValues = { x: 0, y: 0 };
  79983. }
  79984. if (!camera.rotationQuaternion) {
  79985. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  79986. }
  79987. else {
  79988. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  79989. }
  79990. var speed = camera._computeLocalCameraSpeed() * 50.0;
  79991. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  79992. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  79993. camera.cameraDirection.addInPlace(this._deltaTransform);
  79994. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  79995. camera.cameraRotation.addInPlace(this._vector2);
  79996. }
  79997. };
  79998. /**
  79999. * Gets the class name of the current intput.
  80000. * @returns the class name
  80001. */
  80002. FreeCameraGamepadInput.prototype.getClassName = function () {
  80003. return "FreeCameraGamepadInput";
  80004. };
  80005. /**
  80006. * Get the friendly name associated with the input class.
  80007. * @returns the input friendly name
  80008. */
  80009. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  80010. return "gamepad";
  80011. };
  80012. __decorate([
  80013. BABYLON.serialize()
  80014. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  80015. __decorate([
  80016. BABYLON.serialize()
  80017. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  80018. return FreeCameraGamepadInput;
  80019. }());
  80020. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  80021. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  80022. })(BABYLON || (BABYLON = {}));
  80023. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  80024. var BABYLON;
  80025. (function (BABYLON) {
  80026. /**
  80027. * Manage the gamepad inputs to control an arc rotate camera.
  80028. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  80029. */
  80030. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  80031. function ArcRotateCameraGamepadInput() {
  80032. /**
  80033. * Defines the gamepad rotation sensiblity.
  80034. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  80035. */
  80036. this.gamepadRotationSensibility = 80;
  80037. /**
  80038. * Defines the gamepad move sensiblity.
  80039. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  80040. */
  80041. this.gamepadMoveSensibility = 40;
  80042. }
  80043. /**
  80044. * Attach the input controls to a specific dom element to get the input from.
  80045. * @param element Defines the element the controls should be listened from
  80046. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  80047. */
  80048. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  80049. var _this = this;
  80050. var manager = this.camera.getScene().gamepadManager;
  80051. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  80052. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  80053. // prioritize XBOX gamepads.
  80054. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  80055. _this.gamepad = gamepad;
  80056. }
  80057. }
  80058. });
  80059. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  80060. if (_this.gamepad === gamepad) {
  80061. _this.gamepad = null;
  80062. }
  80063. });
  80064. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  80065. };
  80066. /**
  80067. * Detach the current controls from the specified dom element.
  80068. * @param element Defines the element to stop listening the inputs from
  80069. */
  80070. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  80071. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  80072. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  80073. this.gamepad = null;
  80074. };
  80075. /**
  80076. * Update the current camera state depending on the inputs that have been used this frame.
  80077. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  80078. */
  80079. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  80080. if (this.gamepad) {
  80081. var camera = this.camera;
  80082. var RSValues = this.gamepad.rightStick;
  80083. if (RSValues) {
  80084. if (RSValues.x != 0) {
  80085. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  80086. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  80087. camera.inertialAlphaOffset += normalizedRX;
  80088. }
  80089. }
  80090. if (RSValues.y != 0) {
  80091. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  80092. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  80093. camera.inertialBetaOffset += normalizedRY;
  80094. }
  80095. }
  80096. }
  80097. var LSValues = this.gamepad.leftStick;
  80098. if (LSValues && LSValues.y != 0) {
  80099. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  80100. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  80101. this.camera.inertialRadiusOffset -= normalizedLY;
  80102. }
  80103. }
  80104. }
  80105. };
  80106. /**
  80107. * Gets the class name of the current intput.
  80108. * @returns the class name
  80109. */
  80110. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  80111. return "ArcRotateCameraGamepadInput";
  80112. };
  80113. /**
  80114. * Get the friendly name associated with the input class.
  80115. * @returns the input friendly name
  80116. */
  80117. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  80118. return "gamepad";
  80119. };
  80120. __decorate([
  80121. BABYLON.serialize()
  80122. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  80123. __decorate([
  80124. BABYLON.serialize()
  80125. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  80126. return ArcRotateCameraGamepadInput;
  80127. }());
  80128. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  80129. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  80130. })(BABYLON || (BABYLON = {}));
  80131. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  80132. var BABYLON;
  80133. (function (BABYLON) {
  80134. /**
  80135. * Manager for handling gamepads
  80136. */
  80137. var GamepadManager = /** @class */ (function () {
  80138. /**
  80139. * Initializes the gamepad manager
  80140. * @param _scene BabylonJS scene
  80141. */
  80142. function GamepadManager(_scene) {
  80143. var _this = this;
  80144. this._scene = _scene;
  80145. this._babylonGamepads = [];
  80146. this._oneGamepadConnected = false;
  80147. /** @hidden */
  80148. this._isMonitoring = false;
  80149. /**
  80150. * observable to be triggered when the gamepad controller has been disconnected
  80151. */
  80152. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  80153. if (!BABYLON.Tools.IsWindowObjectExist()) {
  80154. this._gamepadEventSupported = false;
  80155. }
  80156. else {
  80157. this._gamepadEventSupported = 'GamepadEvent' in window;
  80158. this._gamepadSupport = (navigator.getGamepads ||
  80159. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  80160. }
  80161. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  80162. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  80163. for (var i in _this._babylonGamepads) {
  80164. var gamepad = _this._babylonGamepads[i];
  80165. if (gamepad && gamepad._isConnected) {
  80166. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  80167. }
  80168. }
  80169. });
  80170. this._onGamepadConnectedEvent = function (evt) {
  80171. var gamepad = evt.gamepad;
  80172. if (gamepad.index in _this._babylonGamepads) {
  80173. if (_this._babylonGamepads[gamepad.index].isConnected) {
  80174. return;
  80175. }
  80176. }
  80177. var newGamepad;
  80178. if (_this._babylonGamepads[gamepad.index]) {
  80179. newGamepad = _this._babylonGamepads[gamepad.index];
  80180. newGamepad.browserGamepad = gamepad;
  80181. newGamepad._isConnected = true;
  80182. }
  80183. else {
  80184. newGamepad = _this._addNewGamepad(gamepad);
  80185. }
  80186. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  80187. _this._startMonitoringGamepads();
  80188. };
  80189. this._onGamepadDisconnectedEvent = function (evt) {
  80190. var gamepad = evt.gamepad;
  80191. // Remove the gamepad from the list of gamepads to monitor.
  80192. for (var i in _this._babylonGamepads) {
  80193. if (_this._babylonGamepads[i].index === gamepad.index) {
  80194. var disconnectedGamepad = _this._babylonGamepads[i];
  80195. disconnectedGamepad._isConnected = false;
  80196. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  80197. break;
  80198. }
  80199. }
  80200. };
  80201. if (this._gamepadSupport) {
  80202. //first add already-connected gamepads
  80203. this._updateGamepadObjects();
  80204. if (this._babylonGamepads.length) {
  80205. this._startMonitoringGamepads();
  80206. }
  80207. // Checking if the gamepad connected event is supported (like in Firefox)
  80208. if (this._gamepadEventSupported) {
  80209. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  80210. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  80211. }
  80212. else {
  80213. this._startMonitoringGamepads();
  80214. }
  80215. }
  80216. }
  80217. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  80218. /**
  80219. * The gamepads in the game pad manager
  80220. */
  80221. get: function () {
  80222. return this._babylonGamepads;
  80223. },
  80224. enumerable: true,
  80225. configurable: true
  80226. });
  80227. /**
  80228. * Get the gamepad controllers based on type
  80229. * @param type The type of gamepad controller
  80230. * @returns Nullable gamepad
  80231. */
  80232. GamepadManager.prototype.getGamepadByType = function (type) {
  80233. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  80234. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  80235. var gamepad = _a[_i];
  80236. if (gamepad && gamepad.type === type) {
  80237. return gamepad;
  80238. }
  80239. }
  80240. return null;
  80241. };
  80242. /**
  80243. * Disposes the gamepad manager
  80244. */
  80245. GamepadManager.prototype.dispose = function () {
  80246. if (this._gamepadEventSupported) {
  80247. if (this._onGamepadConnectedEvent) {
  80248. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  80249. }
  80250. if (this._onGamepadDisconnectedEvent) {
  80251. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  80252. }
  80253. this._onGamepadConnectedEvent = null;
  80254. this._onGamepadDisconnectedEvent = null;
  80255. }
  80256. this._babylonGamepads.forEach(function (gamepad) {
  80257. gamepad.dispose();
  80258. });
  80259. this.onGamepadConnectedObservable.clear();
  80260. this.onGamepadDisconnectedObservable.clear();
  80261. this._oneGamepadConnected = false;
  80262. this._stopMonitoringGamepads();
  80263. this._babylonGamepads = [];
  80264. };
  80265. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  80266. if (!this._oneGamepadConnected) {
  80267. this._oneGamepadConnected = true;
  80268. }
  80269. var newGamepad;
  80270. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  80271. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  80272. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  80273. }
  80274. // if pose is supported, use the (WebVR) pose enabled controller
  80275. else if (gamepad.pose) {
  80276. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  80277. }
  80278. else {
  80279. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  80280. }
  80281. this._babylonGamepads[newGamepad.index] = newGamepad;
  80282. return newGamepad;
  80283. };
  80284. GamepadManager.prototype._startMonitoringGamepads = function () {
  80285. if (!this._isMonitoring) {
  80286. this._isMonitoring = true;
  80287. //back-comp
  80288. if (!this._scene) {
  80289. this._checkGamepadsStatus();
  80290. }
  80291. }
  80292. };
  80293. GamepadManager.prototype._stopMonitoringGamepads = function () {
  80294. this._isMonitoring = false;
  80295. };
  80296. /** @hidden */
  80297. GamepadManager.prototype._checkGamepadsStatus = function () {
  80298. var _this = this;
  80299. // Hack to be compatible Chrome
  80300. this._updateGamepadObjects();
  80301. for (var i in this._babylonGamepads) {
  80302. var gamepad = this._babylonGamepads[i];
  80303. if (!gamepad || !gamepad.isConnected) {
  80304. continue;
  80305. }
  80306. gamepad.update();
  80307. }
  80308. if (this._isMonitoring && !this._scene) {
  80309. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  80310. }
  80311. };
  80312. // This function is called only on Chrome, which does not properly support
  80313. // connection/disconnection events and forces you to recopy again the gamepad object
  80314. GamepadManager.prototype._updateGamepadObjects = function () {
  80315. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  80316. for (var i = 0; i < gamepads.length; i++) {
  80317. var gamepad = gamepads[i];
  80318. if (gamepad) {
  80319. if (!this._babylonGamepads[gamepad.index]) {
  80320. var newGamepad = this._addNewGamepad(gamepad);
  80321. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  80322. }
  80323. else {
  80324. // Forced to copy again this object for Chrome for unknown reason
  80325. this._babylonGamepads[i].browserGamepad = gamepad;
  80326. if (!this._babylonGamepads[i].isConnected) {
  80327. this._babylonGamepads[i]._isConnected = true;
  80328. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  80329. }
  80330. }
  80331. }
  80332. }
  80333. };
  80334. return GamepadManager;
  80335. }());
  80336. BABYLON.GamepadManager = GamepadManager;
  80337. })(BABYLON || (BABYLON = {}));
  80338. //# sourceMappingURL=babylon.gamepadManager.js.map
  80339. var BABYLON;
  80340. (function (BABYLON) {
  80341. /**
  80342. * Represents a gamepad control stick position
  80343. */
  80344. var StickValues = /** @class */ (function () {
  80345. /**
  80346. * Initializes the gamepad x and y control stick values
  80347. * @param x The x component of the gamepad control stick value
  80348. * @param y The y component of the gamepad control stick value
  80349. */
  80350. function StickValues(
  80351. /**
  80352. * The x component of the control stick
  80353. */
  80354. x,
  80355. /**
  80356. * The y component of the control stick
  80357. */
  80358. y) {
  80359. this.x = x;
  80360. this.y = y;
  80361. }
  80362. return StickValues;
  80363. }());
  80364. BABYLON.StickValues = StickValues;
  80365. /**
  80366. * Represents a gamepad
  80367. */
  80368. var Gamepad = /** @class */ (function () {
  80369. /**
  80370. * Initializes the gamepad
  80371. * @param id The id of the gamepad
  80372. * @param index The index of the gamepad
  80373. * @param browserGamepad The browser gamepad
  80374. * @param leftStickX The x component of the left joystick
  80375. * @param leftStickY The y component of the left joystick
  80376. * @param rightStickX The x component of the right joystick
  80377. * @param rightStickY The y component of the right joystick
  80378. */
  80379. function Gamepad(
  80380. /**
  80381. * The id of the gamepad
  80382. */
  80383. id,
  80384. /**
  80385. * The index of the gamepad
  80386. */
  80387. index,
  80388. /**
  80389. * The browser gamepad
  80390. */
  80391. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  80392. if (leftStickX === void 0) { leftStickX = 0; }
  80393. if (leftStickY === void 0) { leftStickY = 1; }
  80394. if (rightStickX === void 0) { rightStickX = 2; }
  80395. if (rightStickY === void 0) { rightStickY = 3; }
  80396. this.id = id;
  80397. this.index = index;
  80398. this.browserGamepad = browserGamepad;
  80399. this._leftStick = { x: 0, y: 0 };
  80400. this._rightStick = { x: 0, y: 0 };
  80401. /** @hidden */
  80402. this._isConnected = true;
  80403. /**
  80404. * Specifies whether the left control stick should be Y-inverted
  80405. */
  80406. this._invertLeftStickY = false;
  80407. this.type = Gamepad.GAMEPAD;
  80408. this._leftStickAxisX = leftStickX;
  80409. this._leftStickAxisY = leftStickY;
  80410. this._rightStickAxisX = rightStickX;
  80411. this._rightStickAxisY = rightStickY;
  80412. if (this.browserGamepad.axes.length >= 2) {
  80413. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  80414. }
  80415. if (this.browserGamepad.axes.length >= 4) {
  80416. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  80417. }
  80418. }
  80419. Object.defineProperty(Gamepad.prototype, "isConnected", {
  80420. /**
  80421. * Specifies if the gamepad has been connected
  80422. */
  80423. get: function () {
  80424. return this._isConnected;
  80425. },
  80426. enumerable: true,
  80427. configurable: true
  80428. });
  80429. /**
  80430. * Callback triggered when the left joystick has changed
  80431. * @param callback
  80432. */
  80433. Gamepad.prototype.onleftstickchanged = function (callback) {
  80434. this._onleftstickchanged = callback;
  80435. };
  80436. /**
  80437. * Callback triggered when the right joystick has changed
  80438. * @param callback
  80439. */
  80440. Gamepad.prototype.onrightstickchanged = function (callback) {
  80441. this._onrightstickchanged = callback;
  80442. };
  80443. Object.defineProperty(Gamepad.prototype, "leftStick", {
  80444. /**
  80445. * Gets the left joystick
  80446. */
  80447. get: function () {
  80448. return this._leftStick;
  80449. },
  80450. /**
  80451. * Sets the left joystick values
  80452. */
  80453. set: function (newValues) {
  80454. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  80455. this._onleftstickchanged(newValues);
  80456. }
  80457. this._leftStick = newValues;
  80458. },
  80459. enumerable: true,
  80460. configurable: true
  80461. });
  80462. Object.defineProperty(Gamepad.prototype, "rightStick", {
  80463. /**
  80464. * Gets the right joystick
  80465. */
  80466. get: function () {
  80467. return this._rightStick;
  80468. },
  80469. /**
  80470. * Sets the right joystick value
  80471. */
  80472. set: function (newValues) {
  80473. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  80474. this._onrightstickchanged(newValues);
  80475. }
  80476. this._rightStick = newValues;
  80477. },
  80478. enumerable: true,
  80479. configurable: true
  80480. });
  80481. /**
  80482. * Updates the gamepad joystick positions
  80483. */
  80484. Gamepad.prototype.update = function () {
  80485. if (this._leftStick) {
  80486. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  80487. if (this._invertLeftStickY) {
  80488. this.leftStick.y *= -1;
  80489. }
  80490. }
  80491. if (this._rightStick) {
  80492. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  80493. }
  80494. };
  80495. /**
  80496. * Disposes the gamepad
  80497. */
  80498. Gamepad.prototype.dispose = function () {
  80499. };
  80500. /**
  80501. * Represents a gamepad controller
  80502. */
  80503. Gamepad.GAMEPAD = 0;
  80504. /**
  80505. * Represents a generic controller
  80506. */
  80507. Gamepad.GENERIC = 1;
  80508. /**
  80509. * Represents an XBox controller
  80510. */
  80511. Gamepad.XBOX = 2;
  80512. /**
  80513. * Represents a pose-enabled controller
  80514. */
  80515. Gamepad.POSE_ENABLED = 3;
  80516. return Gamepad;
  80517. }());
  80518. BABYLON.Gamepad = Gamepad;
  80519. /**
  80520. * Represents a generic gamepad
  80521. */
  80522. var GenericPad = /** @class */ (function (_super) {
  80523. __extends(GenericPad, _super);
  80524. /**
  80525. * Initializes the generic gamepad
  80526. * @param id The id of the generic gamepad
  80527. * @param index The index of the generic gamepad
  80528. * @param browserGamepad The browser gamepad
  80529. */
  80530. function GenericPad(id, index, browserGamepad) {
  80531. var _this = _super.call(this, id, index, browserGamepad) || this;
  80532. /**
  80533. * Observable triggered when a button has been pressed
  80534. */
  80535. _this.onButtonDownObservable = new BABYLON.Observable();
  80536. /**
  80537. * Observable triggered when a button has been released
  80538. */
  80539. _this.onButtonUpObservable = new BABYLON.Observable();
  80540. _this.type = Gamepad.GENERIC;
  80541. _this._buttons = new Array(browserGamepad.buttons.length);
  80542. return _this;
  80543. }
  80544. /**
  80545. * Callback triggered when a button has been pressed
  80546. * @param callback Called when a button has been pressed
  80547. */
  80548. GenericPad.prototype.onbuttondown = function (callback) {
  80549. this._onbuttondown = callback;
  80550. };
  80551. /**
  80552. * Callback triggered when a button has been released
  80553. * @param callback Called when a button has been released
  80554. */
  80555. GenericPad.prototype.onbuttonup = function (callback) {
  80556. this._onbuttonup = callback;
  80557. };
  80558. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  80559. if (newValue !== currentValue) {
  80560. if (newValue === 1) {
  80561. if (this._onbuttondown) {
  80562. this._onbuttondown(buttonIndex);
  80563. }
  80564. this.onButtonDownObservable.notifyObservers(buttonIndex);
  80565. }
  80566. if (newValue === 0) {
  80567. if (this._onbuttonup) {
  80568. this._onbuttonup(buttonIndex);
  80569. }
  80570. this.onButtonUpObservable.notifyObservers(buttonIndex);
  80571. }
  80572. }
  80573. return newValue;
  80574. };
  80575. /**
  80576. * Updates the generic gamepad
  80577. */
  80578. GenericPad.prototype.update = function () {
  80579. _super.prototype.update.call(this);
  80580. for (var index = 0; index < this._buttons.length; index++) {
  80581. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  80582. }
  80583. };
  80584. /**
  80585. * Disposes the generic gamepad
  80586. */
  80587. GenericPad.prototype.dispose = function () {
  80588. _super.prototype.dispose.call(this);
  80589. this.onButtonDownObservable.clear();
  80590. this.onButtonUpObservable.clear();
  80591. };
  80592. return GenericPad;
  80593. }(Gamepad));
  80594. BABYLON.GenericPad = GenericPad;
  80595. })(BABYLON || (BABYLON = {}));
  80596. //# sourceMappingURL=babylon.gamepad.js.map
  80597. var BABYLON;
  80598. (function (BABYLON) {
  80599. /**
  80600. * Defines supported buttons for XBox360 compatible gamepads
  80601. */
  80602. var Xbox360Button;
  80603. (function (Xbox360Button) {
  80604. /** A */
  80605. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  80606. /** B */
  80607. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  80608. /** X */
  80609. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  80610. /** Y */
  80611. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  80612. /** Start */
  80613. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  80614. /** Back */
  80615. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  80616. /** Left button */
  80617. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  80618. /** Right button */
  80619. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  80620. /** Left stick */
  80621. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  80622. /** Right stick */
  80623. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  80624. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  80625. /** Defines values for XBox360 DPad */
  80626. var Xbox360Dpad;
  80627. (function (Xbox360Dpad) {
  80628. /** Up */
  80629. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  80630. /** Down */
  80631. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  80632. /** Left */
  80633. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  80634. /** Right */
  80635. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  80636. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  80637. /**
  80638. * Defines a XBox360 gamepad
  80639. */
  80640. var Xbox360Pad = /** @class */ (function (_super) {
  80641. __extends(Xbox360Pad, _super);
  80642. /**
  80643. * Creates a new XBox360 gamepad object
  80644. * @param id defines the id of this gamepad
  80645. * @param index defines its index
  80646. * @param gamepad defines the internal HTML gamepad object
  80647. * @param xboxOne defines if it is a XBox One gamepad
  80648. */
  80649. function Xbox360Pad(id, index, gamepad, xboxOne) {
  80650. if (xboxOne === void 0) { xboxOne = false; }
  80651. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  80652. _this._leftTrigger = 0;
  80653. _this._rightTrigger = 0;
  80654. /** Observable raised when a button is pressed */
  80655. _this.onButtonDownObservable = new BABYLON.Observable();
  80656. /** Observable raised when a button is released */
  80657. _this.onButtonUpObservable = new BABYLON.Observable();
  80658. /** Observable raised when a pad is pressed */
  80659. _this.onPadDownObservable = new BABYLON.Observable();
  80660. /** Observable raised when a pad is released */
  80661. _this.onPadUpObservable = new BABYLON.Observable();
  80662. _this._buttonA = 0;
  80663. _this._buttonB = 0;
  80664. _this._buttonX = 0;
  80665. _this._buttonY = 0;
  80666. _this._buttonBack = 0;
  80667. _this._buttonStart = 0;
  80668. _this._buttonLB = 0;
  80669. _this._buttonRB = 0;
  80670. _this._buttonLeftStick = 0;
  80671. _this._buttonRightStick = 0;
  80672. _this._dPadUp = 0;
  80673. _this._dPadDown = 0;
  80674. _this._dPadLeft = 0;
  80675. _this._dPadRight = 0;
  80676. _this._isXboxOnePad = false;
  80677. _this.type = BABYLON.Gamepad.XBOX;
  80678. _this._isXboxOnePad = xboxOne;
  80679. return _this;
  80680. }
  80681. /**
  80682. * Defines the callback to call when left trigger is pressed
  80683. * @param callback defines the callback to use
  80684. */
  80685. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  80686. this._onlefttriggerchanged = callback;
  80687. };
  80688. /**
  80689. * Defines the callback to call when right trigger is pressed
  80690. * @param callback defines the callback to use
  80691. */
  80692. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  80693. this._onrighttriggerchanged = callback;
  80694. };
  80695. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  80696. /**
  80697. * Gets the left trigger value
  80698. */
  80699. get: function () {
  80700. return this._leftTrigger;
  80701. },
  80702. /**
  80703. * Sets the left trigger value
  80704. */
  80705. set: function (newValue) {
  80706. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  80707. this._onlefttriggerchanged(newValue);
  80708. }
  80709. this._leftTrigger = newValue;
  80710. },
  80711. enumerable: true,
  80712. configurable: true
  80713. });
  80714. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  80715. /**
  80716. * Gets the right trigger value
  80717. */
  80718. get: function () {
  80719. return this._rightTrigger;
  80720. },
  80721. /**
  80722. * Sets the right trigger value
  80723. */
  80724. set: function (newValue) {
  80725. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  80726. this._onrighttriggerchanged(newValue);
  80727. }
  80728. this._rightTrigger = newValue;
  80729. },
  80730. enumerable: true,
  80731. configurable: true
  80732. });
  80733. /**
  80734. * Defines the callback to call when a button is pressed
  80735. * @param callback defines the callback to use
  80736. */
  80737. Xbox360Pad.prototype.onbuttondown = function (callback) {
  80738. this._onbuttondown = callback;
  80739. };
  80740. /**
  80741. * Defines the callback to call when a button is released
  80742. * @param callback defines the callback to use
  80743. */
  80744. Xbox360Pad.prototype.onbuttonup = function (callback) {
  80745. this._onbuttonup = callback;
  80746. };
  80747. /**
  80748. * Defines the callback to call when a pad is pressed
  80749. * @param callback defines the callback to use
  80750. */
  80751. Xbox360Pad.prototype.ondpaddown = function (callback) {
  80752. this._ondpaddown = callback;
  80753. };
  80754. /**
  80755. * Defines the callback to call when a pad is released
  80756. * @param callback defines the callback to use
  80757. */
  80758. Xbox360Pad.prototype.ondpadup = function (callback) {
  80759. this._ondpadup = callback;
  80760. };
  80761. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  80762. if (newValue !== currentValue) {
  80763. if (newValue === 1) {
  80764. if (this._onbuttondown) {
  80765. this._onbuttondown(buttonType);
  80766. }
  80767. this.onButtonDownObservable.notifyObservers(buttonType);
  80768. }
  80769. if (newValue === 0) {
  80770. if (this._onbuttonup) {
  80771. this._onbuttonup(buttonType);
  80772. }
  80773. this.onButtonUpObservable.notifyObservers(buttonType);
  80774. }
  80775. }
  80776. return newValue;
  80777. };
  80778. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  80779. if (newValue !== currentValue) {
  80780. if (newValue === 1) {
  80781. if (this._ondpaddown) {
  80782. this._ondpaddown(buttonType);
  80783. }
  80784. this.onPadDownObservable.notifyObservers(buttonType);
  80785. }
  80786. if (newValue === 0) {
  80787. if (this._ondpadup) {
  80788. this._ondpadup(buttonType);
  80789. }
  80790. this.onPadUpObservable.notifyObservers(buttonType);
  80791. }
  80792. }
  80793. return newValue;
  80794. };
  80795. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  80796. /**
  80797. * Gets the value of the `A` button
  80798. */
  80799. get: function () {
  80800. return this._buttonA;
  80801. },
  80802. /**
  80803. * Sets the value of the `A` button
  80804. */
  80805. set: function (value) {
  80806. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  80807. },
  80808. enumerable: true,
  80809. configurable: true
  80810. });
  80811. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  80812. /**
  80813. * Gets the value of the `B` button
  80814. */
  80815. get: function () {
  80816. return this._buttonB;
  80817. },
  80818. /**
  80819. * Sets the value of the `B` button
  80820. */
  80821. set: function (value) {
  80822. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  80823. },
  80824. enumerable: true,
  80825. configurable: true
  80826. });
  80827. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  80828. /**
  80829. * Gets the value of the `X` button
  80830. */
  80831. get: function () {
  80832. return this._buttonX;
  80833. },
  80834. /**
  80835. * Sets the value of the `X` button
  80836. */
  80837. set: function (value) {
  80838. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  80839. },
  80840. enumerable: true,
  80841. configurable: true
  80842. });
  80843. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  80844. /**
  80845. * Gets the value of the `Y` button
  80846. */
  80847. get: function () {
  80848. return this._buttonY;
  80849. },
  80850. /**
  80851. * Sets the value of the `Y` button
  80852. */
  80853. set: function (value) {
  80854. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  80855. },
  80856. enumerable: true,
  80857. configurable: true
  80858. });
  80859. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  80860. /**
  80861. * Gets the value of the `Start` button
  80862. */
  80863. get: function () {
  80864. return this._buttonStart;
  80865. },
  80866. /**
  80867. * Sets the value of the `Start` button
  80868. */
  80869. set: function (value) {
  80870. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  80871. },
  80872. enumerable: true,
  80873. configurable: true
  80874. });
  80875. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  80876. /**
  80877. * Gets the value of the `Back` button
  80878. */
  80879. get: function () {
  80880. return this._buttonBack;
  80881. },
  80882. /**
  80883. * Sets the value of the `Back` button
  80884. */
  80885. set: function (value) {
  80886. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  80887. },
  80888. enumerable: true,
  80889. configurable: true
  80890. });
  80891. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  80892. /**
  80893. * Gets the value of the `Left` button
  80894. */
  80895. get: function () {
  80896. return this._buttonLB;
  80897. },
  80898. /**
  80899. * Sets the value of the `Left` button
  80900. */
  80901. set: function (value) {
  80902. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  80903. },
  80904. enumerable: true,
  80905. configurable: true
  80906. });
  80907. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  80908. /**
  80909. * Gets the value of the `Right` button
  80910. */
  80911. get: function () {
  80912. return this._buttonRB;
  80913. },
  80914. /**
  80915. * Sets the value of the `Right` button
  80916. */
  80917. set: function (value) {
  80918. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  80919. },
  80920. enumerable: true,
  80921. configurable: true
  80922. });
  80923. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  80924. /**
  80925. * Gets the value of the Left joystick
  80926. */
  80927. get: function () {
  80928. return this._buttonLeftStick;
  80929. },
  80930. /**
  80931. * Sets the value of the Left joystick
  80932. */
  80933. set: function (value) {
  80934. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  80935. },
  80936. enumerable: true,
  80937. configurable: true
  80938. });
  80939. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  80940. /**
  80941. * Gets the value of the Right joystick
  80942. */
  80943. get: function () {
  80944. return this._buttonRightStick;
  80945. },
  80946. /**
  80947. * Sets the value of the Right joystick
  80948. */
  80949. set: function (value) {
  80950. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  80951. },
  80952. enumerable: true,
  80953. configurable: true
  80954. });
  80955. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  80956. /**
  80957. * Gets the value of D-pad up
  80958. */
  80959. get: function () {
  80960. return this._dPadUp;
  80961. },
  80962. /**
  80963. * Sets the value of D-pad up
  80964. */
  80965. set: function (value) {
  80966. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  80967. },
  80968. enumerable: true,
  80969. configurable: true
  80970. });
  80971. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  80972. /**
  80973. * Gets the value of D-pad down
  80974. */
  80975. get: function () {
  80976. return this._dPadDown;
  80977. },
  80978. /**
  80979. * Sets the value of D-pad down
  80980. */
  80981. set: function (value) {
  80982. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  80983. },
  80984. enumerable: true,
  80985. configurable: true
  80986. });
  80987. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  80988. /**
  80989. * Gets the value of D-pad left
  80990. */
  80991. get: function () {
  80992. return this._dPadLeft;
  80993. },
  80994. /**
  80995. * Sets the value of D-pad left
  80996. */
  80997. set: function (value) {
  80998. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  80999. },
  81000. enumerable: true,
  81001. configurable: true
  81002. });
  81003. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  81004. /**
  81005. * Gets the value of D-pad right
  81006. */
  81007. get: function () {
  81008. return this._dPadRight;
  81009. },
  81010. /**
  81011. * Sets the value of D-pad right
  81012. */
  81013. set: function (value) {
  81014. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  81015. },
  81016. enumerable: true,
  81017. configurable: true
  81018. });
  81019. /**
  81020. * Force the gamepad to synchronize with device values
  81021. */
  81022. Xbox360Pad.prototype.update = function () {
  81023. _super.prototype.update.call(this);
  81024. if (this._isXboxOnePad) {
  81025. this.buttonA = this.browserGamepad.buttons[0].value;
  81026. this.buttonB = this.browserGamepad.buttons[1].value;
  81027. this.buttonX = this.browserGamepad.buttons[2].value;
  81028. this.buttonY = this.browserGamepad.buttons[3].value;
  81029. this.buttonLB = this.browserGamepad.buttons[4].value;
  81030. this.buttonRB = this.browserGamepad.buttons[5].value;
  81031. this.leftTrigger = this.browserGamepad.axes[2];
  81032. this.rightTrigger = this.browserGamepad.axes[5];
  81033. this.buttonBack = this.browserGamepad.buttons[9].value;
  81034. this.buttonStart = this.browserGamepad.buttons[8].value;
  81035. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  81036. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  81037. this.dPadUp = this.browserGamepad.buttons[11].value;
  81038. this.dPadDown = this.browserGamepad.buttons[12].value;
  81039. this.dPadLeft = this.browserGamepad.buttons[13].value;
  81040. this.dPadRight = this.browserGamepad.buttons[14].value;
  81041. }
  81042. else {
  81043. this.buttonA = this.browserGamepad.buttons[0].value;
  81044. this.buttonB = this.browserGamepad.buttons[1].value;
  81045. this.buttonX = this.browserGamepad.buttons[2].value;
  81046. this.buttonY = this.browserGamepad.buttons[3].value;
  81047. this.buttonLB = this.browserGamepad.buttons[4].value;
  81048. this.buttonRB = this.browserGamepad.buttons[5].value;
  81049. this.leftTrigger = this.browserGamepad.buttons[6].value;
  81050. this.rightTrigger = this.browserGamepad.buttons[7].value;
  81051. this.buttonBack = this.browserGamepad.buttons[8].value;
  81052. this.buttonStart = this.browserGamepad.buttons[9].value;
  81053. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  81054. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  81055. this.dPadUp = this.browserGamepad.buttons[12].value;
  81056. this.dPadDown = this.browserGamepad.buttons[13].value;
  81057. this.dPadLeft = this.browserGamepad.buttons[14].value;
  81058. this.dPadRight = this.browserGamepad.buttons[15].value;
  81059. }
  81060. };
  81061. /**
  81062. * Disposes the gamepad
  81063. */
  81064. Xbox360Pad.prototype.dispose = function () {
  81065. _super.prototype.dispose.call(this);
  81066. this.onButtonDownObservable.clear();
  81067. this.onButtonUpObservable.clear();
  81068. this.onPadDownObservable.clear();
  81069. this.onPadUpObservable.clear();
  81070. };
  81071. return Xbox360Pad;
  81072. }(BABYLON.Gamepad));
  81073. BABYLON.Xbox360Pad = Xbox360Pad;
  81074. })(BABYLON || (BABYLON = {}));
  81075. //# sourceMappingURL=babylon.xboxGamepad.js.map
  81076. var BABYLON;
  81077. (function (BABYLON) {
  81078. /**
  81079. * Defines the types of pose enabled controllers that are supported
  81080. */
  81081. var PoseEnabledControllerType;
  81082. (function (PoseEnabledControllerType) {
  81083. /**
  81084. * HTC Vive
  81085. */
  81086. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  81087. /**
  81088. * Oculus Rift
  81089. */
  81090. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  81091. /**
  81092. * Windows mixed reality
  81093. */
  81094. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  81095. /**
  81096. * Samsung gear VR
  81097. */
  81098. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  81099. /**
  81100. * Google Daydream
  81101. */
  81102. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  81103. /**
  81104. * Generic
  81105. */
  81106. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  81107. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  81108. /**
  81109. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  81110. */
  81111. var PoseEnabledControllerHelper = /** @class */ (function () {
  81112. function PoseEnabledControllerHelper() {
  81113. }
  81114. /**
  81115. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  81116. * @param vrGamepad the gamepad to initialized
  81117. * @returns a vr controller of the type the gamepad identified as
  81118. */
  81119. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  81120. // Oculus Touch
  81121. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  81122. return new BABYLON.OculusTouchController(vrGamepad);
  81123. }
  81124. // Windows Mixed Reality controllers
  81125. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  81126. return new BABYLON.WindowsMotionController(vrGamepad);
  81127. }
  81128. // HTC Vive
  81129. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  81130. return new BABYLON.ViveController(vrGamepad);
  81131. }
  81132. // Samsung/Oculus Gear VR or Oculus Go
  81133. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  81134. return new BABYLON.GearVRController(vrGamepad);
  81135. }
  81136. // Google Daydream
  81137. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  81138. return new BABYLON.DaydreamController(vrGamepad);
  81139. }
  81140. // Generic
  81141. else {
  81142. return new BABYLON.GenericController(vrGamepad);
  81143. }
  81144. };
  81145. return PoseEnabledControllerHelper;
  81146. }());
  81147. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  81148. /**
  81149. * Defines the PoseEnabledController object that contains state of a vr capable controller
  81150. */
  81151. var PoseEnabledController = /** @class */ (function (_super) {
  81152. __extends(PoseEnabledController, _super);
  81153. /**
  81154. * Creates a new PoseEnabledController from a gamepad
  81155. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  81156. */
  81157. function PoseEnabledController(browserGamepad) {
  81158. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  81159. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  81160. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  81161. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  81162. /**
  81163. * The device position in babylon space
  81164. */
  81165. _this.devicePosition = BABYLON.Vector3.Zero();
  81166. /**
  81167. * The device rotation in babylon space
  81168. */
  81169. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  81170. /**
  81171. * The scale factor of the device in babylon space
  81172. */
  81173. _this.deviceScaleFactor = 1;
  81174. // Used to convert 6dof controllers to 3dof
  81175. _this._trackPosition = true;
  81176. _this._maxRotationDistFromHeadset = Math.PI / 5;
  81177. _this._draggedRoomRotation = 0;
  81178. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  81179. /**
  81180. * Internal, matrix used to convert room space to babylon space
  81181. * @hidden
  81182. */
  81183. _this._deviceToWorld = BABYLON.Matrix.Identity();
  81184. /**
  81185. * Node to be used when casting a ray from the controller
  81186. * @hidden
  81187. */
  81188. _this._pointingPoseNode = null;
  81189. _this._workingMatrix = BABYLON.Matrix.Identity();
  81190. /**
  81191. * @hidden
  81192. */
  81193. _this._meshAttachedObservable = new BABYLON.Observable();
  81194. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  81195. _this.controllerType = PoseEnabledControllerType.GENERIC;
  81196. _this.position = BABYLON.Vector3.Zero();
  81197. _this.rotationQuaternion = new BABYLON.Quaternion();
  81198. _this._calculatedPosition = BABYLON.Vector3.Zero();
  81199. _this._calculatedRotation = new BABYLON.Quaternion();
  81200. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  81201. return _this;
  81202. }
  81203. /**
  81204. * @hidden
  81205. */
  81206. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  81207. if (this._trackPosition) {
  81208. this._calculatedPosition.copyFrom(fixedPosition);
  81209. this._trackPosition = false;
  81210. }
  81211. };
  81212. /**
  81213. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  81214. */
  81215. PoseEnabledController.prototype.update = function () {
  81216. _super.prototype.update.call(this);
  81217. this._updatePoseAndMesh();
  81218. };
  81219. /**
  81220. * Updates only the pose device and mesh without doing any button event checking
  81221. */
  81222. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  81223. var pose = this.browserGamepad.pose;
  81224. this.updateFromDevice(pose);
  81225. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  81226. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  81227. camera._computeDevicePosition();
  81228. this._deviceToWorld.setTranslation(camera.devicePosition);
  81229. if (camera.deviceRotationQuaternion) {
  81230. var camera = camera;
  81231. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  81232. // Find the radian distance away that the headset is from the controllers rotation
  81233. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  81234. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  81235. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  81236. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  81237. this._draggedRoomRotation += rotationAmount;
  81238. // Rotate controller around headset
  81239. var sin = Math.sin(-rotationAmount);
  81240. var cos = Math.cos(-rotationAmount);
  81241. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  81242. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  81243. }
  81244. }
  81245. }
  81246. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  81247. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  81248. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  81249. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  81250. if (this._mesh) {
  81251. this._mesh.position.copyFrom(this.devicePosition);
  81252. if (this._mesh.rotationQuaternion) {
  81253. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  81254. }
  81255. }
  81256. };
  81257. /**
  81258. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  81259. * @param poseData raw pose fromthe device
  81260. */
  81261. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  81262. if (poseData) {
  81263. this.rawPose = poseData;
  81264. if (poseData.position) {
  81265. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  81266. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  81267. this._deviceRoomPosition.z *= -1;
  81268. }
  81269. if (this._trackPosition) {
  81270. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  81271. }
  81272. this._calculatedPosition.addInPlace(this.position);
  81273. }
  81274. var pose = this.rawPose;
  81275. if (poseData.orientation && pose.orientation) {
  81276. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  81277. if (this._mesh) {
  81278. if (this._mesh.getScene().useRightHandedSystem) {
  81279. this._deviceRoomRotationQuaternion.z *= -1;
  81280. this._deviceRoomRotationQuaternion.w *= -1;
  81281. }
  81282. else {
  81283. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  81284. }
  81285. }
  81286. // if the camera is set, rotate to the camera's rotation
  81287. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  81288. }
  81289. }
  81290. };
  81291. /**
  81292. * Attaches a mesh to the controller
  81293. * @param mesh the mesh to be attached
  81294. */
  81295. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  81296. if (this._mesh) {
  81297. this._mesh.parent = null;
  81298. }
  81299. this._mesh = mesh;
  81300. if (this._poseControlledCamera) {
  81301. this._mesh.parent = this._poseControlledCamera;
  81302. }
  81303. if (!this._mesh.rotationQuaternion) {
  81304. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  81305. }
  81306. // 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
  81307. this._updatePoseAndMesh();
  81308. if (this._pointingPoseNode) {
  81309. var parents = [];
  81310. var obj = this._pointingPoseNode;
  81311. while (obj.parent) {
  81312. parents.push(obj.parent);
  81313. obj = obj.parent;
  81314. }
  81315. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  81316. }
  81317. this._meshAttachedObservable.notifyObservers(mesh);
  81318. };
  81319. /**
  81320. * Attaches the controllers mesh to a camera
  81321. * @param camera the camera the mesh should be attached to
  81322. */
  81323. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  81324. this._poseControlledCamera = camera;
  81325. if (this._mesh) {
  81326. this._mesh.parent = this._poseControlledCamera;
  81327. }
  81328. };
  81329. /**
  81330. * Disposes of the controller
  81331. */
  81332. PoseEnabledController.prototype.dispose = function () {
  81333. if (this._mesh) {
  81334. this._mesh.dispose();
  81335. }
  81336. this._mesh = null;
  81337. _super.prototype.dispose.call(this);
  81338. };
  81339. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  81340. /**
  81341. * The mesh that is attached to the controller
  81342. */
  81343. get: function () {
  81344. return this._mesh;
  81345. },
  81346. enumerable: true,
  81347. configurable: true
  81348. });
  81349. /**
  81350. * Gets the ray of the controller in the direction the controller is pointing
  81351. * @param length the length the resulting ray should be
  81352. * @returns a ray in the direction the controller is pointing
  81353. */
  81354. PoseEnabledController.prototype.getForwardRay = function (length) {
  81355. if (length === void 0) { length = 100; }
  81356. if (!this.mesh) {
  81357. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  81358. }
  81359. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  81360. var origin = m.getTranslation();
  81361. var forward = new BABYLON.Vector3(0, 0, -1);
  81362. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  81363. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  81364. return new BABYLON.Ray(origin, direction, length);
  81365. };
  81366. /**
  81367. * Name of the child mesh that can be used to cast a ray from the controller
  81368. */
  81369. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  81370. return PoseEnabledController;
  81371. }(BABYLON.Gamepad));
  81372. BABYLON.PoseEnabledController = PoseEnabledController;
  81373. })(BABYLON || (BABYLON = {}));
  81374. //# sourceMappingURL=babylon.poseEnabledController.js.map
  81375. var BABYLON;
  81376. (function (BABYLON) {
  81377. /**
  81378. * Defines the WebVRController object that represents controllers tracked in 3D space
  81379. */
  81380. var WebVRController = /** @class */ (function (_super) {
  81381. __extends(WebVRController, _super);
  81382. /**
  81383. * Creates a new WebVRController from a gamepad
  81384. * @param vrGamepad the gamepad that the WebVRController should be created from
  81385. */
  81386. function WebVRController(vrGamepad) {
  81387. var _this = _super.call(this, vrGamepad) || this;
  81388. // Observables
  81389. /**
  81390. * Fired when the trigger state has changed
  81391. */
  81392. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  81393. /**
  81394. * Fired when the main button state has changed
  81395. */
  81396. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  81397. /**
  81398. * Fired when the secondary button state has changed
  81399. */
  81400. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  81401. /**
  81402. * Fired when the pad state has changed
  81403. */
  81404. _this.onPadStateChangedObservable = new BABYLON.Observable();
  81405. /**
  81406. * Fired when controllers stick values have changed
  81407. */
  81408. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  81409. /**
  81410. * X and Y axis corrisponding to the controllers joystick
  81411. */
  81412. _this.pad = { x: 0, y: 0 };
  81413. // avoid GC, store state in a tmp object
  81414. _this._changes = {
  81415. pressChanged: false,
  81416. touchChanged: false,
  81417. valueChanged: false,
  81418. changed: false
  81419. };
  81420. _this._buttons = new Array(vrGamepad.buttons.length);
  81421. _this.hand = vrGamepad.hand;
  81422. return _this;
  81423. }
  81424. /**
  81425. * Fired when a controller button's state has changed
  81426. * @param callback the callback containing the button that was modified
  81427. */
  81428. WebVRController.prototype.onButtonStateChange = function (callback) {
  81429. this._onButtonStateChange = callback;
  81430. };
  81431. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  81432. /**
  81433. * The default controller model for the controller
  81434. */
  81435. get: function () {
  81436. return this._defaultModel;
  81437. },
  81438. enumerable: true,
  81439. configurable: true
  81440. });
  81441. /**
  81442. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  81443. */
  81444. WebVRController.prototype.update = function () {
  81445. _super.prototype.update.call(this);
  81446. for (var index = 0; index < this._buttons.length; index++) {
  81447. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  81448. }
  81449. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  81450. this.pad.x = this.leftStick.x;
  81451. this.pad.y = this.leftStick.y;
  81452. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  81453. }
  81454. };
  81455. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  81456. if (!newState) {
  81457. newState = {
  81458. pressed: false,
  81459. touched: false,
  81460. value: 0
  81461. };
  81462. }
  81463. if (!currentState) {
  81464. this._buttons[buttonIndex] = {
  81465. pressed: newState.pressed,
  81466. touched: newState.touched,
  81467. value: newState.value
  81468. };
  81469. return;
  81470. }
  81471. this._checkChanges(newState, currentState);
  81472. if (this._changes.changed) {
  81473. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  81474. this._handleButtonChange(buttonIndex, newState, this._changes);
  81475. }
  81476. this._buttons[buttonIndex].pressed = newState.pressed;
  81477. this._buttons[buttonIndex].touched = newState.touched;
  81478. // oculus triggers are never 0, thou not touched.
  81479. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  81480. };
  81481. WebVRController.prototype._checkChanges = function (newState, currentState) {
  81482. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  81483. this._changes.touchChanged = newState.touched !== currentState.touched;
  81484. this._changes.valueChanged = newState.value !== currentState.value;
  81485. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  81486. return this._changes;
  81487. };
  81488. /**
  81489. * Disposes of th webVRCOntroller
  81490. */
  81491. WebVRController.prototype.dispose = function () {
  81492. _super.prototype.dispose.call(this);
  81493. this.onTriggerStateChangedObservable.clear();
  81494. this.onMainButtonStateChangedObservable.clear();
  81495. this.onSecondaryButtonStateChangedObservable.clear();
  81496. this.onPadStateChangedObservable.clear();
  81497. this.onPadValuesChangedObservable.clear();
  81498. };
  81499. return WebVRController;
  81500. }(BABYLON.PoseEnabledController));
  81501. BABYLON.WebVRController = WebVRController;
  81502. })(BABYLON || (BABYLON = {}));
  81503. //# sourceMappingURL=babylon.webVRController.js.map
  81504. var BABYLON;
  81505. (function (BABYLON) {
  81506. /**
  81507. * Oculus Touch Controller
  81508. */
  81509. var OculusTouchController = /** @class */ (function (_super) {
  81510. __extends(OculusTouchController, _super);
  81511. /**
  81512. * Creates a new OculusTouchController from a gamepad
  81513. * @param vrGamepad the gamepad that the controller should be created from
  81514. */
  81515. function OculusTouchController(vrGamepad) {
  81516. var _this = _super.call(this, vrGamepad) || this;
  81517. /**
  81518. * Fired when the secondary trigger on this controller is modified
  81519. */
  81520. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  81521. /**
  81522. * Fired when the thumb rest on this controller is modified
  81523. */
  81524. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  81525. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  81526. return _this;
  81527. }
  81528. /**
  81529. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81530. * @param scene scene in which to add meshes
  81531. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81532. */
  81533. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81534. var _this = this;
  81535. var meshName;
  81536. // Hand
  81537. if (this.hand === 'left') {
  81538. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  81539. }
  81540. else { // Right is the default if no hand is specified
  81541. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  81542. }
  81543. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  81544. /*
  81545. Parent Mesh name: oculus_touch_left
  81546. - body
  81547. - trigger
  81548. - thumbstick
  81549. - grip
  81550. - button_y
  81551. - button_x
  81552. - button_enter
  81553. */
  81554. _this._defaultModel = newMeshes[1];
  81555. _this.attachToMesh(_this._defaultModel);
  81556. if (meshLoaded) {
  81557. meshLoaded(_this._defaultModel);
  81558. }
  81559. });
  81560. };
  81561. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  81562. /**
  81563. * Fired when the A button on this controller is modified
  81564. */
  81565. get: function () {
  81566. if (this.hand === 'right') {
  81567. return this.onMainButtonStateChangedObservable;
  81568. }
  81569. else {
  81570. throw new Error('No A button on left hand');
  81571. }
  81572. },
  81573. enumerable: true,
  81574. configurable: true
  81575. });
  81576. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  81577. /**
  81578. * Fired when the B button on this controller is modified
  81579. */
  81580. get: function () {
  81581. if (this.hand === 'right') {
  81582. return this.onSecondaryButtonStateChangedObservable;
  81583. }
  81584. else {
  81585. throw new Error('No B button on left hand');
  81586. }
  81587. },
  81588. enumerable: true,
  81589. configurable: true
  81590. });
  81591. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  81592. /**
  81593. * Fired when the X button on this controller is modified
  81594. */
  81595. get: function () {
  81596. if (this.hand === 'left') {
  81597. return this.onMainButtonStateChangedObservable;
  81598. }
  81599. else {
  81600. throw new Error('No X button on right hand');
  81601. }
  81602. },
  81603. enumerable: true,
  81604. configurable: true
  81605. });
  81606. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  81607. /**
  81608. * Fired when the Y button on this controller is modified
  81609. */
  81610. get: function () {
  81611. if (this.hand === 'left') {
  81612. return this.onSecondaryButtonStateChangedObservable;
  81613. }
  81614. else {
  81615. throw new Error('No Y button on right hand');
  81616. }
  81617. },
  81618. enumerable: true,
  81619. configurable: true
  81620. });
  81621. /**
  81622. * Called once for each button that changed state since the last frame
  81623. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  81624. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  81625. * 2) secondary trigger (same)
  81626. * 3) A (right) X (left), touch, pressed = value
  81627. * 4) B / Y
  81628. * 5) thumb rest
  81629. * @param buttonIdx Which button index changed
  81630. * @param state New state of the button
  81631. * @param changes Which properties on the state changed since last frame
  81632. */
  81633. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81634. var notifyObject = state; //{ state: state, changes: changes };
  81635. var triggerDirection = this.hand === 'right' ? -1 : 1;
  81636. switch (buttonIdx) {
  81637. case 0:
  81638. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  81639. return;
  81640. case 1: // index trigger
  81641. if (this._defaultModel) {
  81642. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  81643. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  81644. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  81645. }
  81646. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  81647. return;
  81648. case 2: // secondary trigger
  81649. if (this._defaultModel) {
  81650. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  81651. }
  81652. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  81653. return;
  81654. case 3:
  81655. if (this._defaultModel) {
  81656. if (notifyObject.pressed) {
  81657. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  81658. }
  81659. else {
  81660. (this._defaultModel.getChildren()[1]).position.y = 0;
  81661. }
  81662. }
  81663. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  81664. return;
  81665. case 4:
  81666. if (this._defaultModel) {
  81667. if (notifyObject.pressed) {
  81668. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  81669. }
  81670. else {
  81671. (this._defaultModel.getChildren()[2]).position.y = 0;
  81672. }
  81673. }
  81674. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  81675. return;
  81676. case 5:
  81677. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  81678. return;
  81679. }
  81680. };
  81681. /**
  81682. * Base Url for the controller model.
  81683. */
  81684. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  81685. /**
  81686. * File name for the left controller model.
  81687. */
  81688. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  81689. /**
  81690. * File name for the right controller model.
  81691. */
  81692. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  81693. return OculusTouchController;
  81694. }(BABYLON.WebVRController));
  81695. BABYLON.OculusTouchController = OculusTouchController;
  81696. })(BABYLON || (BABYLON = {}));
  81697. //# sourceMappingURL=babylon.oculusTouchController.js.map
  81698. var BABYLON;
  81699. (function (BABYLON) {
  81700. /**
  81701. * Vive Controller
  81702. */
  81703. var ViveController = /** @class */ (function (_super) {
  81704. __extends(ViveController, _super);
  81705. /**
  81706. * Creates a new ViveController from a gamepad
  81707. * @param vrGamepad the gamepad that the controller should be created from
  81708. */
  81709. function ViveController(vrGamepad) {
  81710. var _this = _super.call(this, vrGamepad) || this;
  81711. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  81712. _this._invertLeftStickY = true;
  81713. return _this;
  81714. }
  81715. /**
  81716. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81717. * @param scene scene in which to add meshes
  81718. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81719. */
  81720. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81721. var _this = this;
  81722. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  81723. /*
  81724. Parent Mesh name: ViveWand
  81725. - body
  81726. - r_gripper
  81727. - l_gripper
  81728. - menu_button
  81729. - system_button
  81730. - trackpad
  81731. - trigger
  81732. - LED
  81733. */
  81734. _this._defaultModel = newMeshes[1];
  81735. _this.attachToMesh(_this._defaultModel);
  81736. if (meshLoaded) {
  81737. meshLoaded(_this._defaultModel);
  81738. }
  81739. });
  81740. };
  81741. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  81742. /**
  81743. * Fired when the left button on this controller is modified
  81744. */
  81745. get: function () {
  81746. return this.onMainButtonStateChangedObservable;
  81747. },
  81748. enumerable: true,
  81749. configurable: true
  81750. });
  81751. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  81752. /**
  81753. * Fired when the right button on this controller is modified
  81754. */
  81755. get: function () {
  81756. return this.onMainButtonStateChangedObservable;
  81757. },
  81758. enumerable: true,
  81759. configurable: true
  81760. });
  81761. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  81762. /**
  81763. * Fired when the menu button on this controller is modified
  81764. */
  81765. get: function () {
  81766. return this.onSecondaryButtonStateChangedObservable;
  81767. },
  81768. enumerable: true,
  81769. configurable: true
  81770. });
  81771. /**
  81772. * Called once for each button that changed state since the last frame
  81773. * Vive mapping:
  81774. * 0: touchpad
  81775. * 1: trigger
  81776. * 2: left AND right buttons
  81777. * 3: menu button
  81778. * @param buttonIdx Which button index changed
  81779. * @param state New state of the button
  81780. * @param changes Which properties on the state changed since last frame
  81781. */
  81782. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81783. var notifyObject = state; //{ state: state, changes: changes };
  81784. switch (buttonIdx) {
  81785. case 0:
  81786. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  81787. return;
  81788. case 1: // index trigger
  81789. if (this._defaultModel) {
  81790. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  81791. }
  81792. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  81793. return;
  81794. case 2: // left AND right button
  81795. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  81796. return;
  81797. case 3:
  81798. if (this._defaultModel) {
  81799. if (notifyObject.pressed) {
  81800. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  81801. }
  81802. else {
  81803. (this._defaultModel.getChildren()[2]).position.y = 0;
  81804. }
  81805. }
  81806. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  81807. return;
  81808. }
  81809. };
  81810. /**
  81811. * Base Url for the controller model.
  81812. */
  81813. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  81814. /**
  81815. * File name for the controller model.
  81816. */
  81817. ViveController.MODEL_FILENAME = 'wand.babylon';
  81818. return ViveController;
  81819. }(BABYLON.WebVRController));
  81820. BABYLON.ViveController = ViveController;
  81821. })(BABYLON || (BABYLON = {}));
  81822. //# sourceMappingURL=babylon.viveController.js.map
  81823. var BABYLON;
  81824. (function (BABYLON) {
  81825. /**
  81826. * Generic Controller
  81827. */
  81828. var GenericController = /** @class */ (function (_super) {
  81829. __extends(GenericController, _super);
  81830. /**
  81831. * Creates a new GenericController from a gamepad
  81832. * @param vrGamepad the gamepad that the controller should be created from
  81833. */
  81834. function GenericController(vrGamepad) {
  81835. return _super.call(this, vrGamepad) || this;
  81836. }
  81837. /**
  81838. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81839. * @param scene scene in which to add meshes
  81840. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81841. */
  81842. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81843. var _this = this;
  81844. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  81845. _this._defaultModel = newMeshes[1];
  81846. _this.attachToMesh(_this._defaultModel);
  81847. if (meshLoaded) {
  81848. meshLoaded(_this._defaultModel);
  81849. }
  81850. });
  81851. };
  81852. /**
  81853. * Called once for each button that changed state since the last frame
  81854. * @param buttonIdx Which button index changed
  81855. * @param state New state of the button
  81856. * @param changes Which properties on the state changed since last frame
  81857. */
  81858. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81859. console.log("Button id: " + buttonIdx + "state: ");
  81860. console.dir(state);
  81861. };
  81862. /**
  81863. * Base Url for the controller model.
  81864. */
  81865. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  81866. /**
  81867. * File name for the controller model.
  81868. */
  81869. GenericController.MODEL_FILENAME = 'generic.babylon';
  81870. return GenericController;
  81871. }(BABYLON.WebVRController));
  81872. BABYLON.GenericController = GenericController;
  81873. })(BABYLON || (BABYLON = {}));
  81874. //# sourceMappingURL=babylon.genericController.js.map
  81875. var BABYLON;
  81876. (function (BABYLON) {
  81877. /**
  81878. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  81879. */
  81880. var LoadedMeshInfo = /** @class */ (function () {
  81881. function LoadedMeshInfo() {
  81882. /**
  81883. * Map of the button meshes contained in the controller
  81884. */
  81885. this.buttonMeshes = {};
  81886. /**
  81887. * Map of the axis meshes contained in the controller
  81888. */
  81889. this.axisMeshes = {};
  81890. }
  81891. return LoadedMeshInfo;
  81892. }());
  81893. /**
  81894. * Defines the WindowsMotionController object that the state of the windows motion controller
  81895. */
  81896. var WindowsMotionController = /** @class */ (function (_super) {
  81897. __extends(WindowsMotionController, _super);
  81898. /**
  81899. * Creates a new WindowsMotionController from a gamepad
  81900. * @param vrGamepad the gamepad that the controller should be created from
  81901. */
  81902. function WindowsMotionController(vrGamepad) {
  81903. var _this = _super.call(this, vrGamepad) || this;
  81904. _this._mapping = {
  81905. // Semantic button names
  81906. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  81907. // A mapping of the button name to glTF model node name
  81908. // that should be transformed by button value.
  81909. buttonMeshNames: {
  81910. 'trigger': 'SELECT',
  81911. 'menu': 'MENU',
  81912. 'grip': 'GRASP',
  81913. 'thumbstick': 'THUMBSTICK_PRESS',
  81914. 'trackpad': 'TOUCHPAD_PRESS'
  81915. },
  81916. // This mapping is used to translate from the Motion Controller to Babylon semantics
  81917. buttonObservableNames: {
  81918. 'trigger': 'onTriggerStateChangedObservable',
  81919. 'menu': 'onSecondaryButtonStateChangedObservable',
  81920. 'grip': 'onMainButtonStateChangedObservable',
  81921. 'thumbstick': 'onPadStateChangedObservable',
  81922. 'trackpad': 'onTrackpadChangedObservable'
  81923. },
  81924. // A mapping of the axis name to glTF model node name
  81925. // that should be transformed by axis value.
  81926. // This array mirrors the browserGamepad.axes array, such that
  81927. // the mesh corresponding to axis 0 is in this array index 0.
  81928. axisMeshNames: [
  81929. 'THUMBSTICK_X',
  81930. 'THUMBSTICK_Y',
  81931. 'TOUCHPAD_TOUCH_X',
  81932. 'TOUCHPAD_TOUCH_Y'
  81933. ],
  81934. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  81935. };
  81936. /**
  81937. * Fired when the trackpad on this controller is clicked
  81938. */
  81939. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  81940. /**
  81941. * Fired when the trackpad on this controller is modified
  81942. */
  81943. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  81944. /**
  81945. * The current x and y values of this controller's trackpad
  81946. */
  81947. _this.trackpad = { x: 0, y: 0 };
  81948. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  81949. _this._loadedMeshInfo = null;
  81950. return _this;
  81951. }
  81952. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  81953. /**
  81954. * Fired when the trigger on this controller is modified
  81955. */
  81956. get: function () {
  81957. return this.onTriggerStateChangedObservable;
  81958. },
  81959. enumerable: true,
  81960. configurable: true
  81961. });
  81962. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  81963. /**
  81964. * Fired when the menu button on this controller is modified
  81965. */
  81966. get: function () {
  81967. return this.onSecondaryButtonStateChangedObservable;
  81968. },
  81969. enumerable: true,
  81970. configurable: true
  81971. });
  81972. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  81973. /**
  81974. * Fired when the grip button on this controller is modified
  81975. */
  81976. get: function () {
  81977. return this.onMainButtonStateChangedObservable;
  81978. },
  81979. enumerable: true,
  81980. configurable: true
  81981. });
  81982. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  81983. /**
  81984. * Fired when the thumbstick button on this controller is modified
  81985. */
  81986. get: function () {
  81987. return this.onPadStateChangedObservable;
  81988. },
  81989. enumerable: true,
  81990. configurable: true
  81991. });
  81992. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  81993. /**
  81994. * Fired when the touchpad button on this controller is modified
  81995. */
  81996. get: function () {
  81997. return this.onTrackpadChangedObservable;
  81998. },
  81999. enumerable: true,
  82000. configurable: true
  82001. });
  82002. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  82003. /**
  82004. * Fired when the touchpad values on this controller are modified
  82005. */
  82006. get: function () {
  82007. return this.onTrackpadValuesChangedObservable;
  82008. },
  82009. enumerable: true,
  82010. configurable: true
  82011. });
  82012. WindowsMotionController.prototype._updateTrackpad = function () {
  82013. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  82014. this.trackpad.x = this.browserGamepad["axes"][2];
  82015. this.trackpad.y = this.browserGamepad["axes"][3];
  82016. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  82017. }
  82018. };
  82019. /**
  82020. * Called once per frame by the engine.
  82021. */
  82022. WindowsMotionController.prototype.update = function () {
  82023. _super.prototype.update.call(this);
  82024. if (this.browserGamepad.axes) {
  82025. this._updateTrackpad();
  82026. // Only need to animate axes if there is a loaded mesh
  82027. if (this._loadedMeshInfo) {
  82028. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  82029. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  82030. }
  82031. }
  82032. }
  82033. };
  82034. /**
  82035. * Called once for each button that changed state since the last frame
  82036. * @param buttonIdx Which button index changed
  82037. * @param state New state of the button
  82038. * @param changes Which properties on the state changed since last frame
  82039. */
  82040. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82041. var buttonName = this._mapping.buttons[buttonIdx];
  82042. if (!buttonName) {
  82043. return;
  82044. }
  82045. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  82046. this._updateTrackpad();
  82047. // Only emit events for buttons that we know how to map from index to name
  82048. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  82049. if (observable) {
  82050. observable.notifyObservers(state);
  82051. }
  82052. this._lerpButtonTransform(buttonName, state.value);
  82053. };
  82054. /**
  82055. * Moves the buttons on the controller mesh based on their current state
  82056. * @param buttonName the name of the button to move
  82057. * @param buttonValue the value of the button which determines the buttons new position
  82058. */
  82059. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  82060. // If there is no loaded mesh, there is nothing to transform.
  82061. if (!this._loadedMeshInfo) {
  82062. return;
  82063. }
  82064. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  82065. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  82066. return;
  82067. }
  82068. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  82069. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  82070. };
  82071. /**
  82072. * Moves the axis on the controller mesh based on its current state
  82073. * @param axis the index of the axis
  82074. * @param axisValue the value of the axis which determines the meshes new position
  82075. * @hidden
  82076. */
  82077. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  82078. if (!this._loadedMeshInfo) {
  82079. return;
  82080. }
  82081. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  82082. if (!meshInfo) {
  82083. return;
  82084. }
  82085. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  82086. return;
  82087. }
  82088. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  82089. var lerpValue = axisValue * 0.5 + 0.5;
  82090. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  82091. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  82092. };
  82093. /**
  82094. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82095. * @param scene scene in which to add meshes
  82096. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82097. */
  82098. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  82099. var _this = this;
  82100. if (forceDefault === void 0) { forceDefault = false; }
  82101. var path;
  82102. var filename;
  82103. // Checking if GLB loader is present
  82104. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  82105. // Determine the device specific folder based on the ID suffix
  82106. var device = 'default';
  82107. if (this.id && !forceDefault) {
  82108. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  82109. device = ((match && match[0]) || device);
  82110. }
  82111. // Hand
  82112. if (this.hand === 'left') {
  82113. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  82114. }
  82115. else { // Right is the default if no hand is specified
  82116. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  82117. }
  82118. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  82119. }
  82120. else {
  82121. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  82122. path = BABYLON.GenericController.MODEL_BASE_URL;
  82123. filename = BABYLON.GenericController.MODEL_FILENAME;
  82124. }
  82125. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  82126. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  82127. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  82128. if (!_this._loadedMeshInfo) {
  82129. return;
  82130. }
  82131. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  82132. _this.attachToMesh(_this._defaultModel);
  82133. if (meshLoaded) {
  82134. meshLoaded(_this._defaultModel);
  82135. }
  82136. }, null, function (scene, message) {
  82137. BABYLON.Tools.Log(message);
  82138. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  82139. if (!forceDefault) {
  82140. _this.initControllerMesh(scene, meshLoaded, true);
  82141. }
  82142. });
  82143. };
  82144. /**
  82145. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  82146. * can be transformed by button presses and axes values, based on this._mapping.
  82147. *
  82148. * @param scene scene in which the meshes exist
  82149. * @param meshes list of meshes that make up the controller model to process
  82150. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  82151. */
  82152. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  82153. var loadedMeshInfo = null;
  82154. // Create a new mesh to contain the glTF hierarchy
  82155. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  82156. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  82157. var childMesh = null;
  82158. for (var i = 0; i < meshes.length; i++) {
  82159. var mesh = meshes[i];
  82160. if (!mesh.parent) {
  82161. // Exclude controller meshes from picking results
  82162. mesh.isPickable = false;
  82163. // Handle root node, attach to the new parentMesh
  82164. childMesh = mesh;
  82165. break;
  82166. }
  82167. }
  82168. if (childMesh) {
  82169. childMesh.setParent(parentMesh);
  82170. // Create our mesh info. Note that this method will always return non-null.
  82171. loadedMeshInfo = this.createMeshInfo(parentMesh);
  82172. }
  82173. else {
  82174. BABYLON.Tools.Warn('Could not find root node in model file.');
  82175. }
  82176. return loadedMeshInfo;
  82177. };
  82178. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  82179. var loadedMeshInfo = new LoadedMeshInfo();
  82180. var i;
  82181. loadedMeshInfo.rootNode = rootNode;
  82182. // Reset the caches
  82183. loadedMeshInfo.buttonMeshes = {};
  82184. loadedMeshInfo.axisMeshes = {};
  82185. // Button Meshes
  82186. for (i = 0; i < this._mapping.buttons.length; i++) {
  82187. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  82188. if (!buttonMeshName) {
  82189. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  82190. continue;
  82191. }
  82192. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  82193. if (!buttonMesh) {
  82194. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  82195. continue;
  82196. }
  82197. var buttonMeshInfo = {
  82198. index: i,
  82199. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  82200. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  82201. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  82202. };
  82203. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  82204. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  82205. }
  82206. else {
  82207. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  82208. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  82209. '(VALUE: ' + !!buttonMeshInfo.value +
  82210. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  82211. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  82212. ')');
  82213. }
  82214. }
  82215. // Axis Meshes
  82216. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  82217. var axisMeshName = this._mapping.axisMeshNames[i];
  82218. if (!axisMeshName) {
  82219. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  82220. continue;
  82221. }
  82222. var axisMesh = getChildByName(rootNode, axisMeshName);
  82223. if (!axisMesh) {
  82224. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  82225. continue;
  82226. }
  82227. var axisMeshInfo = {
  82228. index: i,
  82229. value: getImmediateChildByName(axisMesh, 'VALUE'),
  82230. min: getImmediateChildByName(axisMesh, 'MIN'),
  82231. max: getImmediateChildByName(axisMesh, 'MAX')
  82232. };
  82233. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  82234. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  82235. }
  82236. else {
  82237. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  82238. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  82239. '(VALUE: ' + !!axisMeshInfo.value +
  82240. ', MIN: ' + !!axisMeshInfo.min +
  82241. ', MAX:' + !!axisMeshInfo.max +
  82242. ')');
  82243. }
  82244. }
  82245. // Pointing Ray
  82246. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  82247. if (!loadedMeshInfo.pointingPoseNode) {
  82248. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  82249. }
  82250. else {
  82251. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  82252. }
  82253. return loadedMeshInfo;
  82254. // Look through all children recursively. This will return null if no mesh exists with the given name.
  82255. function getChildByName(node, name) {
  82256. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  82257. }
  82258. // Look through only immediate children. This will return null if no mesh exists with the given name.
  82259. function getImmediateChildByName(node, name) {
  82260. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  82261. }
  82262. };
  82263. /**
  82264. * Gets the ray of the controller in the direction the controller is pointing
  82265. * @param length the length the resulting ray should be
  82266. * @returns a ray in the direction the controller is pointing
  82267. */
  82268. WindowsMotionController.prototype.getForwardRay = function (length) {
  82269. if (length === void 0) { length = 100; }
  82270. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  82271. return _super.prototype.getForwardRay.call(this, length);
  82272. }
  82273. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  82274. var origin = m.getTranslation();
  82275. var forward = new BABYLON.Vector3(0, 0, -1);
  82276. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  82277. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  82278. return new BABYLON.Ray(origin, direction, length);
  82279. };
  82280. /**
  82281. * Disposes of the controller
  82282. */
  82283. WindowsMotionController.prototype.dispose = function () {
  82284. _super.prototype.dispose.call(this);
  82285. this.onTrackpadChangedObservable.clear();
  82286. };
  82287. /**
  82288. * The base url used to load the left and right controller models
  82289. */
  82290. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  82291. /**
  82292. * The name of the left controller model file
  82293. */
  82294. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  82295. /**
  82296. * The name of the right controller model file
  82297. */
  82298. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  82299. /**
  82300. * The controller name prefix for this controller type
  82301. */
  82302. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  82303. /**
  82304. * The controller id pattern for this controller type
  82305. */
  82306. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  82307. return WindowsMotionController;
  82308. }(BABYLON.WebVRController));
  82309. BABYLON.WindowsMotionController = WindowsMotionController;
  82310. })(BABYLON || (BABYLON = {}));
  82311. //# sourceMappingURL=babylon.windowsMotionController.js.map
  82312. var BABYLON;
  82313. (function (BABYLON) {
  82314. /**
  82315. * Gear VR Controller
  82316. */
  82317. var GearVRController = /** @class */ (function (_super) {
  82318. __extends(GearVRController, _super);
  82319. /**
  82320. * Creates a new GearVRController from a gamepad
  82321. * @param vrGamepad the gamepad that the controller should be created from
  82322. */
  82323. function GearVRController(vrGamepad) {
  82324. var _this = _super.call(this, vrGamepad) || this;
  82325. _this._buttonIndexToObservableNameMap = [
  82326. 'onTrackpadChangedObservable',
  82327. 'onTriggerStateChangedObservable' // Trigger
  82328. ];
  82329. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  82330. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  82331. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  82332. _this._disableTrackPosition(_this._calculatedPosition);
  82333. return _this;
  82334. }
  82335. /**
  82336. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82337. * @param scene scene in which to add meshes
  82338. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82339. */
  82340. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82341. var _this = this;
  82342. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  82343. // Offset the controller so it will rotate around the users wrist
  82344. var mesh = new BABYLON.Mesh("", scene);
  82345. newMeshes[1].parent = mesh;
  82346. newMeshes[1].position.z = -0.15;
  82347. _this._defaultModel = mesh;
  82348. _this.attachToMesh(_this._defaultModel);
  82349. if (meshLoaded) {
  82350. meshLoaded(_this._defaultModel);
  82351. }
  82352. });
  82353. };
  82354. /**
  82355. * Called once for each button that changed state since the last frame
  82356. * @param buttonIdx Which button index changed
  82357. * @param state New state of the button
  82358. * @param changes Which properties on the state changed since last frame
  82359. */
  82360. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82361. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  82362. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  82363. // Only emit events for buttons that we know how to map from index to observable
  82364. var observable = this[observableName];
  82365. if (observable) {
  82366. observable.notifyObservers(state);
  82367. }
  82368. }
  82369. };
  82370. /**
  82371. * Base Url for the controller model.
  82372. */
  82373. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  82374. /**
  82375. * File name for the controller model.
  82376. */
  82377. GearVRController.MODEL_FILENAME = 'generic.babylon';
  82378. /**
  82379. * Gamepad Id prefix used to identify this controller.
  82380. */
  82381. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  82382. return GearVRController;
  82383. }(BABYLON.WebVRController));
  82384. BABYLON.GearVRController = GearVRController;
  82385. })(BABYLON || (BABYLON = {}));
  82386. //# sourceMappingURL=babylon.gearVRController.js.map
  82387. var BABYLON;
  82388. (function (BABYLON) {
  82389. /**
  82390. * Google Daydream controller
  82391. */
  82392. var DaydreamController = /** @class */ (function (_super) {
  82393. __extends(DaydreamController, _super);
  82394. /**
  82395. * Creates a new DaydreamController from a gamepad
  82396. * @param vrGamepad the gamepad that the controller should be created from
  82397. */
  82398. function DaydreamController(vrGamepad) {
  82399. var _this = _super.call(this, vrGamepad) || this;
  82400. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  82401. return _this;
  82402. }
  82403. /**
  82404. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82405. * @param scene scene in which to add meshes
  82406. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82407. */
  82408. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82409. var _this = this;
  82410. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  82411. _this._defaultModel = newMeshes[1];
  82412. _this.attachToMesh(_this._defaultModel);
  82413. if (meshLoaded) {
  82414. meshLoaded(_this._defaultModel);
  82415. }
  82416. });
  82417. };
  82418. /**
  82419. * Called once for each button that changed state since the last frame
  82420. * @param buttonIdx Which button index changed
  82421. * @param state New state of the button
  82422. * @param changes Which properties on the state changed since last frame
  82423. */
  82424. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82425. // Daydream controller only has 1 GamepadButton (on the trackpad).
  82426. if (buttonIdx === 0) {
  82427. var observable = this.onTriggerStateChangedObservable;
  82428. if (observable) {
  82429. observable.notifyObservers(state);
  82430. }
  82431. }
  82432. else {
  82433. // If the app or home buttons are ever made available
  82434. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  82435. }
  82436. };
  82437. /**
  82438. * Base Url for the controller model.
  82439. */
  82440. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  82441. /**
  82442. * File name for the controller model.
  82443. */
  82444. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  82445. /**
  82446. * Gamepad Id prefix used to identify Daydream Controller.
  82447. */
  82448. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  82449. return DaydreamController;
  82450. }(BABYLON.WebVRController));
  82451. BABYLON.DaydreamController = DaydreamController;
  82452. })(BABYLON || (BABYLON = {}));
  82453. //# sourceMappingURL=babylon.daydreamController.js.map
  82454. var BABYLON;
  82455. (function (BABYLON) {
  82456. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  82457. get: function () {
  82458. if (!this._gamepadManager) {
  82459. this._gamepadManager = new BABYLON.GamepadManager(this);
  82460. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  82461. if (!component) {
  82462. component = new GamepadSystemSceneComponent(this);
  82463. this._addComponent(component);
  82464. }
  82465. }
  82466. return this._gamepadManager;
  82467. },
  82468. enumerable: true,
  82469. configurable: true
  82470. });
  82471. /**
  82472. * Adds a gamepad to the free camera inputs manager
  82473. */
  82474. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  82475. this.add(new BABYLON.FreeCameraGamepadInput());
  82476. return this;
  82477. };
  82478. /**
  82479. * Adds a gamepad to the arc rotate camera inputs manager
  82480. */
  82481. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  82482. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  82483. return this;
  82484. };
  82485. /**
  82486. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  82487. */
  82488. var GamepadSystemSceneComponent = /** @class */ (function () {
  82489. /**
  82490. * Creates a new instance of the component for the given scene
  82491. * @param scene Defines the scene to register the component in
  82492. */
  82493. function GamepadSystemSceneComponent(scene) {
  82494. /**
  82495. * The component name helpfull to identify the component in the list of scene components.
  82496. */
  82497. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  82498. this.scene = scene;
  82499. }
  82500. /**
  82501. * Registers the component in a given scene
  82502. */
  82503. GamepadSystemSceneComponent.prototype.register = function () {
  82504. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  82505. };
  82506. /**
  82507. * Rebuilds the elements related to this component in case of
  82508. * context lost for instance.
  82509. */
  82510. GamepadSystemSceneComponent.prototype.rebuild = function () {
  82511. // Nothing to do for gamepads
  82512. };
  82513. /**
  82514. * Disposes the component and the associated ressources
  82515. */
  82516. GamepadSystemSceneComponent.prototype.dispose = function () {
  82517. var gamepadManager = this.scene._gamepadManager;
  82518. if (gamepadManager) {
  82519. gamepadManager.dispose();
  82520. this.scene._gamepadManager = null;
  82521. }
  82522. };
  82523. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  82524. var gamepadManager = this.scene._gamepadManager;
  82525. if (gamepadManager && gamepadManager._isMonitoring) {
  82526. gamepadManager._checkGamepadsStatus();
  82527. }
  82528. };
  82529. return GamepadSystemSceneComponent;
  82530. }());
  82531. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  82532. })(BABYLON || (BABYLON = {}));
  82533. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  82534. var BABYLON;
  82535. (function (BABYLON) {
  82536. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  82537. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  82538. });
  82539. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  82540. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  82541. });
  82542. /**
  82543. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  82544. * an arc rotate version arcFollowCamera are available.
  82545. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82546. */
  82547. var FollowCamera = /** @class */ (function (_super) {
  82548. __extends(FollowCamera, _super);
  82549. /**
  82550. * Instantiates the follow camera.
  82551. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82552. * @param name Define the name of the camera in the scene
  82553. * @param position Define the position of the camera
  82554. * @param scene Define the scene the camera belong to
  82555. * @param lockedTarget Define the target of the camera
  82556. */
  82557. function FollowCamera(name, position, scene, lockedTarget) {
  82558. if (lockedTarget === void 0) { lockedTarget = null; }
  82559. var _this = _super.call(this, name, position, scene) || this;
  82560. /**
  82561. * Distance the follow camera should follow an object at
  82562. */
  82563. _this.radius = 12;
  82564. /**
  82565. * Define a rotation offset between the camera and the object it follows
  82566. */
  82567. _this.rotationOffset = 0;
  82568. /**
  82569. * Define a height offset between the camera and the object it follows.
  82570. * It can help following an object from the top (like a car chaing a plane)
  82571. */
  82572. _this.heightOffset = 4;
  82573. /**
  82574. * Define how fast the camera can accelerate to follow it s target.
  82575. */
  82576. _this.cameraAcceleration = 0.05;
  82577. /**
  82578. * Define the speed limit of the camera following an object.
  82579. */
  82580. _this.maxCameraSpeed = 20;
  82581. _this.lockedTarget = lockedTarget;
  82582. return _this;
  82583. }
  82584. FollowCamera.prototype._follow = function (cameraTarget) {
  82585. if (!cameraTarget) {
  82586. return;
  82587. }
  82588. var yRotation;
  82589. if (cameraTarget.rotationQuaternion) {
  82590. var rotMatrix = new BABYLON.Matrix();
  82591. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  82592. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  82593. }
  82594. else {
  82595. yRotation = cameraTarget.rotation.y;
  82596. }
  82597. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  82598. var targetPosition = cameraTarget.getAbsolutePosition();
  82599. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  82600. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  82601. var dx = targetX - this.position.x;
  82602. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  82603. var dz = (targetZ) - this.position.z;
  82604. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  82605. var vy = dy * this.cameraAcceleration;
  82606. var vz = dz * this.cameraAcceleration * 2;
  82607. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  82608. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  82609. }
  82610. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  82611. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  82612. }
  82613. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  82614. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  82615. }
  82616. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  82617. this.setTarget(targetPosition);
  82618. };
  82619. /** @hidden */
  82620. FollowCamera.prototype._checkInputs = function () {
  82621. _super.prototype._checkInputs.call(this);
  82622. if (this.lockedTarget) {
  82623. this._follow(this.lockedTarget);
  82624. }
  82625. };
  82626. /**
  82627. * Gets the camera class name.
  82628. * @returns the class name
  82629. */
  82630. FollowCamera.prototype.getClassName = function () {
  82631. return "FollowCamera";
  82632. };
  82633. __decorate([
  82634. BABYLON.serialize()
  82635. ], FollowCamera.prototype, "radius", void 0);
  82636. __decorate([
  82637. BABYLON.serialize()
  82638. ], FollowCamera.prototype, "rotationOffset", void 0);
  82639. __decorate([
  82640. BABYLON.serialize()
  82641. ], FollowCamera.prototype, "heightOffset", void 0);
  82642. __decorate([
  82643. BABYLON.serialize()
  82644. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  82645. __decorate([
  82646. BABYLON.serialize()
  82647. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  82648. __decorate([
  82649. BABYLON.serializeAsMeshReference("lockedTargetId")
  82650. ], FollowCamera.prototype, "lockedTarget", void 0);
  82651. return FollowCamera;
  82652. }(BABYLON.TargetCamera));
  82653. BABYLON.FollowCamera = FollowCamera;
  82654. /**
  82655. * Arc Rotate version of the follow camera.
  82656. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  82657. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82658. */
  82659. var ArcFollowCamera = /** @class */ (function (_super) {
  82660. __extends(ArcFollowCamera, _super);
  82661. /**
  82662. * Instantiates a new ArcFollowCamera
  82663. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82664. * @param name Define the name of the camera
  82665. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  82666. * @param beta Define the rotation angle of the camera around the elevation axis
  82667. * @param radius Define the radius of the camera from its target point
  82668. * @param target Define the target of the camera
  82669. * @param scene Define the scene the camera belongs to
  82670. */
  82671. function ArcFollowCamera(name,
  82672. /** The longitudinal angle of the camera */
  82673. alpha,
  82674. /** The latitudinal angle of the camera */
  82675. beta,
  82676. /** The radius of the camera from its target */
  82677. radius,
  82678. /** Define the camera target (the messh it should follow) */
  82679. target, scene) {
  82680. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  82681. _this.alpha = alpha;
  82682. _this.beta = beta;
  82683. _this.radius = radius;
  82684. _this.target = target;
  82685. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  82686. _this._follow();
  82687. return _this;
  82688. }
  82689. ArcFollowCamera.prototype._follow = function () {
  82690. if (!this.target) {
  82691. return;
  82692. }
  82693. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  82694. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  82695. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  82696. var targetPosition = this.target.getAbsolutePosition();
  82697. this.position = targetPosition.add(this._cartesianCoordinates);
  82698. this.setTarget(targetPosition);
  82699. };
  82700. /** @hidden */
  82701. ArcFollowCamera.prototype._checkInputs = function () {
  82702. _super.prototype._checkInputs.call(this);
  82703. this._follow();
  82704. };
  82705. /**
  82706. * Returns the class name of the object.
  82707. * It is mostly used internally for serialization purposes.
  82708. */
  82709. ArcFollowCamera.prototype.getClassName = function () {
  82710. return "ArcFollowCamera";
  82711. };
  82712. return ArcFollowCamera;
  82713. }(BABYLON.TargetCamera));
  82714. BABYLON.ArcFollowCamera = ArcFollowCamera;
  82715. })(BABYLON || (BABYLON = {}));
  82716. //# sourceMappingURL=babylon.followCamera.js.map
  82717. var BABYLON;
  82718. (function (BABYLON) {
  82719. /**
  82720. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  82721. * which still works and will still be found in many Playgrounds.
  82722. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82723. */
  82724. var UniversalCamera = /** @class */ (function (_super) {
  82725. __extends(UniversalCamera, _super);
  82726. /**
  82727. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  82728. * which still works and will still be found in many Playgrounds.
  82729. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82730. * @param name Define the name of the camera in the scene
  82731. * @param position Define the start position of the camera in the scene
  82732. * @param scene Define the scene the camera belongs to
  82733. */
  82734. function UniversalCamera(name, position, scene) {
  82735. var _this = _super.call(this, name, position, scene) || this;
  82736. _this.inputs.addGamepad();
  82737. return _this;
  82738. }
  82739. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  82740. /**
  82741. * Defines the gamepad rotation sensiblity.
  82742. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  82743. */
  82744. get: function () {
  82745. var gamepad = this.inputs.attached["gamepad"];
  82746. if (gamepad) {
  82747. return gamepad.gamepadAngularSensibility;
  82748. }
  82749. return 0;
  82750. },
  82751. set: function (value) {
  82752. var gamepad = this.inputs.attached["gamepad"];
  82753. if (gamepad) {
  82754. gamepad.gamepadAngularSensibility = value;
  82755. }
  82756. },
  82757. enumerable: true,
  82758. configurable: true
  82759. });
  82760. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  82761. /**
  82762. * Defines the gamepad move sensiblity.
  82763. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  82764. */
  82765. get: function () {
  82766. var gamepad = this.inputs.attached["gamepad"];
  82767. if (gamepad) {
  82768. return gamepad.gamepadMoveSensibility;
  82769. }
  82770. return 0;
  82771. },
  82772. set: function (value) {
  82773. var gamepad = this.inputs.attached["gamepad"];
  82774. if (gamepad) {
  82775. gamepad.gamepadMoveSensibility = value;
  82776. }
  82777. },
  82778. enumerable: true,
  82779. configurable: true
  82780. });
  82781. /**
  82782. * Gets the current object class name.
  82783. * @return the class name
  82784. */
  82785. UniversalCamera.prototype.getClassName = function () {
  82786. return "UniversalCamera";
  82787. };
  82788. return UniversalCamera;
  82789. }(BABYLON.TouchCamera));
  82790. BABYLON.UniversalCamera = UniversalCamera;
  82791. })(BABYLON || (BABYLON = {}));
  82792. //# sourceMappingURL=babylon.universalCamera.js.map
  82793. var BABYLON;
  82794. (function (BABYLON) {
  82795. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  82796. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  82797. });
  82798. /**
  82799. * This represents a FPS type of camera. This is only here for back compat purpose.
  82800. * Please use the UniversalCamera instead as both are identical.
  82801. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82802. */
  82803. var GamepadCamera = /** @class */ (function (_super) {
  82804. __extends(GamepadCamera, _super);
  82805. /**
  82806. * Instantiates a new Gamepad Camera
  82807. * This represents a FPS type of camera. This is only here for back compat purpose.
  82808. * Please use the UniversalCamera instead as both are identical.
  82809. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82810. * @param name Define the name of the camera in the scene
  82811. * @param position Define the start position of the camera in the scene
  82812. * @param scene Define the scene the camera belongs to
  82813. */
  82814. function GamepadCamera(name, position, scene) {
  82815. return _super.call(this, name, position, scene) || this;
  82816. }
  82817. /**
  82818. * Gets the current object class name.
  82819. * @return the class name
  82820. */
  82821. GamepadCamera.prototype.getClassName = function () {
  82822. return "GamepadCamera";
  82823. };
  82824. return GamepadCamera;
  82825. }(BABYLON.UniversalCamera));
  82826. BABYLON.GamepadCamera = GamepadCamera;
  82827. })(BABYLON || (BABYLON = {}));
  82828. //# sourceMappingURL=babylon.gamepadCamera.js.map
  82829. var BABYLON;
  82830. (function (BABYLON) {
  82831. /**
  82832. * PostProcessRenderPipelineManager class
  82833. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  82834. */
  82835. var PostProcessRenderPipelineManager = /** @class */ (function () {
  82836. /**
  82837. * Initializes a PostProcessRenderPipelineManager
  82838. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  82839. */
  82840. function PostProcessRenderPipelineManager() {
  82841. this._renderPipelines = {};
  82842. }
  82843. /**
  82844. * Adds a pipeline to the manager
  82845. * @param renderPipeline The pipeline to add
  82846. */
  82847. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  82848. this._renderPipelines[renderPipeline._name] = renderPipeline;
  82849. };
  82850. /**
  82851. * Attaches a camera to the pipeline
  82852. * @param renderPipelineName The name of the pipeline to attach to
  82853. * @param cameras the camera to attach
  82854. * @param unique if the camera can be attached multiple times to the pipeline
  82855. */
  82856. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  82857. if (unique === void 0) { unique = false; }
  82858. var renderPipeline = this._renderPipelines[renderPipelineName];
  82859. if (!renderPipeline) {
  82860. return;
  82861. }
  82862. renderPipeline._attachCameras(cameras, unique);
  82863. };
  82864. /**
  82865. * Detaches a camera from the pipeline
  82866. * @param renderPipelineName The name of the pipeline to detach from
  82867. * @param cameras the camera to detach
  82868. */
  82869. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  82870. var renderPipeline = this._renderPipelines[renderPipelineName];
  82871. if (!renderPipeline) {
  82872. return;
  82873. }
  82874. renderPipeline._detachCameras(cameras);
  82875. };
  82876. /**
  82877. * Enables an effect by name on a pipeline
  82878. * @param renderPipelineName the name of the pipeline to enable the effect in
  82879. * @param renderEffectName the name of the effect to enable
  82880. * @param cameras the cameras that the effect should be enabled on
  82881. */
  82882. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  82883. var renderPipeline = this._renderPipelines[renderPipelineName];
  82884. if (!renderPipeline) {
  82885. return;
  82886. }
  82887. renderPipeline._enableEffect(renderEffectName, cameras);
  82888. };
  82889. /**
  82890. * Disables an effect by name on a pipeline
  82891. * @param renderPipelineName the name of the pipeline to disable the effect in
  82892. * @param renderEffectName the name of the effect to disable
  82893. * @param cameras the cameras that the effect should be disabled on
  82894. */
  82895. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  82896. var renderPipeline = this._renderPipelines[renderPipelineName];
  82897. if (!renderPipeline) {
  82898. return;
  82899. }
  82900. renderPipeline._disableEffect(renderEffectName, cameras);
  82901. };
  82902. /**
  82903. * Updates the state of all contained render pipelines and disposes of any non supported pipelines
  82904. */
  82905. PostProcessRenderPipelineManager.prototype.update = function () {
  82906. for (var renderPipelineName in this._renderPipelines) {
  82907. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  82908. var pipeline = this._renderPipelines[renderPipelineName];
  82909. if (!pipeline.isSupported) {
  82910. pipeline.dispose();
  82911. delete this._renderPipelines[renderPipelineName];
  82912. }
  82913. else {
  82914. pipeline._update();
  82915. }
  82916. }
  82917. }
  82918. };
  82919. /** @hidden */
  82920. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  82921. for (var renderPipelineName in this._renderPipelines) {
  82922. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  82923. var pipeline = this._renderPipelines[renderPipelineName];
  82924. pipeline._rebuild();
  82925. }
  82926. }
  82927. };
  82928. /**
  82929. * Disposes of the manager and pipelines
  82930. */
  82931. PostProcessRenderPipelineManager.prototype.dispose = function () {
  82932. for (var renderPipelineName in this._renderPipelines) {
  82933. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  82934. var pipeline = this._renderPipelines[renderPipelineName];
  82935. pipeline.dispose();
  82936. }
  82937. }
  82938. };
  82939. return PostProcessRenderPipelineManager;
  82940. }());
  82941. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  82942. })(BABYLON || (BABYLON = {}));
  82943. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  82944. var BABYLON;
  82945. (function (BABYLON) {
  82946. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  82947. get: function () {
  82948. if (!this._postProcessRenderPipelineManager) {
  82949. // Register the G Buffer component to the scene.
  82950. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  82951. if (!component) {
  82952. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  82953. this._addComponent(component);
  82954. }
  82955. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  82956. }
  82957. return this._postProcessRenderPipelineManager;
  82958. },
  82959. enumerable: true,
  82960. configurable: true
  82961. });
  82962. /**
  82963. * Defines the Render Pipeline scene component responsible to rendering pipelines
  82964. */
  82965. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  82966. /**
  82967. * Creates a new instance of the component for the given scene
  82968. * @param scene Defines the scene to register the component in
  82969. */
  82970. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  82971. /**
  82972. * The component name helpfull to identify the component in the list of scene components.
  82973. */
  82974. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  82975. this.scene = scene;
  82976. }
  82977. /**
  82978. * Registers the component in a given scene
  82979. */
  82980. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  82981. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  82982. };
  82983. /**
  82984. * Rebuilds the elements related to this component in case of
  82985. * context lost for instance.
  82986. */
  82987. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  82988. if (this.scene._postProcessRenderPipelineManager) {
  82989. this.scene._postProcessRenderPipelineManager._rebuild();
  82990. }
  82991. };
  82992. /**
  82993. * Disposes the component and the associated ressources
  82994. */
  82995. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  82996. if (this.scene._postProcessRenderPipelineManager) {
  82997. this.scene._postProcessRenderPipelineManager.dispose();
  82998. }
  82999. };
  83000. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  83001. if (this.scene._postProcessRenderPipelineManager) {
  83002. this.scene._postProcessRenderPipelineManager.update();
  83003. }
  83004. };
  83005. return PostProcessRenderPipelineManagerSceneComponent;
  83006. }());
  83007. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  83008. })(BABYLON || (BABYLON = {}));
  83009. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  83010. var BABYLON;
  83011. (function (BABYLON) {
  83012. /**
  83013. * This represents a set of one or more post processes in Babylon.
  83014. * A post process can be used to apply a shader to a texture after it is rendered.
  83015. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  83016. */
  83017. var PostProcessRenderEffect = /** @class */ (function () {
  83018. /**
  83019. * Instantiates a post process render effect.
  83020. * A post process can be used to apply a shader to a texture after it is rendered.
  83021. * @param engine The engine the effect is tied to
  83022. * @param name The name of the effect
  83023. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  83024. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  83025. */
  83026. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  83027. this._name = name;
  83028. this._singleInstance = singleInstance || true;
  83029. this._getPostProcesses = getPostProcesses;
  83030. this._cameras = {};
  83031. this._indicesForCamera = {};
  83032. this._postProcesses = {};
  83033. }
  83034. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  83035. /**
  83036. * Checks if all the post processes in the effect are supported.
  83037. */
  83038. get: function () {
  83039. for (var index in this._postProcesses) {
  83040. if (this._postProcesses.hasOwnProperty(index)) {
  83041. var pps = this._postProcesses[index];
  83042. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  83043. if (!pps[ppIndex].isSupported) {
  83044. return false;
  83045. }
  83046. }
  83047. }
  83048. }
  83049. return true;
  83050. },
  83051. enumerable: true,
  83052. configurable: true
  83053. });
  83054. /**
  83055. * Updates the current state of the effect
  83056. * @hidden
  83057. */
  83058. PostProcessRenderEffect.prototype._update = function () {
  83059. };
  83060. /**
  83061. * Attaches the effect on cameras
  83062. * @param cameras The camera to attach to.
  83063. * @hidden
  83064. */
  83065. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  83066. var _this = this;
  83067. var cameraKey;
  83068. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83069. if (!cams) {
  83070. return;
  83071. }
  83072. for (var i = 0; i < cams.length; i++) {
  83073. var camera = cams[i];
  83074. var cameraName = camera.name;
  83075. if (this._singleInstance) {
  83076. cameraKey = 0;
  83077. }
  83078. else {
  83079. cameraKey = cameraName;
  83080. }
  83081. if (!this._postProcesses[cameraKey]) {
  83082. var postProcess = this._getPostProcesses();
  83083. if (postProcess) {
  83084. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  83085. }
  83086. }
  83087. if (!this._indicesForCamera[cameraName]) {
  83088. this._indicesForCamera[cameraName] = [];
  83089. }
  83090. this._postProcesses[cameraKey].forEach(function (postProcess) {
  83091. var index = camera.attachPostProcess(postProcess);
  83092. _this._indicesForCamera[cameraName].push(index);
  83093. });
  83094. if (!this._cameras[cameraName]) {
  83095. this._cameras[cameraName] = camera;
  83096. }
  83097. }
  83098. };
  83099. /**
  83100. * Detatches the effect on cameras
  83101. * @param cameras The camera to detatch from.
  83102. * @hidden
  83103. */
  83104. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  83105. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83106. if (!cams) {
  83107. return;
  83108. }
  83109. for (var i = 0; i < cams.length; i++) {
  83110. var camera = cams[i];
  83111. var cameraName = camera.name;
  83112. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  83113. camera.detachPostProcess(postProcess);
  83114. });
  83115. if (this._cameras[cameraName]) {
  83116. //this._indicesForCamera.splice(index, 1);
  83117. this._cameras[cameraName] = null;
  83118. }
  83119. }
  83120. };
  83121. /**
  83122. * Enables the effect on given cameras
  83123. * @param cameras The camera to enable.
  83124. * @hidden
  83125. */
  83126. PostProcessRenderEffect.prototype._enable = function (cameras) {
  83127. var _this = this;
  83128. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83129. if (!cams) {
  83130. return;
  83131. }
  83132. for (var i = 0; i < cams.length; i++) {
  83133. var camera = cams[i];
  83134. var cameraName = camera.name;
  83135. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  83136. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  83137. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  83138. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  83139. });
  83140. }
  83141. }
  83142. }
  83143. };
  83144. /**
  83145. * Disables the effect on the given cameras
  83146. * @param cameras The camera to disable.
  83147. * @hidden
  83148. */
  83149. PostProcessRenderEffect.prototype._disable = function (cameras) {
  83150. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83151. if (!cams) {
  83152. return;
  83153. }
  83154. for (var i = 0; i < cams.length; i++) {
  83155. var camera = cams[i];
  83156. var cameraName = camera.name;
  83157. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  83158. camera.detachPostProcess(postProcess);
  83159. });
  83160. }
  83161. };
  83162. /**
  83163. * Gets a list of the post processes contained in the effect.
  83164. * @param camera The camera to get the post processes on.
  83165. * @returns The list of the post processes in the effect.
  83166. */
  83167. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  83168. if (this._singleInstance) {
  83169. return this._postProcesses[0];
  83170. }
  83171. else {
  83172. if (!camera) {
  83173. return null;
  83174. }
  83175. return this._postProcesses[camera.name];
  83176. }
  83177. };
  83178. return PostProcessRenderEffect;
  83179. }());
  83180. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  83181. })(BABYLON || (BABYLON = {}));
  83182. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  83183. var BABYLON;
  83184. (function (BABYLON) {
  83185. /**
  83186. * PostProcessRenderPipeline
  83187. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  83188. */
  83189. var PostProcessRenderPipeline = /** @class */ (function () {
  83190. /**
  83191. * Initializes a PostProcessRenderPipeline
  83192. * @param engine engine to add the pipeline to
  83193. * @param name name of the pipeline
  83194. */
  83195. function PostProcessRenderPipeline(engine, name) {
  83196. this.engine = engine;
  83197. this._name = name;
  83198. this._renderEffects = {};
  83199. this._renderEffectsForIsolatedPass = new Array();
  83200. this._cameras = [];
  83201. }
  83202. /**
  83203. * "PostProcessRenderPipeline"
  83204. * @returns "PostProcessRenderPipeline"
  83205. */
  83206. PostProcessRenderPipeline.prototype.getClassName = function () {
  83207. return "PostProcessRenderPipeline";
  83208. };
  83209. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  83210. /**
  83211. * If all the render effects in the pipeline are support
  83212. */
  83213. get: function () {
  83214. for (var renderEffectName in this._renderEffects) {
  83215. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  83216. if (!this._renderEffects[renderEffectName].isSupported) {
  83217. return false;
  83218. }
  83219. }
  83220. }
  83221. return true;
  83222. },
  83223. enumerable: true,
  83224. configurable: true
  83225. });
  83226. /**
  83227. * Adds an effect to the pipeline
  83228. * @param renderEffect the effect to add
  83229. */
  83230. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  83231. this._renderEffects[renderEffect._name] = renderEffect;
  83232. };
  83233. // private
  83234. /** @hidden */
  83235. PostProcessRenderPipeline.prototype._rebuild = function () {
  83236. };
  83237. /** @hidden */
  83238. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  83239. var renderEffects = this._renderEffects[renderEffectName];
  83240. if (!renderEffects) {
  83241. return;
  83242. }
  83243. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  83244. };
  83245. /** @hidden */
  83246. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  83247. var renderEffects = this._renderEffects[renderEffectName];
  83248. if (!renderEffects) {
  83249. return;
  83250. }
  83251. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  83252. };
  83253. /** @hidden */
  83254. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  83255. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83256. if (!cams) {
  83257. return;
  83258. }
  83259. var indicesToDelete = [];
  83260. var i;
  83261. for (i = 0; i < cams.length; i++) {
  83262. var camera = cams[i];
  83263. var cameraName = camera.name;
  83264. if (this._cameras.indexOf(camera) === -1) {
  83265. this._cameras[cameraName] = camera;
  83266. }
  83267. else if (unique) {
  83268. indicesToDelete.push(i);
  83269. }
  83270. }
  83271. for (i = 0; i < indicesToDelete.length; i++) {
  83272. cameras.splice(indicesToDelete[i], 1);
  83273. }
  83274. for (var renderEffectName in this._renderEffects) {
  83275. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  83276. this._renderEffects[renderEffectName]._attachCameras(cams);
  83277. }
  83278. }
  83279. };
  83280. /** @hidden */
  83281. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  83282. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83283. if (!cams) {
  83284. return;
  83285. }
  83286. for (var renderEffectName in this._renderEffects) {
  83287. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  83288. this._renderEffects[renderEffectName]._detachCameras(cams);
  83289. }
  83290. }
  83291. for (var i = 0; i < cams.length; i++) {
  83292. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  83293. }
  83294. };
  83295. /** @hidden */
  83296. PostProcessRenderPipeline.prototype._update = function () {
  83297. for (var renderEffectName in this._renderEffects) {
  83298. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  83299. this._renderEffects[renderEffectName]._update();
  83300. }
  83301. }
  83302. for (var i = 0; i < this._cameras.length; i++) {
  83303. var cameraName = this._cameras[i].name;
  83304. if (this._renderEffectsForIsolatedPass[cameraName]) {
  83305. this._renderEffectsForIsolatedPass[cameraName]._update();
  83306. }
  83307. }
  83308. };
  83309. /** @hidden */
  83310. PostProcessRenderPipeline.prototype._reset = function () {
  83311. this._renderEffects = {};
  83312. this._renderEffectsForIsolatedPass = new Array();
  83313. };
  83314. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  83315. // 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)
  83316. var effectKeys = Object.keys(this._renderEffects);
  83317. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  83318. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  83319. if (postProcesses) {
  83320. postProcesses[0].samples = sampleCount;
  83321. return true;
  83322. }
  83323. }
  83324. return false;
  83325. };
  83326. /**
  83327. * Disposes of the pipeline
  83328. */
  83329. PostProcessRenderPipeline.prototype.dispose = function () {
  83330. // Must be implemented by children
  83331. };
  83332. __decorate([
  83333. BABYLON.serialize()
  83334. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  83335. return PostProcessRenderPipeline;
  83336. }());
  83337. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  83338. })(BABYLON || (BABYLON = {}));
  83339. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  83340. var BABYLON;
  83341. (function (BABYLON) {
  83342. /**
  83343. * This represents a depth renderer in Babylon.
  83344. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  83345. */
  83346. var DepthRenderer = /** @class */ (function () {
  83347. /**
  83348. * Instantiates a depth renderer
  83349. * @param scene The scene the renderer belongs to
  83350. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  83351. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  83352. */
  83353. function DepthRenderer(scene, type, camera) {
  83354. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  83355. if (camera === void 0) { camera = null; }
  83356. var _this = this;
  83357. /**
  83358. * Specifiess that the depth renderer will only be used within
  83359. * the camera it is created for.
  83360. * This can help forcing its rendering during the camera processing.
  83361. */
  83362. this.useOnlyInActiveCamera = false;
  83363. this._scene = scene;
  83364. // Register the G Buffer component to the scene.
  83365. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  83366. if (!component) {
  83367. component = new BABYLON.DepthRendererSceneComponent(scene);
  83368. scene._addComponent(component);
  83369. }
  83370. this._camera = camera;
  83371. var engine = scene.getEngine();
  83372. // Render target
  83373. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  83374. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83375. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83376. this._depthMap.refreshRate = 1;
  83377. this._depthMap.renderParticles = false;
  83378. this._depthMap.renderList = null;
  83379. // Camera to get depth map from to support multiple concurrent cameras
  83380. this._depthMap.activeCamera = this._camera;
  83381. this._depthMap.ignoreCameraViewport = true;
  83382. this._depthMap.useCameraPostProcesses = false;
  83383. // set default depth value to 1.0 (far away)
  83384. this._depthMap.onClearObservable.add(function (engine) {
  83385. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  83386. });
  83387. // Custom render function
  83388. var renderSubMesh = function (subMesh) {
  83389. var mesh = subMesh.getRenderingMesh();
  83390. var scene = _this._scene;
  83391. var engine = scene.getEngine();
  83392. var material = subMesh.getMaterial();
  83393. if (!material) {
  83394. return;
  83395. }
  83396. // Culling and reverse (right handed system)
  83397. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  83398. // Managing instances
  83399. var batch = mesh._getInstancesRenderList(subMesh._id);
  83400. if (batch.mustReturn) {
  83401. return;
  83402. }
  83403. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  83404. var camera = _this._camera || scene.activeCamera;
  83405. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  83406. engine.enableEffect(_this._effect);
  83407. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  83408. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83409. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  83410. // Alpha test
  83411. if (material && material.needAlphaTesting()) {
  83412. var alphaTexture = material.getAlphaTestTexture();
  83413. if (alphaTexture) {
  83414. _this._effect.setTexture("diffuseSampler", alphaTexture);
  83415. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83416. }
  83417. }
  83418. // Bones
  83419. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83420. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83421. }
  83422. // Draw
  83423. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  83424. }
  83425. };
  83426. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83427. var index;
  83428. if (depthOnlySubMeshes.length) {
  83429. engine.setColorWrite(false);
  83430. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83431. renderSubMesh(depthOnlySubMeshes.data[index]);
  83432. }
  83433. engine.setColorWrite(true);
  83434. }
  83435. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83436. renderSubMesh(opaqueSubMeshes.data[index]);
  83437. }
  83438. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83439. renderSubMesh(alphaTestSubMeshes.data[index]);
  83440. }
  83441. };
  83442. }
  83443. /**
  83444. * Creates the depth rendering effect and checks if the effect is ready.
  83445. * @param subMesh The submesh to be used to render the depth map of
  83446. * @param useInstances If multiple world instances should be used
  83447. * @returns if the depth renderer is ready to render the depth map
  83448. */
  83449. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  83450. var material = subMesh.getMaterial();
  83451. if (material.disableDepthWrite) {
  83452. return false;
  83453. }
  83454. var defines = [];
  83455. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83456. var mesh = subMesh.getMesh();
  83457. // Alpha test
  83458. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  83459. defines.push("#define ALPHATEST");
  83460. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83461. attribs.push(BABYLON.VertexBuffer.UVKind);
  83462. defines.push("#define UV1");
  83463. }
  83464. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83465. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83466. defines.push("#define UV2");
  83467. }
  83468. }
  83469. // Bones
  83470. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83471. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83472. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83473. if (mesh.numBoneInfluencers > 4) {
  83474. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83475. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83476. }
  83477. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83478. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83479. }
  83480. else {
  83481. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83482. }
  83483. // Instances
  83484. if (useInstances) {
  83485. defines.push("#define INSTANCES");
  83486. attribs.push("world0");
  83487. attribs.push("world1");
  83488. attribs.push("world2");
  83489. attribs.push("world3");
  83490. }
  83491. // Get correct effect
  83492. var join = defines.join("\n");
  83493. if (this._cachedDefines !== join) {
  83494. this._cachedDefines = join;
  83495. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  83496. }
  83497. return this._effect.isReady();
  83498. };
  83499. /**
  83500. * Gets the texture which the depth map will be written to.
  83501. * @returns The depth map texture
  83502. */
  83503. DepthRenderer.prototype.getDepthMap = function () {
  83504. return this._depthMap;
  83505. };
  83506. /**
  83507. * Disposes of the depth renderer.
  83508. */
  83509. DepthRenderer.prototype.dispose = function () {
  83510. this._depthMap.dispose();
  83511. };
  83512. return DepthRenderer;
  83513. }());
  83514. BABYLON.DepthRenderer = DepthRenderer;
  83515. })(BABYLON || (BABYLON = {}));
  83516. //# sourceMappingURL=babylon.depthRenderer.js.map
  83517. var BABYLON;
  83518. (function (BABYLON) {
  83519. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  83520. camera = camera || this.activeCamera;
  83521. if (!camera) {
  83522. throw "No camera available to enable depth renderer";
  83523. }
  83524. if (!this._depthRenderer) {
  83525. this._depthRenderer = {};
  83526. }
  83527. if (!this._depthRenderer[camera.id]) {
  83528. var textureType = 0;
  83529. if (this.getEngine().getCaps().textureHalfFloatRender) {
  83530. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83531. }
  83532. else if (this.getEngine().getCaps().textureFloatRender) {
  83533. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83534. }
  83535. else {
  83536. throw "Depth renderer does not support int texture type";
  83537. }
  83538. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  83539. }
  83540. return this._depthRenderer[camera.id];
  83541. };
  83542. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  83543. camera = camera || this.activeCamera;
  83544. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  83545. return;
  83546. }
  83547. this._depthRenderer[camera.id].dispose();
  83548. delete this._depthRenderer[camera.id];
  83549. };
  83550. /**
  83551. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  83552. * in several rendering techniques.
  83553. */
  83554. var DepthRendererSceneComponent = /** @class */ (function () {
  83555. /**
  83556. * Creates a new instance of the component for the given scene
  83557. * @param scene Defines the scene to register the component in
  83558. */
  83559. function DepthRendererSceneComponent(scene) {
  83560. /**
  83561. * The component name helpfull to identify the component in the list of scene components.
  83562. */
  83563. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  83564. this.scene = scene;
  83565. }
  83566. /**
  83567. * Registers the component in a given scene
  83568. */
  83569. DepthRendererSceneComponent.prototype.register = function () {
  83570. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  83571. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  83572. };
  83573. /**
  83574. * Rebuilds the elements related to this component in case of
  83575. * context lost for instance.
  83576. */
  83577. DepthRendererSceneComponent.prototype.rebuild = function () {
  83578. // Nothing to do for this component
  83579. };
  83580. /**
  83581. * Disposes the component and the associated ressources
  83582. */
  83583. DepthRendererSceneComponent.prototype.dispose = function () {
  83584. for (var key in this.scene._depthRenderer) {
  83585. this.scene._depthRenderer[key].dispose();
  83586. }
  83587. };
  83588. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  83589. if (this.scene._depthRenderer) {
  83590. for (var key in this.scene._depthRenderer) {
  83591. var depthRenderer = this.scene._depthRenderer[key];
  83592. if (!depthRenderer.useOnlyInActiveCamera) {
  83593. renderTargets.push(depthRenderer.getDepthMap());
  83594. }
  83595. }
  83596. }
  83597. };
  83598. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  83599. if (this.scene._depthRenderer) {
  83600. for (var key in this.scene._depthRenderer) {
  83601. var depthRenderer = this.scene._depthRenderer[key];
  83602. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  83603. renderTargets.push(depthRenderer.getDepthMap());
  83604. }
  83605. }
  83606. }
  83607. };
  83608. return DepthRendererSceneComponent;
  83609. }());
  83610. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  83611. })(BABYLON || (BABYLON = {}));
  83612. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  83613. var BABYLON;
  83614. (function (BABYLON) {
  83615. /**
  83616. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  83617. */
  83618. var GeometryBufferRenderer = /** @class */ (function () {
  83619. /**
  83620. * Creates a new G Buffer for the scene
  83621. * @param scene The scene the buffer belongs to
  83622. * @param ratio How big is the buffer related to the main canvas.
  83623. */
  83624. function GeometryBufferRenderer(scene, ratio) {
  83625. if (ratio === void 0) { ratio = 1; }
  83626. this._enablePosition = false;
  83627. this._scene = scene;
  83628. this._ratio = ratio;
  83629. // Register the G Buffer component to the scene.
  83630. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  83631. if (!component) {
  83632. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  83633. scene._addComponent(component);
  83634. }
  83635. // Render target
  83636. this._createRenderTargets();
  83637. }
  83638. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  83639. /**
  83640. * Set the render list (meshes to be rendered) used in the G buffer.
  83641. */
  83642. set: function (meshes) {
  83643. this._multiRenderTarget.renderList = meshes;
  83644. },
  83645. enumerable: true,
  83646. configurable: true
  83647. });
  83648. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  83649. /**
  83650. * Gets wether or not G buffer are supported by the running hardware.
  83651. * This requires draw buffer supports
  83652. */
  83653. get: function () {
  83654. return this._multiRenderTarget.isSupported;
  83655. },
  83656. enumerable: true,
  83657. configurable: true
  83658. });
  83659. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  83660. /**
  83661. * Gets wether or not position are enabled for the G buffer.
  83662. */
  83663. get: function () {
  83664. return this._enablePosition;
  83665. },
  83666. /**
  83667. * Sets wether or not position are enabled for the G buffer.
  83668. */
  83669. set: function (enable) {
  83670. this._enablePosition = enable;
  83671. this.dispose();
  83672. this._createRenderTargets();
  83673. },
  83674. enumerable: true,
  83675. configurable: true
  83676. });
  83677. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  83678. /**
  83679. * Gets the scene associated with the buffer.
  83680. */
  83681. get: function () {
  83682. return this._scene;
  83683. },
  83684. enumerable: true,
  83685. configurable: true
  83686. });
  83687. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  83688. /**
  83689. * Gets the ratio used by the buffer during its creation.
  83690. * How big is the buffer related to the main canvas.
  83691. */
  83692. get: function () {
  83693. return this._ratio;
  83694. },
  83695. enumerable: true,
  83696. configurable: true
  83697. });
  83698. /**
  83699. * Checks wether everything is ready to render a submesh to the G buffer.
  83700. * @param subMesh the submesh to check readiness for
  83701. * @param useInstances is the mesh drawn using instance or not
  83702. * @returns true if ready otherwise false
  83703. */
  83704. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  83705. var material = subMesh.getMaterial();
  83706. if (material && material.disableDepthWrite) {
  83707. return false;
  83708. }
  83709. var defines = [];
  83710. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  83711. var mesh = subMesh.getMesh();
  83712. // Alpha test
  83713. if (material && material.needAlphaTesting()) {
  83714. defines.push("#define ALPHATEST");
  83715. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83716. attribs.push(BABYLON.VertexBuffer.UVKind);
  83717. defines.push("#define UV1");
  83718. }
  83719. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83720. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83721. defines.push("#define UV2");
  83722. }
  83723. }
  83724. // Buffers
  83725. if (this._enablePosition) {
  83726. defines.push("#define POSITION");
  83727. }
  83728. // Bones
  83729. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83730. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83731. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83732. if (mesh.numBoneInfluencers > 4) {
  83733. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83734. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83735. }
  83736. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83737. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83738. }
  83739. else {
  83740. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83741. }
  83742. // Instances
  83743. if (useInstances) {
  83744. defines.push("#define INSTANCES");
  83745. attribs.push("world0");
  83746. attribs.push("world1");
  83747. attribs.push("world2");
  83748. attribs.push("world3");
  83749. }
  83750. // Get correct effect
  83751. var join = defines.join("\n");
  83752. if (this._cachedDefines !== join) {
  83753. this._cachedDefines = join;
  83754. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  83755. }
  83756. return this._effect.isReady();
  83757. };
  83758. /**
  83759. * Gets the current underlying G Buffer.
  83760. * @returns the buffer
  83761. */
  83762. GeometryBufferRenderer.prototype.getGBuffer = function () {
  83763. return this._multiRenderTarget;
  83764. };
  83765. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  83766. /**
  83767. * Gets the number of samples used to render the buffer (anti aliasing).
  83768. */
  83769. get: function () {
  83770. return this._multiRenderTarget.samples;
  83771. },
  83772. /**
  83773. * Sets the number of samples used to render the buffer (anti aliasing).
  83774. */
  83775. set: function (value) {
  83776. this._multiRenderTarget.samples = value;
  83777. },
  83778. enumerable: true,
  83779. configurable: true
  83780. });
  83781. /**
  83782. * Disposes the renderer and frees up associated resources.
  83783. */
  83784. GeometryBufferRenderer.prototype.dispose = function () {
  83785. this.getGBuffer().dispose();
  83786. };
  83787. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  83788. var _this = this;
  83789. var engine = this._scene.getEngine();
  83790. var count = this._enablePosition ? 3 : 2;
  83791. 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 });
  83792. if (!this.isSupported) {
  83793. return;
  83794. }
  83795. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83796. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83797. this._multiRenderTarget.refreshRate = 1;
  83798. this._multiRenderTarget.renderParticles = false;
  83799. this._multiRenderTarget.renderList = null;
  83800. // set default depth value to 1.0 (far away)
  83801. this._multiRenderTarget.onClearObservable.add(function (engine) {
  83802. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  83803. });
  83804. // Custom render function
  83805. var renderSubMesh = function (subMesh) {
  83806. var mesh = subMesh.getRenderingMesh();
  83807. var scene = _this._scene;
  83808. var engine = scene.getEngine();
  83809. var material = subMesh.getMaterial();
  83810. if (!material) {
  83811. return;
  83812. }
  83813. // Culling
  83814. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  83815. // Managing instances
  83816. var batch = mesh._getInstancesRenderList(subMesh._id);
  83817. if (batch.mustReturn) {
  83818. return;
  83819. }
  83820. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  83821. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  83822. engine.enableEffect(_this._effect);
  83823. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  83824. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83825. _this._effect.setMatrix("view", scene.getViewMatrix());
  83826. // Alpha test
  83827. if (material && material.needAlphaTesting()) {
  83828. var alphaTexture = material.getAlphaTestTexture();
  83829. if (alphaTexture) {
  83830. _this._effect.setTexture("diffuseSampler", alphaTexture);
  83831. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83832. }
  83833. }
  83834. // Bones
  83835. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83836. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83837. }
  83838. // Draw
  83839. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  83840. }
  83841. };
  83842. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83843. var index;
  83844. if (depthOnlySubMeshes.length) {
  83845. engine.setColorWrite(false);
  83846. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83847. renderSubMesh(depthOnlySubMeshes.data[index]);
  83848. }
  83849. engine.setColorWrite(true);
  83850. }
  83851. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83852. renderSubMesh(opaqueSubMeshes.data[index]);
  83853. }
  83854. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83855. renderSubMesh(alphaTestSubMeshes.data[index]);
  83856. }
  83857. };
  83858. };
  83859. return GeometryBufferRenderer;
  83860. }());
  83861. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  83862. })(BABYLON || (BABYLON = {}));
  83863. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  83864. var BABYLON;
  83865. (function (BABYLON) {
  83866. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  83867. get: function () {
  83868. this._geometryBufferRenderer;
  83869. },
  83870. set: function (value) {
  83871. if (value && value.isSupported) {
  83872. this._geometryBufferRenderer = value;
  83873. }
  83874. },
  83875. enumerable: true,
  83876. configurable: true
  83877. });
  83878. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  83879. if (ratio === void 0) { ratio = 1; }
  83880. if (this._geometryBufferRenderer) {
  83881. return this._geometryBufferRenderer;
  83882. }
  83883. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  83884. if (!this._geometryBufferRenderer.isSupported) {
  83885. this._geometryBufferRenderer = null;
  83886. }
  83887. return this._geometryBufferRenderer;
  83888. };
  83889. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  83890. if (!this._geometryBufferRenderer) {
  83891. return;
  83892. }
  83893. this._geometryBufferRenderer.dispose();
  83894. this._geometryBufferRenderer = null;
  83895. };
  83896. /**
  83897. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  83898. * in several rendering techniques.
  83899. */
  83900. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  83901. /**
  83902. * Creates a new instance of the component for the given scene
  83903. * @param scene Defines the scene to register the component in
  83904. */
  83905. function GeometryBufferRendererSceneComponent(scene) {
  83906. /**
  83907. * The component name helpful to identify the component in the list of scene components.
  83908. */
  83909. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  83910. this.scene = scene;
  83911. }
  83912. /**
  83913. * Registers the component in a given scene
  83914. */
  83915. GeometryBufferRendererSceneComponent.prototype.register = function () {
  83916. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  83917. };
  83918. /**
  83919. * Rebuilds the elements related to this component in case of
  83920. * context lost for instance.
  83921. */
  83922. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  83923. // Nothing to do for this component
  83924. };
  83925. /**
  83926. * Disposes the component and the associated ressources
  83927. */
  83928. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  83929. // Nothing to do for this component
  83930. };
  83931. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  83932. if (this.scene._geometryBufferRenderer) {
  83933. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  83934. }
  83935. };
  83936. return GeometryBufferRendererSceneComponent;
  83937. }());
  83938. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  83939. })(BABYLON || (BABYLON = {}));
  83940. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  83941. var BABYLON;
  83942. (function (BABYLON) {
  83943. /**
  83944. * Render pipeline to produce ssao effect
  83945. */
  83946. var SSAORenderingPipeline = /** @class */ (function (_super) {
  83947. __extends(SSAORenderingPipeline, _super);
  83948. /**
  83949. * @constructor
  83950. * @param name - The rendering pipeline name
  83951. * @param scene - The scene linked to this pipeline
  83952. * @param 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 }
  83953. * @param cameras - The array of cameras that the rendering pipeline will be attached to
  83954. */
  83955. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  83956. var _this = _super.call(this, scene.getEngine(), name) || this;
  83957. // Members
  83958. /**
  83959. * @ignore
  83960. * The PassPostProcess id in the pipeline that contains the original scene color
  83961. */
  83962. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  83963. /**
  83964. * @ignore
  83965. * The SSAO PostProcess id in the pipeline
  83966. */
  83967. _this.SSAORenderEffect = "SSAORenderEffect";
  83968. /**
  83969. * @ignore
  83970. * The horizontal blur PostProcess id in the pipeline
  83971. */
  83972. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  83973. /**
  83974. * @ignore
  83975. * The vertical blur PostProcess id in the pipeline
  83976. */
  83977. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  83978. /**
  83979. * @ignore
  83980. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  83981. */
  83982. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  83983. /**
  83984. * The output strength of the SSAO post-process. Default value is 1.0.
  83985. */
  83986. _this.totalStrength = 1.0;
  83987. /**
  83988. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  83989. */
  83990. _this.radius = 0.0001;
  83991. /**
  83992. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  83993. * Must not be equal to fallOff and superior to fallOff.
  83994. * Default value is 0.975
  83995. */
  83996. _this.area = 0.0075;
  83997. /**
  83998. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  83999. * Must not be equal to area and inferior to area.
  84000. * Default value is 0.0
  84001. */
  84002. _this.fallOff = 0.000001;
  84003. /**
  84004. * The base color of the SSAO post-process
  84005. * The final result is "base + ssao" between [0, 1]
  84006. */
  84007. _this.base = 0.5;
  84008. _this._firstUpdate = true;
  84009. _this._scene = scene;
  84010. // Set up assets
  84011. _this._createRandomTexture();
  84012. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  84013. var ssaoRatio = ratio.ssaoRatio || ratio;
  84014. var combineRatio = ratio.combineRatio || ratio;
  84015. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  84016. _this._createSSAOPostProcess(ssaoRatio);
  84017. _this._createBlurPostProcess(ssaoRatio);
  84018. _this._createSSAOCombinePostProcess(combineRatio);
  84019. // Set up pipeline
  84020. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  84021. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  84022. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  84023. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  84024. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  84025. // Finish
  84026. scene.postProcessRenderPipelineManager.addPipeline(_this);
  84027. if (cameras) {
  84028. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  84029. }
  84030. return _this;
  84031. }
  84032. // Public Methods
  84033. /**
  84034. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  84035. */
  84036. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  84037. if (disableDepthRender === void 0) { disableDepthRender = false; }
  84038. for (var i = 0; i < this._scene.cameras.length; i++) {
  84039. var camera = this._scene.cameras[i];
  84040. this._originalColorPostProcess.dispose(camera);
  84041. this._ssaoPostProcess.dispose(camera);
  84042. this._blurHPostProcess.dispose(camera);
  84043. this._blurVPostProcess.dispose(camera);
  84044. this._ssaoCombinePostProcess.dispose(camera);
  84045. }
  84046. this._randomTexture.dispose();
  84047. if (disableDepthRender) {
  84048. this._scene.disableDepthRenderer();
  84049. }
  84050. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  84051. _super.prototype.dispose.call(this);
  84052. };
  84053. // Private Methods
  84054. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  84055. var _this = this;
  84056. var size = 16;
  84057. 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);
  84058. 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);
  84059. this._blurHPostProcess.onActivateObservable.add(function () {
  84060. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  84061. _this._blurHPostProcess.kernel = size * dw;
  84062. });
  84063. this._blurVPostProcess.onActivateObservable.add(function () {
  84064. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  84065. _this._blurVPostProcess.kernel = size * dw;
  84066. });
  84067. };
  84068. /** @hidden */
  84069. SSAORenderingPipeline.prototype._rebuild = function () {
  84070. this._firstUpdate = true;
  84071. _super.prototype._rebuild.call(this);
  84072. };
  84073. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  84074. var _this = this;
  84075. var numSamples = 16;
  84076. var sampleSphere = [
  84077. 0.5381, 0.1856, -0.4319,
  84078. 0.1379, 0.2486, 0.4430,
  84079. 0.3371, 0.5679, -0.0057,
  84080. -0.6999, -0.0451, -0.0019,
  84081. 0.0689, -0.1598, -0.8547,
  84082. 0.0560, 0.0069, -0.1843,
  84083. -0.0146, 0.1402, 0.0762,
  84084. 0.0100, -0.1924, -0.0344,
  84085. -0.3577, -0.5301, -0.4358,
  84086. -0.3169, 0.1063, 0.0158,
  84087. 0.0103, -0.5869, 0.0046,
  84088. -0.0897, -0.4940, 0.3287,
  84089. 0.7119, -0.0154, -0.0918,
  84090. -0.0533, 0.0596, -0.5411,
  84091. 0.0352, -0.0631, 0.5460,
  84092. -0.4776, 0.2847, -0.0271
  84093. ];
  84094. var samplesFactor = 1.0 / numSamples;
  84095. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  84096. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  84097. "area", "fallOff", "base", "range", "viewport"
  84098. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  84099. this._ssaoPostProcess.onApply = function (effect) {
  84100. if (_this._firstUpdate) {
  84101. effect.setArray3("sampleSphere", sampleSphere);
  84102. effect.setFloat("samplesFactor", samplesFactor);
  84103. effect.setFloat("randTextureTiles", 4.0);
  84104. }
  84105. effect.setFloat("totalStrength", _this.totalStrength);
  84106. effect.setFloat("radius", _this.radius);
  84107. effect.setFloat("area", _this.area);
  84108. effect.setFloat("fallOff", _this.fallOff);
  84109. effect.setFloat("base", _this.base);
  84110. effect.setTexture("textureSampler", _this._depthTexture);
  84111. effect.setTexture("randomSampler", _this._randomTexture);
  84112. };
  84113. };
  84114. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  84115. var _this = this;
  84116. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  84117. this._ssaoCombinePostProcess.onApply = function (effect) {
  84118. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  84119. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  84120. };
  84121. };
  84122. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  84123. var size = 512;
  84124. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84125. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  84126. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  84127. var context = this._randomTexture.getContext();
  84128. var rand = function (min, max) {
  84129. return Math.random() * (max - min) + min;
  84130. };
  84131. var randVector = BABYLON.Vector3.Zero();
  84132. for (var x = 0; x < size; x++) {
  84133. for (var y = 0; y < size; y++) {
  84134. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  84135. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  84136. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  84137. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  84138. context.fillRect(x, y, 1, 1);
  84139. }
  84140. }
  84141. this._randomTexture.update(false);
  84142. };
  84143. __decorate([
  84144. BABYLON.serialize()
  84145. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  84146. __decorate([
  84147. BABYLON.serialize()
  84148. ], SSAORenderingPipeline.prototype, "radius", void 0);
  84149. __decorate([
  84150. BABYLON.serialize()
  84151. ], SSAORenderingPipeline.prototype, "area", void 0);
  84152. __decorate([
  84153. BABYLON.serialize()
  84154. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  84155. __decorate([
  84156. BABYLON.serialize()
  84157. ], SSAORenderingPipeline.prototype, "base", void 0);
  84158. return SSAORenderingPipeline;
  84159. }(BABYLON.PostProcessRenderPipeline));
  84160. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  84161. })(BABYLON || (BABYLON = {}));
  84162. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  84163. var BABYLON;
  84164. (function (BABYLON) {
  84165. /**
  84166. * Render pipeline to produce ssao effect
  84167. */
  84168. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  84169. __extends(SSAO2RenderingPipeline, _super);
  84170. /**
  84171. * @constructor
  84172. * @param name The rendering pipeline name
  84173. * @param scene The scene linked to this pipeline
  84174. * @param 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 }
  84175. * @param cameras The array of cameras that the rendering pipeline will be attached to
  84176. */
  84177. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  84178. var _this = _super.call(this, scene.getEngine(), name) || this;
  84179. // Members
  84180. /**
  84181. * @ignore
  84182. * The PassPostProcess id in the pipeline that contains the original scene color
  84183. */
  84184. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  84185. /**
  84186. * @ignore
  84187. * The SSAO PostProcess id in the pipeline
  84188. */
  84189. _this.SSAORenderEffect = "SSAORenderEffect";
  84190. /**
  84191. * @ignore
  84192. * The horizontal blur PostProcess id in the pipeline
  84193. */
  84194. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  84195. /**
  84196. * @ignore
  84197. * The vertical blur PostProcess id in the pipeline
  84198. */
  84199. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  84200. /**
  84201. * @ignore
  84202. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  84203. */
  84204. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  84205. /**
  84206. * The output strength of the SSAO post-process. Default value is 1.0.
  84207. */
  84208. _this.totalStrength = 1.0;
  84209. /**
  84210. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  84211. */
  84212. _this.maxZ = 100.0;
  84213. /**
  84214. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  84215. */
  84216. _this.minZAspect = 0.2;
  84217. _this._samples = 8;
  84218. _this._textureSamples = 1;
  84219. _this._expensiveBlur = true;
  84220. /**
  84221. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  84222. */
  84223. _this.radius = 2.0;
  84224. /**
  84225. * The base color of the SSAO post-process
  84226. * The final result is "base + ssao" between [0, 1]
  84227. */
  84228. _this.base = 0;
  84229. _this._firstUpdate = true;
  84230. _this._bits = new Uint32Array(1);
  84231. _this._scene = scene;
  84232. _this._ratio = ratio;
  84233. if (!_this.isSupported) {
  84234. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  84235. return _this;
  84236. }
  84237. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  84238. var blurRatio = _this._ratio.blurRatio || ratio;
  84239. // Set up assets
  84240. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  84241. _this._createRandomTexture();
  84242. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  84243. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  84244. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  84245. _this._originalColorPostProcess.samples = _this.textureSamples;
  84246. _this._createSSAOPostProcess(1.0);
  84247. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  84248. _this._createSSAOCombinePostProcess(blurRatio);
  84249. // Set up pipeline
  84250. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  84251. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  84252. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  84253. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  84254. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  84255. // Finish
  84256. scene.postProcessRenderPipelineManager.addPipeline(_this);
  84257. if (cameras) {
  84258. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  84259. }
  84260. return _this;
  84261. }
  84262. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  84263. get: function () {
  84264. return this._samples;
  84265. },
  84266. /**
  84267. * Number of samples used for the SSAO calculations. Default value is 8
  84268. */
  84269. set: function (n) {
  84270. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  84271. this._samples = n;
  84272. this._sampleSphere = this._generateHemisphere();
  84273. this._firstUpdate = true;
  84274. },
  84275. enumerable: true,
  84276. configurable: true
  84277. });
  84278. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  84279. get: function () {
  84280. return this._textureSamples;
  84281. },
  84282. /**
  84283. * Number of samples to use for antialiasing
  84284. */
  84285. set: function (n) {
  84286. this._textureSamples = n;
  84287. this._originalColorPostProcess.samples = n;
  84288. this._blurHPostProcess.samples = n;
  84289. this._blurVPostProcess.samples = n;
  84290. this._ssaoPostProcess.samples = n;
  84291. this._ssaoCombinePostProcess.samples = n;
  84292. },
  84293. enumerable: true,
  84294. configurable: true
  84295. });
  84296. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  84297. get: function () {
  84298. return this._expensiveBlur;
  84299. },
  84300. /**
  84301. * If bilateral blur should be used
  84302. */
  84303. set: function (b) {
  84304. 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"]);
  84305. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  84306. this._expensiveBlur = b;
  84307. this._firstUpdate = true;
  84308. },
  84309. enumerable: true,
  84310. configurable: true
  84311. });
  84312. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  84313. /**
  84314. * Support test.
  84315. */
  84316. get: function () {
  84317. var engine = BABYLON.Engine.LastCreatedEngine;
  84318. if (!engine) {
  84319. return false;
  84320. }
  84321. return engine.getCaps().drawBuffersExtension;
  84322. },
  84323. enumerable: true,
  84324. configurable: true
  84325. });
  84326. // Public Methods
  84327. /**
  84328. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  84329. */
  84330. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  84331. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  84332. for (var i = 0; i < this._scene.cameras.length; i++) {
  84333. var camera = this._scene.cameras[i];
  84334. this._originalColorPostProcess.dispose(camera);
  84335. this._ssaoPostProcess.dispose(camera);
  84336. this._blurHPostProcess.dispose(camera);
  84337. this._blurVPostProcess.dispose(camera);
  84338. this._ssaoCombinePostProcess.dispose(camera);
  84339. }
  84340. this._randomTexture.dispose();
  84341. if (disableGeometryBufferRenderer) {
  84342. this._scene.disableGeometryBufferRenderer();
  84343. }
  84344. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  84345. _super.prototype.dispose.call(this);
  84346. };
  84347. // Private Methods
  84348. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  84349. var _this = this;
  84350. this._samplerOffsets = [];
  84351. var expensive = this.expensiveBlur;
  84352. for (var i = -8; i < 8; i++) {
  84353. this._samplerOffsets.push(i * 2 + 0.5);
  84354. }
  84355. 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");
  84356. this._blurHPostProcess.onApply = function (effect) {
  84357. if (!_this._scene.activeCamera) {
  84358. return;
  84359. }
  84360. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  84361. effect.setFloat("near", _this._scene.activeCamera.minZ);
  84362. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  84363. effect.setFloat("radius", _this.radius);
  84364. effect.setTexture("depthSampler", _this._depthTexture);
  84365. if (_this._firstUpdate) {
  84366. effect.setArray("samplerOffsets", _this._samplerOffsets);
  84367. }
  84368. };
  84369. 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");
  84370. this._blurVPostProcess.onApply = function (effect) {
  84371. if (!_this._scene.activeCamera) {
  84372. return;
  84373. }
  84374. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  84375. effect.setFloat("near", _this._scene.activeCamera.minZ);
  84376. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  84377. effect.setFloat("radius", _this.radius);
  84378. effect.setTexture("depthSampler", _this._depthTexture);
  84379. if (_this._firstUpdate) {
  84380. effect.setArray("samplerOffsets", _this._samplerOffsets);
  84381. _this._firstUpdate = false;
  84382. }
  84383. };
  84384. this._blurHPostProcess.samples = this.textureSamples;
  84385. this._blurVPostProcess.samples = this.textureSamples;
  84386. };
  84387. /** @hidden */
  84388. SSAO2RenderingPipeline.prototype._rebuild = function () {
  84389. this._firstUpdate = true;
  84390. _super.prototype._rebuild.call(this);
  84391. };
  84392. //Van der Corput radical inverse
  84393. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  84394. this._bits[0] = i;
  84395. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  84396. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  84397. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  84398. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  84399. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  84400. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  84401. };
  84402. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  84403. return [i / n, this._radicalInverse_VdC(i)];
  84404. };
  84405. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  84406. var phi = v * 2.0 * Math.PI;
  84407. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  84408. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  84409. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  84410. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  84411. };
  84412. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  84413. var numSamples = this.samples;
  84414. var result = [];
  84415. var vector;
  84416. var i = 0;
  84417. while (i < numSamples) {
  84418. if (numSamples < 16) {
  84419. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  84420. }
  84421. else {
  84422. var rand = this._hammersley(i, numSamples);
  84423. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  84424. }
  84425. result.push(vector.x, vector.y, vector.z);
  84426. i++;
  84427. }
  84428. return result;
  84429. };
  84430. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  84431. var _this = this;
  84432. var numSamples = this.samples;
  84433. this._sampleSphere = this._generateHemisphere();
  84434. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  84435. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  84436. "base", "range", "projection", "near", "far", "texelSize",
  84437. "xViewport", "yViewport", "maxZ", "minZAspect"
  84438. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  84439. this._ssaoPostProcess.onApply = function (effect) {
  84440. if (_this._firstUpdate) {
  84441. effect.setArray3("sampleSphere", _this._sampleSphere);
  84442. effect.setFloat("randTextureTiles", 32.0);
  84443. }
  84444. if (!_this._scene.activeCamera) {
  84445. return;
  84446. }
  84447. effect.setFloat("samplesFactor", 1 / _this.samples);
  84448. effect.setFloat("totalStrength", _this.totalStrength);
  84449. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  84450. effect.setFloat("radius", _this.radius);
  84451. effect.setFloat("maxZ", _this.maxZ);
  84452. effect.setFloat("minZAspect", _this.minZAspect);
  84453. effect.setFloat("base", _this.base);
  84454. effect.setFloat("near", _this._scene.activeCamera.minZ);
  84455. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  84456. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  84457. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  84458. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  84459. effect.setTexture("textureSampler", _this._depthTexture);
  84460. effect.setTexture("normalSampler", _this._normalTexture);
  84461. effect.setTexture("randomSampler", _this._randomTexture);
  84462. };
  84463. this._ssaoPostProcess.samples = this.textureSamples;
  84464. };
  84465. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  84466. var _this = this;
  84467. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  84468. this._ssaoCombinePostProcess.onApply = function (effect) {
  84469. var viewport = _this._scene.activeCamera.viewport;
  84470. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  84471. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  84472. };
  84473. this._ssaoCombinePostProcess.samples = this.textureSamples;
  84474. };
  84475. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  84476. var size = 128;
  84477. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84478. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  84479. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  84480. var context = this._randomTexture.getContext();
  84481. var rand = function (min, max) {
  84482. return Math.random() * (max - min) + min;
  84483. };
  84484. var randVector = BABYLON.Vector3.Zero();
  84485. for (var x = 0; x < size; x++) {
  84486. for (var y = 0; y < size; y++) {
  84487. randVector.x = rand(0.0, 1.0);
  84488. randVector.y = rand(0.0, 1.0);
  84489. randVector.z = 0.0;
  84490. randVector.normalize();
  84491. randVector.scaleInPlace(255);
  84492. randVector.x = Math.floor(randVector.x);
  84493. randVector.y = Math.floor(randVector.y);
  84494. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  84495. context.fillRect(x, y, 1, 1);
  84496. }
  84497. }
  84498. this._randomTexture.update(false);
  84499. };
  84500. /**
  84501. * Serialize the rendering pipeline (Used when exporting)
  84502. * @returns the serialized object
  84503. */
  84504. SSAO2RenderingPipeline.prototype.serialize = function () {
  84505. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  84506. serializationObject.customType = "SSAO2RenderingPipeline";
  84507. return serializationObject;
  84508. };
  84509. /**
  84510. * Parse the serialized pipeline
  84511. * @param source Source pipeline.
  84512. * @param scene The scene to load the pipeline to.
  84513. * @param rootUrl The URL of the serialized pipeline.
  84514. * @returns An instantiated pipeline from the serialized object.
  84515. */
  84516. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  84517. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  84518. };
  84519. __decorate([
  84520. BABYLON.serialize()
  84521. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  84522. __decorate([
  84523. BABYLON.serialize()
  84524. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  84525. __decorate([
  84526. BABYLON.serialize()
  84527. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  84528. __decorate([
  84529. BABYLON.serialize("samples")
  84530. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  84531. __decorate([
  84532. BABYLON.serialize("textureSamples")
  84533. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  84534. __decorate([
  84535. BABYLON.serialize()
  84536. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  84537. __decorate([
  84538. BABYLON.serialize("expensiveBlur")
  84539. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  84540. __decorate([
  84541. BABYLON.serialize()
  84542. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  84543. __decorate([
  84544. BABYLON.serialize()
  84545. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  84546. return SSAO2RenderingPipeline;
  84547. }(BABYLON.PostProcessRenderPipeline));
  84548. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  84549. })(BABYLON || (BABYLON = {}));
  84550. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  84551. var BABYLON;
  84552. (function (BABYLON) {
  84553. /**
  84554. * BABYLON.JS Chromatic Aberration GLSL Shader
  84555. * Author: Olivier Guyot
  84556. * Separates very slightly R, G and B colors on the edges of the screen
  84557. * Inspired by Francois Tarlier & Martins Upitis
  84558. */
  84559. var LensRenderingPipeline = /** @class */ (function (_super) {
  84560. __extends(LensRenderingPipeline, _super);
  84561. /**
  84562. * @constructor
  84563. *
  84564. * Effect parameters are as follow:
  84565. * {
  84566. * chromatic_aberration: number; // from 0 to x (1 for realism)
  84567. * edge_blur: number; // from 0 to x (1 for realism)
  84568. * distortion: number; // from 0 to x (1 for realism)
  84569. * grain_amount: number; // from 0 to 1
  84570. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  84571. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  84572. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  84573. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  84574. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  84575. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  84576. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  84577. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  84578. * }
  84579. * Note: if an effect parameter is unset, effect is disabled
  84580. *
  84581. * @param name The rendering pipeline name
  84582. * @param parameters - An object containing all parameters (see above)
  84583. * @param scene The scene linked to this pipeline
  84584. * @param 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)
  84585. * @param cameras The array of cameras that the rendering pipeline will be attached to
  84586. */
  84587. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  84588. if (ratio === void 0) { ratio = 1.0; }
  84589. var _this = _super.call(this, scene.getEngine(), name) || this;
  84590. // Lens effects can be of the following:
  84591. // - chromatic aberration (slight shift of RGB colors)
  84592. // - blur on the edge of the lens
  84593. // - lens distortion
  84594. // - depth-of-field blur & highlights enhancing
  84595. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  84596. // - grain effect (noise or custom texture)
  84597. // Two additional texture samplers are needed:
  84598. // - depth map (for depth-of-field)
  84599. // - grain texture
  84600. /**
  84601. * @ignore
  84602. * The chromatic aberration PostProcess id in the pipeline
  84603. */
  84604. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  84605. /**
  84606. * @ignore
  84607. * The highlights enhancing PostProcess id in the pipeline
  84608. */
  84609. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  84610. /**
  84611. * @ignore
  84612. * The depth-of-field PostProcess id in the pipeline
  84613. */
  84614. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  84615. _this._scene = scene;
  84616. // Fetch texture samplers
  84617. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  84618. if (parameters.grain_texture) {
  84619. _this._grainTexture = parameters.grain_texture;
  84620. }
  84621. else {
  84622. _this._createGrainTexture();
  84623. }
  84624. // save parameters
  84625. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  84626. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  84627. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  84628. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  84629. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  84630. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  84631. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  84632. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  84633. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  84634. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  84635. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  84636. // Create effects
  84637. _this._createChromaticAberrationPostProcess(ratio);
  84638. _this._createHighlightsPostProcess(ratio);
  84639. _this._createDepthOfFieldPostProcess(ratio / 4);
  84640. // Set up pipeline
  84641. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  84642. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  84643. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  84644. if (_this._highlightsGain === -1) {
  84645. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  84646. }
  84647. // Finish
  84648. scene.postProcessRenderPipelineManager.addPipeline(_this);
  84649. if (cameras) {
  84650. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  84651. }
  84652. return _this;
  84653. }
  84654. // public methods (self explanatory)
  84655. /**
  84656. * Sets the amount of blur at the edges
  84657. * @param amount blur amount
  84658. */
  84659. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  84660. /**
  84661. * Sets edge blur to 0
  84662. */
  84663. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  84664. /**
  84665. * Sets the amout of grain
  84666. * @param amount Amount of grain
  84667. */
  84668. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  84669. /**
  84670. * Set grain amount to 0
  84671. */
  84672. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  84673. /**
  84674. * Sets the chromatic aberration amount
  84675. * @param amount amount of chromatic aberration
  84676. */
  84677. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  84678. /**
  84679. * Sets chromatic aberration amount to 0
  84680. */
  84681. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  84682. /**
  84683. * Sets the EdgeDistortion amount
  84684. * @param amount amount of EdgeDistortion
  84685. */
  84686. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  84687. /**
  84688. * Sets edge distortion to 0
  84689. */
  84690. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  84691. /**
  84692. * Sets the FocusDistance amount
  84693. * @param amount amount of FocusDistance
  84694. */
  84695. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  84696. /**
  84697. * Disables depth of field
  84698. */
  84699. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  84700. /**
  84701. * Sets the Aperture amount
  84702. * @param amount amount of Aperture
  84703. */
  84704. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  84705. /**
  84706. * Sets the DarkenOutOfFocus amount
  84707. * @param amount amount of DarkenOutOfFocus
  84708. */
  84709. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  84710. /**
  84711. * Creates a pentagon bokeh effect
  84712. */
  84713. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  84714. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  84715. };
  84716. /**
  84717. * Disables the pentagon bokeh effect
  84718. */
  84719. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  84720. this._highlightsPostProcess.updateEffect();
  84721. };
  84722. /**
  84723. * Enables noise blur
  84724. */
  84725. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  84726. /**
  84727. * Disables noise blur
  84728. */
  84729. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  84730. /**
  84731. * Sets the HighlightsGain amount
  84732. * @param amount amount of HighlightsGain
  84733. */
  84734. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  84735. this._highlightsGain = amount;
  84736. };
  84737. /**
  84738. * Sets the HighlightsThreshold amount
  84739. * @param amount amount of HighlightsThreshold
  84740. */
  84741. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  84742. if (this._highlightsGain === -1) {
  84743. this._highlightsGain = 1.0;
  84744. }
  84745. this._highlightsThreshold = amount;
  84746. };
  84747. /**
  84748. * Disables highlights
  84749. */
  84750. LensRenderingPipeline.prototype.disableHighlights = function () {
  84751. this._highlightsGain = -1;
  84752. };
  84753. /**
  84754. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  84755. * @param disableDepthRender If the scens depth rendering should be disabled (default: false)
  84756. */
  84757. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  84758. if (disableDepthRender === void 0) { disableDepthRender = false; }
  84759. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  84760. this._chromaticAberrationPostProcess = null;
  84761. this._highlightsPostProcess = null;
  84762. this._depthOfFieldPostProcess = null;
  84763. this._grainTexture.dispose();
  84764. if (disableDepthRender) {
  84765. this._scene.disableDepthRenderer();
  84766. }
  84767. };
  84768. // colors shifting and distortion
  84769. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  84770. var _this = this;
  84771. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  84772. [], // samplers
  84773. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  84774. this._chromaticAberrationPostProcess.onApply = function (effect) {
  84775. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  84776. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  84777. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  84778. effect.setFloat('radialIntensity', 1);
  84779. effect.setFloat2('direction', 17, 17);
  84780. effect.setFloat2('centerPosition', 0.5, 0.5);
  84781. };
  84782. };
  84783. // highlights enhancing
  84784. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  84785. var _this = this;
  84786. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  84787. [], // samplers
  84788. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  84789. this._highlightsPostProcess.onApply = function (effect) {
  84790. effect.setFloat('gain', _this._highlightsGain);
  84791. effect.setFloat('threshold', _this._highlightsThreshold);
  84792. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  84793. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  84794. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  84795. };
  84796. };
  84797. // colors shifting and distortion
  84798. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  84799. var _this = this;
  84800. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  84801. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  84802. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  84803. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  84804. this._depthOfFieldPostProcess.onApply = function (effect) {
  84805. effect.setTexture("depthSampler", _this._depthTexture);
  84806. effect.setTexture("grainSampler", _this._grainTexture);
  84807. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  84808. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  84809. effect.setFloat('grain_amount', _this._grainAmount);
  84810. effect.setBool('blur_noise', _this._blurNoise);
  84811. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  84812. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  84813. effect.setFloat('distortion', _this._distortion);
  84814. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  84815. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  84816. effect.setFloat('aperture', _this._dofAperture);
  84817. effect.setFloat('darken', _this._dofDarken);
  84818. effect.setFloat('edge_blur', _this._edgeBlur);
  84819. effect.setBool('highlights', (_this._highlightsGain !== -1));
  84820. if (_this._scene.activeCamera) {
  84821. effect.setFloat('near', _this._scene.activeCamera.minZ);
  84822. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  84823. }
  84824. };
  84825. };
  84826. // creates a black and white random noise texture, 512x512
  84827. LensRenderingPipeline.prototype._createGrainTexture = function () {
  84828. var size = 512;
  84829. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84830. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  84831. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  84832. var context = this._grainTexture.getContext();
  84833. var rand = function (min, max) {
  84834. return Math.random() * (max - min) + min;
  84835. };
  84836. var value;
  84837. for (var x = 0; x < size; x++) {
  84838. for (var y = 0; y < size; y++) {
  84839. value = Math.floor(rand(0.42, 0.58) * 255);
  84840. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  84841. context.fillRect(x, y, 1, 1);
  84842. }
  84843. }
  84844. this._grainTexture.update(false);
  84845. };
  84846. return LensRenderingPipeline;
  84847. }(BABYLON.PostProcessRenderPipeline));
  84848. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  84849. })(BABYLON || (BABYLON = {}));
  84850. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  84851. var BABYLON;
  84852. (function (BABYLON) {
  84853. /**
  84854. * Standard rendering pipeline
  84855. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  84856. * @see https://doc.babylonjs.com/how_to/using_standard_rendering_pipeline
  84857. */
  84858. var StandardRenderingPipeline = /** @class */ (function (_super) {
  84859. __extends(StandardRenderingPipeline, _super);
  84860. /**
  84861. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  84862. * @constructor
  84863. * @param name The rendering pipeline name
  84864. * @param scene The scene linked to this pipeline
  84865. * @param 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)
  84866. * @param originalPostProcess the custom original color post-process. Must be "reusable". Can be null.
  84867. * @param cameras The array of cameras that the rendering pipeline will be attached to
  84868. */
  84869. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  84870. if (originalPostProcess === void 0) { originalPostProcess = null; }
  84871. var _this = _super.call(this, scene.getEngine(), name) || this;
  84872. /**
  84873. * Post-process used to down scale an image x4
  84874. */
  84875. _this.downSampleX4PostProcess = null;
  84876. /**
  84877. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  84878. */
  84879. _this.brightPassPostProcess = null;
  84880. /**
  84881. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  84882. */
  84883. _this.blurHPostProcesses = [];
  84884. /**
  84885. * Post-process array storing all the vertical blur post-processes used by the pipeline
  84886. */
  84887. _this.blurVPostProcesses = [];
  84888. /**
  84889. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  84890. */
  84891. _this.textureAdderPostProcess = null;
  84892. /**
  84893. * Post-process used to create volumetric lighting effect
  84894. */
  84895. _this.volumetricLightPostProcess = null;
  84896. /**
  84897. * Post-process used to smooth the previous volumetric light post-process on the X axis
  84898. */
  84899. _this.volumetricLightSmoothXPostProcess = null;
  84900. /**
  84901. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  84902. */
  84903. _this.volumetricLightSmoothYPostProcess = null;
  84904. /**
  84905. * Post-process used to merge the volumetric light effect and the real scene color
  84906. */
  84907. _this.volumetricLightMergePostProces = null;
  84908. /**
  84909. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  84910. */
  84911. _this.volumetricLightFinalPostProcess = null;
  84912. /**
  84913. * Base post-process used to calculate the average luminance of the final image for HDR
  84914. */
  84915. _this.luminancePostProcess = null;
  84916. /**
  84917. * Post-processes used to create down sample post-processes in order to get
  84918. * the average luminance of the final image for HDR
  84919. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  84920. */
  84921. _this.luminanceDownSamplePostProcesses = [];
  84922. /**
  84923. * Post-process used to create a HDR effect (light adaptation)
  84924. */
  84925. _this.hdrPostProcess = null;
  84926. /**
  84927. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  84928. */
  84929. _this.textureAdderFinalPostProcess = null;
  84930. /**
  84931. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  84932. */
  84933. _this.lensFlareFinalPostProcess = null;
  84934. /**
  84935. * Post-process used to merge the final HDR post-process and the real scene color
  84936. */
  84937. _this.hdrFinalPostProcess = null;
  84938. /**
  84939. * Post-process used to create a lens flare effect
  84940. */
  84941. _this.lensFlarePostProcess = null;
  84942. /**
  84943. * Post-process that merges the result of the lens flare post-process and the real scene color
  84944. */
  84945. _this.lensFlareComposePostProcess = null;
  84946. /**
  84947. * Post-process used to create a motion blur effect
  84948. */
  84949. _this.motionBlurPostProcess = null;
  84950. /**
  84951. * Post-process used to create a depth of field effect
  84952. */
  84953. _this.depthOfFieldPostProcess = null;
  84954. /**
  84955. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  84956. */
  84957. _this.fxaaPostProcess = null;
  84958. // Values
  84959. /**
  84960. * Represents the brightness threshold in order to configure the illuminated surfaces
  84961. */
  84962. _this.brightThreshold = 1.0;
  84963. /**
  84964. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  84965. */
  84966. _this.blurWidth = 512.0;
  84967. /**
  84968. * Sets if the blur for highlighted surfaces must be only horizontal
  84969. */
  84970. _this.horizontalBlur = false;
  84971. /**
  84972. * Sets the overall exposure used by the pipeline
  84973. */
  84974. _this.exposure = 1.0;
  84975. /**
  84976. * Texture used typically to simulate "dirty" on camera lens
  84977. */
  84978. _this.lensTexture = null;
  84979. /**
  84980. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  84981. */
  84982. _this.volumetricLightCoefficient = 0.2;
  84983. /**
  84984. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  84985. */
  84986. _this.volumetricLightPower = 4.0;
  84987. /**
  84988. * Used the set the blur intensity to smooth the volumetric lights
  84989. */
  84990. _this.volumetricLightBlurScale = 64.0;
  84991. /**
  84992. * Light (spot or directional) used to generate the volumetric lights rays
  84993. * The source light must have a shadow generate so the pipeline can get its
  84994. * depth map
  84995. */
  84996. _this.sourceLight = null;
  84997. /**
  84998. * For eye adaptation, represents the minimum luminance the eye can see
  84999. */
  85000. _this.hdrMinimumLuminance = 1.0;
  85001. /**
  85002. * For eye adaptation, represents the decrease luminance speed
  85003. */
  85004. _this.hdrDecreaseRate = 0.5;
  85005. /**
  85006. * For eye adaptation, represents the increase luminance speed
  85007. */
  85008. _this.hdrIncreaseRate = 0.5;
  85009. /**
  85010. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  85011. */
  85012. _this.lensColorTexture = null;
  85013. /**
  85014. * The overall strengh for the lens flare effect
  85015. */
  85016. _this.lensFlareStrength = 20.0;
  85017. /**
  85018. * Dispersion coefficient for lens flare ghosts
  85019. */
  85020. _this.lensFlareGhostDispersal = 1.4;
  85021. /**
  85022. * Main lens flare halo width
  85023. */
  85024. _this.lensFlareHaloWidth = 0.7;
  85025. /**
  85026. * Based on the lens distortion effect, defines how much the lens flare result
  85027. * is distorted
  85028. */
  85029. _this.lensFlareDistortionStrength = 16.0;
  85030. /**
  85031. * Lens star texture must be used to simulate rays on the flares and is available
  85032. * in the documentation
  85033. */
  85034. _this.lensStarTexture = null;
  85035. /**
  85036. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  85037. * flare effect by taking account of the dirt texture
  85038. */
  85039. _this.lensFlareDirtTexture = null;
  85040. /**
  85041. * Represents the focal length for the depth of field effect
  85042. */
  85043. _this.depthOfFieldDistance = 10.0;
  85044. /**
  85045. * Represents the blur intensity for the blurred part of the depth of field effect
  85046. */
  85047. _this.depthOfFieldBlurWidth = 64.0;
  85048. /**
  85049. * For motion blur, defines how much the image is blurred by the movement
  85050. */
  85051. _this.motionStrength = 1.0;
  85052. /**
  85053. * List of animations for the pipeline (IAnimatable implementation)
  85054. */
  85055. _this.animations = [];
  85056. _this._currentDepthOfFieldSource = null;
  85057. _this._hdrCurrentLuminance = 1.0;
  85058. // Getters and setters
  85059. _this._bloomEnabled = false;
  85060. _this._depthOfFieldEnabled = false;
  85061. _this._vlsEnabled = false;
  85062. _this._lensFlareEnabled = false;
  85063. _this._hdrEnabled = false;
  85064. _this._motionBlurEnabled = false;
  85065. _this._fxaaEnabled = false;
  85066. _this._motionBlurSamples = 64.0;
  85067. _this._volumetricLightStepsCount = 50.0;
  85068. _this._samples = 1;
  85069. _this._cameras = cameras || [];
  85070. // Initialize
  85071. _this._scene = scene;
  85072. _this._basePostProcess = originalPostProcess;
  85073. _this._ratio = ratio;
  85074. // Misc
  85075. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85076. // Finish
  85077. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85078. _this._buildPipeline();
  85079. return _this;
  85080. }
  85081. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  85082. /**
  85083. * @ignore
  85084. * Specifies if the bloom pipeline is enabled
  85085. */
  85086. get: function () {
  85087. return this._bloomEnabled;
  85088. },
  85089. set: function (enabled) {
  85090. if (this._bloomEnabled === enabled) {
  85091. return;
  85092. }
  85093. this._bloomEnabled = enabled;
  85094. this._buildPipeline();
  85095. },
  85096. enumerable: true,
  85097. configurable: true
  85098. });
  85099. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  85100. /**
  85101. * @ignore
  85102. * Specifies if the depth of field pipeline is enabed
  85103. */
  85104. get: function () {
  85105. return this._depthOfFieldEnabled;
  85106. },
  85107. set: function (enabled) {
  85108. if (this._depthOfFieldEnabled === enabled) {
  85109. return;
  85110. }
  85111. this._depthOfFieldEnabled = enabled;
  85112. this._buildPipeline();
  85113. },
  85114. enumerable: true,
  85115. configurable: true
  85116. });
  85117. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  85118. /**
  85119. * @ignore
  85120. * Specifies if the lens flare pipeline is enabed
  85121. */
  85122. get: function () {
  85123. return this._lensFlareEnabled;
  85124. },
  85125. set: function (enabled) {
  85126. if (this._lensFlareEnabled === enabled) {
  85127. return;
  85128. }
  85129. this._lensFlareEnabled = enabled;
  85130. this._buildPipeline();
  85131. },
  85132. enumerable: true,
  85133. configurable: true
  85134. });
  85135. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  85136. /**
  85137. * @ignore
  85138. * Specifies if the HDR pipeline is enabled
  85139. */
  85140. get: function () {
  85141. return this._hdrEnabled;
  85142. },
  85143. set: function (enabled) {
  85144. if (this._hdrEnabled === enabled) {
  85145. return;
  85146. }
  85147. this._hdrEnabled = enabled;
  85148. this._buildPipeline();
  85149. },
  85150. enumerable: true,
  85151. configurable: true
  85152. });
  85153. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  85154. /**
  85155. * @ignore
  85156. * Specifies if the volumetric lights scattering effect is enabled
  85157. */
  85158. get: function () {
  85159. return this._vlsEnabled;
  85160. },
  85161. set: function (enabled) {
  85162. if (this._vlsEnabled === enabled) {
  85163. return;
  85164. }
  85165. if (enabled) {
  85166. var geometry = this._scene.enableGeometryBufferRenderer();
  85167. if (!geometry) {
  85168. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  85169. return;
  85170. }
  85171. }
  85172. this._vlsEnabled = enabled;
  85173. this._buildPipeline();
  85174. },
  85175. enumerable: true,
  85176. configurable: true
  85177. });
  85178. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  85179. /**
  85180. * @ignore
  85181. * Specifies if the motion blur effect is enabled
  85182. */
  85183. get: function () {
  85184. return this._motionBlurEnabled;
  85185. },
  85186. set: function (enabled) {
  85187. if (this._motionBlurEnabled === enabled) {
  85188. return;
  85189. }
  85190. this._motionBlurEnabled = enabled;
  85191. this._buildPipeline();
  85192. },
  85193. enumerable: true,
  85194. configurable: true
  85195. });
  85196. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  85197. /**
  85198. * Specifies if anti-aliasing is enabled
  85199. */
  85200. get: function () {
  85201. return this._fxaaEnabled;
  85202. },
  85203. set: function (enabled) {
  85204. if (this._fxaaEnabled === enabled) {
  85205. return;
  85206. }
  85207. this._fxaaEnabled = enabled;
  85208. this._buildPipeline();
  85209. },
  85210. enumerable: true,
  85211. configurable: true
  85212. });
  85213. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  85214. /**
  85215. * Specifies the number of steps used to calculate the volumetric lights
  85216. * Typically in interval [50, 200]
  85217. */
  85218. get: function () {
  85219. return this._volumetricLightStepsCount;
  85220. },
  85221. set: function (count) {
  85222. if (this.volumetricLightPostProcess) {
  85223. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  85224. }
  85225. this._volumetricLightStepsCount = count;
  85226. },
  85227. enumerable: true,
  85228. configurable: true
  85229. });
  85230. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  85231. /**
  85232. * Specifies the number of samples used for the motion blur effect
  85233. * Typically in interval [16, 64]
  85234. */
  85235. get: function () {
  85236. return this._motionBlurSamples;
  85237. },
  85238. set: function (samples) {
  85239. if (this.motionBlurPostProcess) {
  85240. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  85241. }
  85242. this._motionBlurSamples = samples;
  85243. },
  85244. enumerable: true,
  85245. configurable: true
  85246. });
  85247. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  85248. /**
  85249. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  85250. */
  85251. get: function () {
  85252. return this._samples;
  85253. },
  85254. set: function (sampleCount) {
  85255. if (this._samples === sampleCount) {
  85256. return;
  85257. }
  85258. this._samples = sampleCount;
  85259. this._buildPipeline();
  85260. },
  85261. enumerable: true,
  85262. configurable: true
  85263. });
  85264. StandardRenderingPipeline.prototype._buildPipeline = function () {
  85265. var _this = this;
  85266. var ratio = this._ratio;
  85267. var scene = this._scene;
  85268. this._disposePostProcesses();
  85269. this._reset();
  85270. // Create pass post-process
  85271. if (!this._basePostProcess) {
  85272. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  85273. this.originalPostProcess.onApply = function (effect) {
  85274. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  85275. };
  85276. }
  85277. else {
  85278. this.originalPostProcess = this._basePostProcess;
  85279. }
  85280. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  85281. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  85282. }
  85283. this._currentDepthOfFieldSource = this.originalPostProcess;
  85284. if (this._bloomEnabled) {
  85285. // Create down sample X4 post-process
  85286. this._createDownSampleX4PostProcess(scene, ratio / 2);
  85287. // Create bright pass post-process
  85288. this._createBrightPassPostProcess(scene, ratio / 2);
  85289. // Create gaussian blur post-processes (down sampling blurs)
  85290. this._createBlurPostProcesses(scene, ratio / 4, 1);
  85291. // Create texture adder post-process
  85292. this._createTextureAdderPostProcess(scene, ratio);
  85293. // Create depth-of-field source post-process
  85294. 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);
  85295. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  85296. }
  85297. if (this._vlsEnabled) {
  85298. // Create volumetric light
  85299. this._createVolumetricLightPostProcess(scene, ratio);
  85300. // Create volumetric light final post-process
  85301. 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);
  85302. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  85303. }
  85304. if (this._lensFlareEnabled) {
  85305. // Create lens flare post-process
  85306. this._createLensFlarePostProcess(scene, ratio);
  85307. // Create depth-of-field source post-process post lens-flare and disable it now
  85308. 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);
  85309. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  85310. }
  85311. if (this._hdrEnabled) {
  85312. // Create luminance
  85313. this._createLuminancePostProcesses(scene, this._floatTextureType);
  85314. // Create HDR
  85315. this._createHdrPostProcess(scene, ratio);
  85316. // Create depth-of-field source post-process post hdr and disable it now
  85317. 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);
  85318. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  85319. }
  85320. if (this._depthOfFieldEnabled) {
  85321. // Create gaussian blur used by depth-of-field
  85322. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  85323. // Create depth-of-field post-process
  85324. this._createDepthOfFieldPostProcess(scene, ratio);
  85325. }
  85326. if (this._motionBlurEnabled) {
  85327. // Create motion blur post-process
  85328. this._createMotionBlurPostProcess(scene, ratio);
  85329. }
  85330. if (this._fxaaEnabled) {
  85331. // Create fxaa post-process
  85332. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85333. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  85334. }
  85335. if (this._cameras !== null) {
  85336. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  85337. }
  85338. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  85339. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  85340. }
  85341. };
  85342. // Down Sample X4 Post-Processs
  85343. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  85344. var _this = this;
  85345. var downSampleX4Offsets = new Array(32);
  85346. 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);
  85347. this.downSampleX4PostProcess.onApply = function (effect) {
  85348. var id = 0;
  85349. var width = _this.downSampleX4PostProcess.width;
  85350. var height = _this.downSampleX4PostProcess.height;
  85351. for (var i = -2; i < 2; i++) {
  85352. for (var j = -2; j < 2; j++) {
  85353. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  85354. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  85355. id += 2;
  85356. }
  85357. }
  85358. effect.setArray2("dsOffsets", downSampleX4Offsets);
  85359. };
  85360. // Add to pipeline
  85361. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  85362. };
  85363. // Brightpass Post-Process
  85364. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  85365. var _this = this;
  85366. var brightOffsets = new Array(8);
  85367. 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);
  85368. this.brightPassPostProcess.onApply = function (effect) {
  85369. var sU = (1.0 / _this.brightPassPostProcess.width);
  85370. var sV = (1.0 / _this.brightPassPostProcess.height);
  85371. brightOffsets[0] = -0.5 * sU;
  85372. brightOffsets[1] = 0.5 * sV;
  85373. brightOffsets[2] = 0.5 * sU;
  85374. brightOffsets[3] = 0.5 * sV;
  85375. brightOffsets[4] = -0.5 * sU;
  85376. brightOffsets[5] = -0.5 * sV;
  85377. brightOffsets[6] = 0.5 * sU;
  85378. brightOffsets[7] = -0.5 * sV;
  85379. effect.setArray2("dsOffsets", brightOffsets);
  85380. effect.setFloat("brightThreshold", _this.brightThreshold);
  85381. };
  85382. // Add to pipeline
  85383. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  85384. };
  85385. // Create blur H&V post-processes
  85386. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  85387. var _this = this;
  85388. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  85389. var engine = scene.getEngine();
  85390. 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);
  85391. 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);
  85392. blurX.onActivateObservable.add(function () {
  85393. var dw = blurX.width / engine.getRenderWidth();
  85394. blurX.kernel = _this[blurWidthKey] * dw;
  85395. });
  85396. blurY.onActivateObservable.add(function () {
  85397. var dw = blurY.height / engine.getRenderHeight();
  85398. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  85399. });
  85400. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  85401. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  85402. this.blurHPostProcesses.push(blurX);
  85403. this.blurVPostProcesses.push(blurY);
  85404. };
  85405. // Create texture adder post-process
  85406. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  85407. var _this = this;
  85408. 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);
  85409. this.textureAdderPostProcess.onApply = function (effect) {
  85410. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  85411. effect.setTexture("lensSampler", _this.lensTexture);
  85412. effect.setFloat("exposure", _this.exposure);
  85413. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  85414. };
  85415. // Add to pipeline
  85416. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  85417. };
  85418. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  85419. var _this = this;
  85420. var geometryRenderer = scene.enableGeometryBufferRenderer();
  85421. geometryRenderer.enablePosition = true;
  85422. var geometry = geometryRenderer.getGBuffer();
  85423. // Base post-process
  85424. 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));
  85425. var depthValues = BABYLON.Vector2.Zero();
  85426. this.volumetricLightPostProcess.onApply = function (effect) {
  85427. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  85428. var generator = _this.sourceLight.getShadowGenerator();
  85429. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  85430. effect.setTexture("positionSampler", geometry.textures[2]);
  85431. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  85432. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  85433. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  85434. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  85435. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  85436. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  85437. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  85438. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  85439. effect.setVector2("depthValues", depthValues);
  85440. }
  85441. };
  85442. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  85443. // Smooth
  85444. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  85445. // Merge
  85446. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  85447. this.volumetricLightMergePostProces.onApply = function (effect) {
  85448. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  85449. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  85450. };
  85451. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  85452. };
  85453. // Create luminance
  85454. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  85455. var _this = this;
  85456. // Create luminance
  85457. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  85458. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  85459. var offsets = [];
  85460. this.luminancePostProcess.onApply = function (effect) {
  85461. var sU = (1.0 / _this.luminancePostProcess.width);
  85462. var sV = (1.0 / _this.luminancePostProcess.height);
  85463. offsets[0] = -0.5 * sU;
  85464. offsets[1] = 0.5 * sV;
  85465. offsets[2] = 0.5 * sU;
  85466. offsets[3] = 0.5 * sV;
  85467. offsets[4] = -0.5 * sU;
  85468. offsets[5] = -0.5 * sV;
  85469. offsets[6] = 0.5 * sU;
  85470. offsets[7] = -0.5 * sV;
  85471. effect.setArray2("lumOffsets", offsets);
  85472. };
  85473. // Add to pipeline
  85474. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  85475. // Create down sample luminance
  85476. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  85477. var size = Math.pow(3, i);
  85478. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  85479. if (i === 0) {
  85480. defines += "#define FINAL_DOWN_SAMPLER";
  85481. }
  85482. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  85483. this.luminanceDownSamplePostProcesses.push(postProcess);
  85484. }
  85485. // Create callbacks and add effects
  85486. var lastLuminance = this.luminancePostProcess;
  85487. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  85488. var downSampleOffsets = new Array(18);
  85489. pp.onApply = function (effect) {
  85490. if (!lastLuminance) {
  85491. return;
  85492. }
  85493. var id = 0;
  85494. for (var x = -1; x < 2; x++) {
  85495. for (var y = -1; y < 2; y++) {
  85496. downSampleOffsets[id] = x / lastLuminance.width;
  85497. downSampleOffsets[id + 1] = y / lastLuminance.height;
  85498. id += 2;
  85499. }
  85500. }
  85501. effect.setArray2("dsOffsets", downSampleOffsets);
  85502. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  85503. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  85504. lastLuminance = _this.luminancePostProcess;
  85505. }
  85506. else {
  85507. lastLuminance = pp;
  85508. }
  85509. };
  85510. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  85511. pp.onAfterRender = function (effect) {
  85512. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  85513. 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);
  85514. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  85515. };
  85516. }
  85517. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  85518. });
  85519. };
  85520. // Create HDR post-process
  85521. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  85522. var _this = this;
  85523. 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);
  85524. var outputLiminance = 1;
  85525. var time = 0;
  85526. var lastTime = 0;
  85527. this.hdrPostProcess.onApply = function (effect) {
  85528. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  85529. time += scene.getEngine().getDeltaTime();
  85530. if (outputLiminance < 0) {
  85531. outputLiminance = _this._hdrCurrentLuminance;
  85532. }
  85533. else {
  85534. var dt = (lastTime - time) / 1000.0;
  85535. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  85536. outputLiminance += _this.hdrDecreaseRate * dt;
  85537. }
  85538. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  85539. outputLiminance -= _this.hdrIncreaseRate * dt;
  85540. }
  85541. else {
  85542. outputLiminance = _this._hdrCurrentLuminance;
  85543. }
  85544. }
  85545. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  85546. effect.setFloat("averageLuminance", outputLiminance);
  85547. lastTime = time;
  85548. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  85549. };
  85550. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  85551. };
  85552. // Create lens flare post-process
  85553. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  85554. var _this = this;
  85555. 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);
  85556. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  85557. this._createBlurPostProcesses(scene, ratio / 4, 2);
  85558. 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);
  85559. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  85560. var resolution = new BABYLON.Vector2(0, 0);
  85561. // Lens flare
  85562. this.lensFlarePostProcess.onApply = function (effect) {
  85563. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  85564. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  85565. effect.setFloat("strength", _this.lensFlareStrength);
  85566. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  85567. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  85568. // Shift
  85569. resolution.x = _this.lensFlarePostProcess.width;
  85570. resolution.y = _this.lensFlarePostProcess.height;
  85571. effect.setVector2("resolution", resolution);
  85572. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  85573. };
  85574. // Compose
  85575. 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);
  85576. 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);
  85577. this.lensFlareComposePostProcess.onApply = function (effect) {
  85578. if (!_this._scene.activeCamera) {
  85579. return;
  85580. }
  85581. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  85582. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  85583. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  85584. // Lens start rotation matrix
  85585. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  85586. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  85587. 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));
  85588. camRot *= 4.0;
  85589. 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);
  85590. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  85591. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  85592. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  85593. };
  85594. };
  85595. // Create depth-of-field post-process
  85596. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  85597. var _this = this;
  85598. 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);
  85599. this.depthOfFieldPostProcess.onApply = function (effect) {
  85600. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  85601. effect.setTexture("depthSampler", _this._getDepthTexture());
  85602. effect.setFloat("distance", _this.depthOfFieldDistance);
  85603. };
  85604. // Add to pipeline
  85605. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  85606. };
  85607. // Create motion blur post-process
  85608. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  85609. var _this = this;
  85610. 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);
  85611. var motionScale = 0;
  85612. var prevViewProjection = BABYLON.Matrix.Identity();
  85613. var invViewProjection = BABYLON.Matrix.Identity();
  85614. var viewProjection = BABYLON.Matrix.Identity();
  85615. var screenSize = BABYLON.Vector2.Zero();
  85616. this.motionBlurPostProcess.onApply = function (effect) {
  85617. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  85618. viewProjection.invertToRef(invViewProjection);
  85619. effect.setMatrix("inverseViewProjection", invViewProjection);
  85620. effect.setMatrix("prevViewProjection", prevViewProjection);
  85621. prevViewProjection = viewProjection;
  85622. screenSize.x = _this.motionBlurPostProcess.width;
  85623. screenSize.y = _this.motionBlurPostProcess.height;
  85624. effect.setVector2("screenSize", screenSize);
  85625. motionScale = scene.getEngine().getFps() / 60.0;
  85626. effect.setFloat("motionScale", motionScale);
  85627. effect.setFloat("motionStrength", _this.motionStrength);
  85628. effect.setTexture("depthSampler", _this._getDepthTexture());
  85629. };
  85630. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  85631. };
  85632. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  85633. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  85634. var renderer = this._scene.enableGeometryBufferRenderer();
  85635. return renderer.getGBuffer().textures[0];
  85636. }
  85637. return this._scene.enableDepthRenderer().getDepthMap();
  85638. };
  85639. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  85640. for (var i = 0; i < this._cameras.length; i++) {
  85641. var camera = this._cameras[i];
  85642. if (this.originalPostProcess) {
  85643. this.originalPostProcess.dispose(camera);
  85644. }
  85645. if (this.downSampleX4PostProcess) {
  85646. this.downSampleX4PostProcess.dispose(camera);
  85647. }
  85648. if (this.brightPassPostProcess) {
  85649. this.brightPassPostProcess.dispose(camera);
  85650. }
  85651. if (this.textureAdderPostProcess) {
  85652. this.textureAdderPostProcess.dispose(camera);
  85653. }
  85654. if (this.textureAdderFinalPostProcess) {
  85655. this.textureAdderFinalPostProcess.dispose(camera);
  85656. }
  85657. if (this.volumetricLightPostProcess) {
  85658. this.volumetricLightPostProcess.dispose(camera);
  85659. }
  85660. if (this.volumetricLightSmoothXPostProcess) {
  85661. this.volumetricLightSmoothXPostProcess.dispose(camera);
  85662. }
  85663. if (this.volumetricLightSmoothYPostProcess) {
  85664. this.volumetricLightSmoothYPostProcess.dispose(camera);
  85665. }
  85666. if (this.volumetricLightMergePostProces) {
  85667. this.volumetricLightMergePostProces.dispose(camera);
  85668. }
  85669. if (this.volumetricLightFinalPostProcess) {
  85670. this.volumetricLightFinalPostProcess.dispose(camera);
  85671. }
  85672. if (this.lensFlarePostProcess) {
  85673. this.lensFlarePostProcess.dispose(camera);
  85674. }
  85675. if (this.lensFlareComposePostProcess) {
  85676. this.lensFlareComposePostProcess.dispose(camera);
  85677. }
  85678. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  85679. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  85680. }
  85681. if (this.luminancePostProcess) {
  85682. this.luminancePostProcess.dispose(camera);
  85683. }
  85684. if (this.hdrPostProcess) {
  85685. this.hdrPostProcess.dispose(camera);
  85686. }
  85687. if (this.hdrFinalPostProcess) {
  85688. this.hdrFinalPostProcess.dispose(camera);
  85689. }
  85690. if (this.depthOfFieldPostProcess) {
  85691. this.depthOfFieldPostProcess.dispose(camera);
  85692. }
  85693. if (this.motionBlurPostProcess) {
  85694. this.motionBlurPostProcess.dispose(camera);
  85695. }
  85696. if (this.fxaaPostProcess) {
  85697. this.fxaaPostProcess.dispose(camera);
  85698. }
  85699. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  85700. this.blurHPostProcesses[j].dispose(camera);
  85701. }
  85702. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  85703. this.blurVPostProcesses[j].dispose(camera);
  85704. }
  85705. }
  85706. this.originalPostProcess = null;
  85707. this.downSampleX4PostProcess = null;
  85708. this.brightPassPostProcess = null;
  85709. this.textureAdderPostProcess = null;
  85710. this.textureAdderFinalPostProcess = null;
  85711. this.volumetricLightPostProcess = null;
  85712. this.volumetricLightSmoothXPostProcess = null;
  85713. this.volumetricLightSmoothYPostProcess = null;
  85714. this.volumetricLightMergePostProces = null;
  85715. this.volumetricLightFinalPostProcess = null;
  85716. this.lensFlarePostProcess = null;
  85717. this.lensFlareComposePostProcess = null;
  85718. this.luminancePostProcess = null;
  85719. this.hdrPostProcess = null;
  85720. this.hdrFinalPostProcess = null;
  85721. this.depthOfFieldPostProcess = null;
  85722. this.motionBlurPostProcess = null;
  85723. this.fxaaPostProcess = null;
  85724. this.luminanceDownSamplePostProcesses = [];
  85725. this.blurHPostProcesses = [];
  85726. this.blurVPostProcesses = [];
  85727. };
  85728. /**
  85729. * Dispose of the pipeline and stop all post processes
  85730. */
  85731. StandardRenderingPipeline.prototype.dispose = function () {
  85732. this._disposePostProcesses();
  85733. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  85734. _super.prototype.dispose.call(this);
  85735. };
  85736. /**
  85737. * Serialize the rendering pipeline (Used when exporting)
  85738. * @returns the serialized object
  85739. */
  85740. StandardRenderingPipeline.prototype.serialize = function () {
  85741. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  85742. if (this.sourceLight) {
  85743. serializationObject.sourceLightId = this.sourceLight.id;
  85744. }
  85745. serializationObject.customType = "StandardRenderingPipeline";
  85746. return serializationObject;
  85747. };
  85748. /**
  85749. * Parse the serialized pipeline
  85750. * @param source Source pipeline.
  85751. * @param scene The scene to load the pipeline to.
  85752. * @param rootUrl The URL of the serialized pipeline.
  85753. * @returns An instantiated pipeline from the serialized object.
  85754. */
  85755. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  85756. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  85757. if (source.sourceLightId) {
  85758. p.sourceLight = scene.getLightByID(source.sourceLightId);
  85759. }
  85760. return p;
  85761. };
  85762. /**
  85763. * Luminance steps
  85764. */
  85765. StandardRenderingPipeline.LuminanceSteps = 6;
  85766. __decorate([
  85767. BABYLON.serialize()
  85768. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  85769. __decorate([
  85770. BABYLON.serialize()
  85771. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  85772. __decorate([
  85773. BABYLON.serialize()
  85774. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  85775. __decorate([
  85776. BABYLON.serialize()
  85777. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  85778. __decorate([
  85779. BABYLON.serializeAsTexture("lensTexture")
  85780. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  85781. __decorate([
  85782. BABYLON.serialize()
  85783. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  85784. __decorate([
  85785. BABYLON.serialize()
  85786. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  85787. __decorate([
  85788. BABYLON.serialize()
  85789. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  85790. __decorate([
  85791. BABYLON.serialize()
  85792. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  85793. __decorate([
  85794. BABYLON.serialize()
  85795. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  85796. __decorate([
  85797. BABYLON.serialize()
  85798. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  85799. __decorate([
  85800. BABYLON.serializeAsTexture("lensColorTexture")
  85801. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  85802. __decorate([
  85803. BABYLON.serialize()
  85804. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  85805. __decorate([
  85806. BABYLON.serialize()
  85807. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  85808. __decorate([
  85809. BABYLON.serialize()
  85810. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  85811. __decorate([
  85812. BABYLON.serialize()
  85813. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  85814. __decorate([
  85815. BABYLON.serializeAsTexture("lensStarTexture")
  85816. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  85817. __decorate([
  85818. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  85819. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  85820. __decorate([
  85821. BABYLON.serialize()
  85822. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  85823. __decorate([
  85824. BABYLON.serialize()
  85825. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  85826. __decorate([
  85827. BABYLON.serialize()
  85828. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  85829. __decorate([
  85830. BABYLON.serialize()
  85831. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  85832. __decorate([
  85833. BABYLON.serialize()
  85834. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  85835. __decorate([
  85836. BABYLON.serialize()
  85837. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  85838. __decorate([
  85839. BABYLON.serialize()
  85840. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  85841. __decorate([
  85842. BABYLON.serialize()
  85843. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  85844. __decorate([
  85845. BABYLON.serialize()
  85846. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  85847. __decorate([
  85848. BABYLON.serialize()
  85849. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  85850. __decorate([
  85851. BABYLON.serialize()
  85852. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  85853. __decorate([
  85854. BABYLON.serialize()
  85855. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  85856. __decorate([
  85857. BABYLON.serialize()
  85858. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  85859. __decorate([
  85860. BABYLON.serialize()
  85861. ], StandardRenderingPipeline.prototype, "samples", null);
  85862. return StandardRenderingPipeline;
  85863. }(BABYLON.PostProcessRenderPipeline));
  85864. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  85865. })(BABYLON || (BABYLON = {}));
  85866. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  85867. var BABYLON;
  85868. (function (BABYLON) {
  85869. /**
  85870. * Fxaa post process
  85871. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#fxaa
  85872. */
  85873. var FxaaPostProcess = /** @class */ (function (_super) {
  85874. __extends(FxaaPostProcess, _super);
  85875. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  85876. if (camera === void 0) { camera = null; }
  85877. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85878. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  85879. var defines = _this._getDefines();
  85880. _this.updateEffect(defines);
  85881. _this.onApplyObservable.add(function (effect) {
  85882. var texelSize = _this.texelSize;
  85883. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  85884. });
  85885. return _this;
  85886. }
  85887. FxaaPostProcess.prototype._getDefines = function () {
  85888. var engine = this.getEngine();
  85889. if (!engine) {
  85890. return null;
  85891. }
  85892. var glInfo = engine.getGlInfo();
  85893. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  85894. return "#define MALI 1\n";
  85895. }
  85896. return null;
  85897. };
  85898. return FxaaPostProcess;
  85899. }(BABYLON.PostProcess));
  85900. BABYLON.FxaaPostProcess = FxaaPostProcess;
  85901. })(BABYLON || (BABYLON = {}));
  85902. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  85903. var BABYLON;
  85904. (function (BABYLON) {
  85905. /**
  85906. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  85907. */
  85908. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  85909. __extends(ChromaticAberrationPostProcess, _super);
  85910. /**
  85911. * Creates a new instance ChromaticAberrationPostProcess
  85912. * @param name The name of the effect.
  85913. * @param screenWidth The width of the screen to apply the effect on.
  85914. * @param screenHeight The height of the screen to apply the effect on.
  85915. * @param options The required width/height ratio to downsize to before computing the render pass.
  85916. * @param camera The camera to apply the render pass to.
  85917. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85918. * @param engine The engine which the post process will be applied. (default: current engine)
  85919. * @param reusable If the post process can be reused on the same frame. (default: false)
  85920. * @param textureType Type of textures used when performing the post process. (default: 0)
  85921. * @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)
  85922. */
  85923. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85924. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85925. if (blockCompilation === void 0) { blockCompilation = false; }
  85926. 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;
  85927. /**
  85928. * The amount of seperation of rgb channels (default: 30)
  85929. */
  85930. _this.aberrationAmount = 30;
  85931. /**
  85932. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  85933. */
  85934. _this.radialIntensity = 0;
  85935. /**
  85936. * 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))
  85937. */
  85938. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  85939. /**
  85940. * 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))
  85941. */
  85942. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  85943. _this.onApplyObservable.add(function (effect) {
  85944. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  85945. effect.setFloat('screen_width', screenWidth);
  85946. effect.setFloat('screen_height', screenHeight);
  85947. effect.setFloat('radialIntensity', _this.radialIntensity);
  85948. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  85949. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  85950. });
  85951. return _this;
  85952. }
  85953. return ChromaticAberrationPostProcess;
  85954. }(BABYLON.PostProcess));
  85955. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  85956. })(BABYLON || (BABYLON = {}));
  85957. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  85958. var BABYLON;
  85959. (function (BABYLON) {
  85960. /**
  85961. * The GrainPostProcess adds noise to the image at mid luminance levels
  85962. */
  85963. var GrainPostProcess = /** @class */ (function (_super) {
  85964. __extends(GrainPostProcess, _super);
  85965. /**
  85966. * Creates a new instance of @see GrainPostProcess
  85967. * @param name The name of the effect.
  85968. * @param options The required width/height ratio to downsize to before computing the render pass.
  85969. * @param camera The camera to apply the render pass to.
  85970. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85971. * @param engine The engine which the post process will be applied. (default: current engine)
  85972. * @param reusable If the post process can be reused on the same frame. (default: false)
  85973. * @param textureType Type of textures used when performing the post process. (default: 0)
  85974. * @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)
  85975. */
  85976. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85977. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85978. if (blockCompilation === void 0) { blockCompilation = false; }
  85979. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  85980. /**
  85981. * The intensity of the grain added (default: 30)
  85982. */
  85983. _this.intensity = 30;
  85984. /**
  85985. * If the grain should be randomized on every frame
  85986. */
  85987. _this.animated = false;
  85988. _this.onApplyObservable.add(function (effect) {
  85989. effect.setFloat('intensity', _this.intensity);
  85990. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  85991. });
  85992. return _this;
  85993. }
  85994. return GrainPostProcess;
  85995. }(BABYLON.PostProcess));
  85996. BABYLON.GrainPostProcess = GrainPostProcess;
  85997. })(BABYLON || (BABYLON = {}));
  85998. //# sourceMappingURL=babylon.grainPostProcess.js.map
  85999. var BABYLON;
  86000. (function (BABYLON) {
  86001. /**
  86002. * The SharpenPostProcess applies a sharpen kernel to every pixel
  86003. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  86004. */
  86005. var SharpenPostProcess = /** @class */ (function (_super) {
  86006. __extends(SharpenPostProcess, _super);
  86007. /**
  86008. * Creates a new instance ConvolutionPostProcess
  86009. * @param name The name of the effect.
  86010. * @param options The required width/height ratio to downsize to before computing the render pass.
  86011. * @param camera The camera to apply the render pass to.
  86012. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86013. * @param engine The engine which the post process will be applied. (default: current engine)
  86014. * @param reusable If the post process can be reused on the same frame. (default: false)
  86015. * @param textureType Type of textures used when performing the post process. (default: 0)
  86016. * @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)
  86017. */
  86018. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86019. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86020. if (blockCompilation === void 0) { blockCompilation = false; }
  86021. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  86022. /**
  86023. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  86024. */
  86025. _this.colorAmount = 1.0;
  86026. /**
  86027. * How much sharpness should be applied (default: 0.3)
  86028. */
  86029. _this.edgeAmount = 0.3;
  86030. _this.onApply = function (effect) {
  86031. effect.setFloat2("screenSize", _this.width, _this.height);
  86032. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  86033. };
  86034. return _this;
  86035. }
  86036. return SharpenPostProcess;
  86037. }(BABYLON.PostProcess));
  86038. BABYLON.SharpenPostProcess = SharpenPostProcess;
  86039. })(BABYLON || (BABYLON = {}));
  86040. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  86041. var BABYLON;
  86042. (function (BABYLON) {
  86043. /**
  86044. * The Blur Post Process which blurs an image based on a kernel and direction.
  86045. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  86046. */
  86047. var BlurPostProcess = /** @class */ (function (_super) {
  86048. __extends(BlurPostProcess, _super);
  86049. /**
  86050. * Creates a new instance BlurPostProcess
  86051. * @param name The name of the effect.
  86052. * @param direction The direction in which to blur the image.
  86053. * @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.
  86054. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  86055. * @param camera The camera to apply the render pass to.
  86056. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86057. * @param engine The engine which the post process will be applied. (default: current engine)
  86058. * @param reusable If the post process can be reused on the same frame. (default: false)
  86059. * @param textureType Type of textures used when performing the post process. (default: 0)
  86060. * @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)
  86061. */
  86062. function BlurPostProcess(name,
  86063. /** The direction in which to blur the image. */
  86064. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  86065. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86066. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86067. if (defines === void 0) { defines = ""; }
  86068. if (blockCompilation === void 0) { blockCompilation = false; }
  86069. 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;
  86070. _this.direction = direction;
  86071. _this.blockCompilation = blockCompilation;
  86072. _this._packedFloat = false;
  86073. _this._staticDefines = "";
  86074. _this._staticDefines = defines;
  86075. _this.onApplyObservable.add(function (effect) {
  86076. if (_this._outputTexture) {
  86077. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  86078. }
  86079. else {
  86080. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  86081. }
  86082. });
  86083. _this.kernel = kernel;
  86084. return _this;
  86085. }
  86086. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  86087. /**
  86088. * Gets the length in pixels of the blur sample region
  86089. */
  86090. get: function () {
  86091. return this._idealKernel;
  86092. },
  86093. /**
  86094. * Sets the length in pixels of the blur sample region
  86095. */
  86096. set: function (v) {
  86097. if (this._idealKernel === v) {
  86098. return;
  86099. }
  86100. v = Math.max(v, 1);
  86101. this._idealKernel = v;
  86102. this._kernel = this._nearestBestKernel(v);
  86103. if (!this.blockCompilation) {
  86104. this._updateParameters();
  86105. }
  86106. },
  86107. enumerable: true,
  86108. configurable: true
  86109. });
  86110. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  86111. /**
  86112. * Gets wether or not the blur is unpacking/repacking floats
  86113. */
  86114. get: function () {
  86115. return this._packedFloat;
  86116. },
  86117. /**
  86118. * Sets wether or not the blur needs to unpack/repack floats
  86119. */
  86120. set: function (v) {
  86121. if (this._packedFloat === v) {
  86122. return;
  86123. }
  86124. this._packedFloat = v;
  86125. if (!this.blockCompilation) {
  86126. this._updateParameters();
  86127. }
  86128. },
  86129. enumerable: true,
  86130. configurable: true
  86131. });
  86132. /**
  86133. * Updates the effect with the current post process compile time values and recompiles the shader.
  86134. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  86135. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  86136. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  86137. * @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
  86138. * @param onCompiled Called when the shader has been compiled.
  86139. * @param onError Called if there is an error when compiling a shader.
  86140. */
  86141. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  86142. if (defines === void 0) { defines = null; }
  86143. if (uniforms === void 0) { uniforms = null; }
  86144. if (samplers === void 0) { samplers = null; }
  86145. this._updateParameters(onCompiled, onError);
  86146. };
  86147. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  86148. // Generate sampling offsets and weights
  86149. var N = this._kernel;
  86150. var centerIndex = (N - 1) / 2;
  86151. // Generate Gaussian sampling weights over kernel
  86152. var offsets = [];
  86153. var weights = [];
  86154. var totalWeight = 0;
  86155. for (var i = 0; i < N; i++) {
  86156. var u = i / (N - 1);
  86157. var w = this._gaussianWeight(u * 2.0 - 1);
  86158. offsets[i] = (i - centerIndex);
  86159. weights[i] = w;
  86160. totalWeight += w;
  86161. }
  86162. // Normalize weights
  86163. for (var i = 0; i < weights.length; i++) {
  86164. weights[i] /= totalWeight;
  86165. }
  86166. // Optimize: combine samples to take advantage of hardware linear sampling
  86167. // Walk from left to center, combining pairs (symmetrically)
  86168. var linearSamplingWeights = [];
  86169. var linearSamplingOffsets = [];
  86170. var linearSamplingMap = [];
  86171. for (var i = 0; i <= centerIndex; i += 2) {
  86172. var j = Math.min(i + 1, Math.floor(centerIndex));
  86173. var singleCenterSample = i === j;
  86174. if (singleCenterSample) {
  86175. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  86176. }
  86177. else {
  86178. var sharedCell = j === centerIndex;
  86179. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  86180. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  86181. if (offsetLinear === 0) {
  86182. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  86183. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  86184. }
  86185. else {
  86186. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  86187. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  86188. }
  86189. }
  86190. }
  86191. for (var i = 0; i < linearSamplingMap.length; i++) {
  86192. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  86193. linearSamplingWeights[i] = linearSamplingMap[i].w;
  86194. }
  86195. // Replace with optimized
  86196. offsets = linearSamplingOffsets;
  86197. weights = linearSamplingWeights;
  86198. // Generate shaders
  86199. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  86200. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  86201. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  86202. var defines = "";
  86203. defines += this._staticDefines;
  86204. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  86205. if (this._staticDefines.indexOf("DOF") != -1) {
  86206. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  86207. varyingCount--;
  86208. }
  86209. for (var i = 0; i < varyingCount; i++) {
  86210. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  86211. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  86212. }
  86213. var depCount = 0;
  86214. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  86215. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  86216. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  86217. depCount++;
  86218. }
  86219. if (this.packedFloat) {
  86220. defines += "#define PACKEDFLOAT 1";
  86221. }
  86222. this.blockCompilation = false;
  86223. _super.prototype.updateEffect.call(this, defines, null, null, {
  86224. varyingCount: varyingCount,
  86225. depCount: depCount
  86226. }, onCompiled, onError);
  86227. };
  86228. /**
  86229. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  86230. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  86231. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  86232. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  86233. * The gaps between physical kernels are compensated for in the weighting of the samples
  86234. * @param idealKernel Ideal blur kernel.
  86235. * @return Nearest best kernel.
  86236. */
  86237. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  86238. var v = Math.round(idealKernel);
  86239. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  86240. var k = _a[_i];
  86241. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  86242. return Math.max(k, 3);
  86243. }
  86244. }
  86245. return Math.max(v, 3);
  86246. };
  86247. /**
  86248. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  86249. * @param x The point on the Gaussian distribution to sample.
  86250. * @return the value of the Gaussian function at x.
  86251. */
  86252. BlurPostProcess.prototype._gaussianWeight = function (x) {
  86253. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  86254. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  86255. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  86256. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  86257. // truncated at around 1.3% of peak strength.
  86258. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  86259. var sigma = (1 / 3);
  86260. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  86261. var exponent = -((x * x) / (2.0 * sigma * sigma));
  86262. var weight = (1.0 / denominator) * Math.exp(exponent);
  86263. return weight;
  86264. };
  86265. /**
  86266. * Generates a string that can be used as a floating point number in GLSL.
  86267. * @param x Value to print.
  86268. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  86269. * @return GLSL float string.
  86270. */
  86271. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  86272. if (decimalFigures === void 0) { decimalFigures = 8; }
  86273. return x.toFixed(decimalFigures).replace(/0+$/, '');
  86274. };
  86275. return BlurPostProcess;
  86276. }(BABYLON.PostProcess));
  86277. BABYLON.BlurPostProcess = BlurPostProcess;
  86278. })(BABYLON || (BABYLON = {}));
  86279. //# sourceMappingURL=babylon.blurPostProcess.js.map
  86280. var BABYLON;
  86281. (function (BABYLON) {
  86282. /**
  86283. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  86284. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  86285. * based on samples that have a large difference in distance than the center pixel.
  86286. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  86287. */
  86288. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  86289. __extends(DepthOfFieldBlurPostProcess, _super);
  86290. /**
  86291. * Creates a new instance CircleOfConfusionPostProcess
  86292. * @param name The name of the effect.
  86293. * @param scene The scene the effect belongs to.
  86294. * @param direction The direction the blur should be applied.
  86295. * @param kernel The size of the kernel used to blur.
  86296. * @param options The required width/height ratio to downsize to before computing the render pass.
  86297. * @param camera The camera to apply the render pass to.
  86298. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  86299. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  86300. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86301. * @param engine The engine which the post process will be applied. (default: current engine)
  86302. * @param reusable If the post process can be reused on the same frame. (default: false)
  86303. * @param textureType Type of textures used when performing the post process. (default: 0)
  86304. * @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)
  86305. */
  86306. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  86307. if (imageToBlur === void 0) { imageToBlur = null; }
  86308. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86309. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86310. if (blockCompilation === void 0) { blockCompilation = false; }
  86311. 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;
  86312. _this.direction = direction;
  86313. _this.onApplyObservable.add(function (effect) {
  86314. if (imageToBlur != null) {
  86315. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  86316. }
  86317. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  86318. if (scene.activeCamera) {
  86319. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  86320. }
  86321. });
  86322. return _this;
  86323. }
  86324. return DepthOfFieldBlurPostProcess;
  86325. }(BABYLON.BlurPostProcess));
  86326. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  86327. })(BABYLON || (BABYLON = {}));
  86328. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  86329. var BABYLON;
  86330. (function (BABYLON) {
  86331. /**
  86332. * Options to be set when merging outputs from the default pipeline.
  86333. */
  86334. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  86335. function DepthOfFieldMergePostProcessOptions() {
  86336. }
  86337. return DepthOfFieldMergePostProcessOptions;
  86338. }());
  86339. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  86340. /**
  86341. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  86342. */
  86343. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  86344. __extends(DepthOfFieldMergePostProcess, _super);
  86345. /**
  86346. * Creates a new instance of DepthOfFieldMergePostProcess
  86347. * @param name The name of the effect.
  86348. * @param originalFromInput Post process which's input will be used for the merge.
  86349. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  86350. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  86351. * @param options The required width/height ratio to downsize to before computing the render pass.
  86352. * @param camera The camera to apply the render pass to.
  86353. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86354. * @param engine The engine which the post process will be applied. (default: current engine)
  86355. * @param reusable If the post process can be reused on the same frame. (default: false)
  86356. * @param textureType Type of textures used when performing the post process. (default: 0)
  86357. * @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)
  86358. */
  86359. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86360. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86361. if (blockCompilation === void 0) { blockCompilation = false; }
  86362. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  86363. _this.blurSteps = blurSteps;
  86364. _this.onApplyObservable.add(function (effect) {
  86365. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  86366. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  86367. blurSteps.forEach(function (step, index) {
  86368. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  86369. });
  86370. });
  86371. if (!blockCompilation) {
  86372. _this.updateEffect();
  86373. }
  86374. return _this;
  86375. }
  86376. /**
  86377. * Updates the effect with the current post process compile time values and recompiles the shader.
  86378. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  86379. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  86380. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  86381. * @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
  86382. * @param onCompiled Called when the shader has been compiled.
  86383. * @param onError Called if there is an error when compiling a shader.
  86384. */
  86385. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  86386. if (defines === void 0) { defines = null; }
  86387. if (uniforms === void 0) { uniforms = null; }
  86388. if (samplers === void 0) { samplers = null; }
  86389. if (!defines) {
  86390. defines = "";
  86391. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  86392. }
  86393. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  86394. };
  86395. return DepthOfFieldMergePostProcess;
  86396. }(BABYLON.PostProcess));
  86397. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  86398. })(BABYLON || (BABYLON = {}));
  86399. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  86400. var BABYLON;
  86401. (function (BABYLON) {
  86402. /**
  86403. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  86404. */
  86405. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  86406. __extends(CircleOfConfusionPostProcess, _super);
  86407. /**
  86408. * Creates a new instance CircleOfConfusionPostProcess
  86409. * @param name The name of the effect.
  86410. * @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.
  86411. * @param options The required width/height ratio to downsize to before computing the render pass.
  86412. * @param camera The camera to apply the render pass to.
  86413. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86414. * @param engine The engine which the post process will be applied. (default: current engine)
  86415. * @param reusable If the post process can be reused on the same frame. (default: false)
  86416. * @param textureType Type of textures used when performing the post process. (default: 0)
  86417. * @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)
  86418. */
  86419. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86420. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86421. if (blockCompilation === void 0) { blockCompilation = false; }
  86422. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  86423. /**
  86424. * 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.
  86425. */
  86426. _this.lensSize = 50;
  86427. /**
  86428. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  86429. */
  86430. _this.fStop = 1.4;
  86431. /**
  86432. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  86433. */
  86434. _this.focusDistance = 2000;
  86435. /**
  86436. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  86437. */
  86438. _this.focalLength = 50;
  86439. _this._depthTexture = null;
  86440. _this._depthTexture = depthTexture;
  86441. _this.onApplyObservable.add(function (effect) {
  86442. if (!_this._depthTexture) {
  86443. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  86444. return;
  86445. }
  86446. effect.setTexture("depthSampler", _this._depthTexture);
  86447. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  86448. var aperture = _this.lensSize / _this.fStop;
  86449. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  86450. effect.setFloat('focusDistance', _this.focusDistance);
  86451. effect.setFloat('cocPrecalculation', cocPrecalculation);
  86452. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  86453. });
  86454. return _this;
  86455. }
  86456. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  86457. /**
  86458. * 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.
  86459. */
  86460. set: function (value) {
  86461. this._depthTexture = value;
  86462. },
  86463. enumerable: true,
  86464. configurable: true
  86465. });
  86466. return CircleOfConfusionPostProcess;
  86467. }(BABYLON.PostProcess));
  86468. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  86469. })(BABYLON || (BABYLON = {}));
  86470. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  86471. var BABYLON;
  86472. (function (BABYLON) {
  86473. /**
  86474. * Specifies the level of max blur that should be applied when using the depth of field effect
  86475. */
  86476. var DepthOfFieldEffectBlurLevel;
  86477. (function (DepthOfFieldEffectBlurLevel) {
  86478. /**
  86479. * Subtle blur
  86480. */
  86481. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  86482. /**
  86483. * Medium blur
  86484. */
  86485. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  86486. /**
  86487. * Large blur
  86488. */
  86489. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  86490. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  86491. /**
  86492. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  86493. */
  86494. var DepthOfFieldEffect = /** @class */ (function (_super) {
  86495. __extends(DepthOfFieldEffect, _super);
  86496. /**
  86497. * Creates a new instance DepthOfFieldEffect
  86498. * @param scene The scene the effect belongs to.
  86499. * @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.
  86500. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  86501. * @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)
  86502. */
  86503. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  86504. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  86505. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  86506. if (blockCompilation === void 0) { blockCompilation = false; }
  86507. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  86508. return _this._effects;
  86509. }, true) || this;
  86510. /**
  86511. * @hidden Internal post processes in depth of field effect
  86512. */
  86513. _this._effects = [];
  86514. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  86515. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86516. // 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)
  86517. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  86518. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  86519. _this._depthOfFieldBlurY = [];
  86520. _this._depthOfFieldBlurX = [];
  86521. var blurCount = 1;
  86522. var kernelSize = 15;
  86523. switch (blurLevel) {
  86524. case DepthOfFieldEffectBlurLevel.High: {
  86525. blurCount = 3;
  86526. kernelSize = 51;
  86527. break;
  86528. }
  86529. case DepthOfFieldEffectBlurLevel.Medium: {
  86530. blurCount = 2;
  86531. kernelSize = 31;
  86532. break;
  86533. }
  86534. default: {
  86535. kernelSize = 15;
  86536. blurCount = 1;
  86537. break;
  86538. }
  86539. }
  86540. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  86541. var ratio = 1.0;
  86542. for (var i = 0; i < blurCount; i++) {
  86543. 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);
  86544. blurY.autoClear = false;
  86545. ratio = 0.75 / Math.pow(2, i);
  86546. 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);
  86547. blurX.autoClear = false;
  86548. _this._depthOfFieldBlurY.push(blurY);
  86549. _this._depthOfFieldBlurX.push(blurX);
  86550. }
  86551. // Set all post processes on the effect.
  86552. _this._effects = [_this._circleOfConfusion];
  86553. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  86554. _this._effects.push(_this._depthOfFieldBlurY[i]);
  86555. _this._effects.push(_this._depthOfFieldBlurX[i]);
  86556. }
  86557. // Merge blurred images with original image based on circleOfConfusion
  86558. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86559. _this._dofMerge.autoClear = false;
  86560. _this._effects.push(_this._dofMerge);
  86561. return _this;
  86562. }
  86563. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  86564. get: function () {
  86565. return this._circleOfConfusion.focalLength;
  86566. },
  86567. /**
  86568. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  86569. */
  86570. set: function (value) {
  86571. this._circleOfConfusion.focalLength = value;
  86572. },
  86573. enumerable: true,
  86574. configurable: true
  86575. });
  86576. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  86577. get: function () {
  86578. return this._circleOfConfusion.fStop;
  86579. },
  86580. /**
  86581. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  86582. */
  86583. set: function (value) {
  86584. this._circleOfConfusion.fStop = value;
  86585. },
  86586. enumerable: true,
  86587. configurable: true
  86588. });
  86589. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  86590. get: function () {
  86591. return this._circleOfConfusion.focusDistance;
  86592. },
  86593. /**
  86594. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  86595. */
  86596. set: function (value) {
  86597. this._circleOfConfusion.focusDistance = value;
  86598. },
  86599. enumerable: true,
  86600. configurable: true
  86601. });
  86602. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  86603. get: function () {
  86604. return this._circleOfConfusion.lensSize;
  86605. },
  86606. /**
  86607. * 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.
  86608. */
  86609. set: function (value) {
  86610. this._circleOfConfusion.lensSize = value;
  86611. },
  86612. enumerable: true,
  86613. configurable: true
  86614. });
  86615. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  86616. /**
  86617. * 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.
  86618. */
  86619. set: function (value) {
  86620. this._circleOfConfusion.depthTexture = value;
  86621. },
  86622. enumerable: true,
  86623. configurable: true
  86624. });
  86625. /**
  86626. * Disposes each of the internal effects for a given camera.
  86627. * @param camera The camera to dispose the effect on.
  86628. */
  86629. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  86630. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86631. this._effects[effectIndex].dispose(camera);
  86632. }
  86633. };
  86634. /**
  86635. * @hidden Internal
  86636. */
  86637. DepthOfFieldEffect.prototype._updateEffects = function () {
  86638. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86639. this._effects[effectIndex].updateEffect();
  86640. }
  86641. };
  86642. /**
  86643. * Internal
  86644. * @returns if all the contained post processes are ready.
  86645. * @hidden
  86646. */
  86647. DepthOfFieldEffect.prototype._isReady = function () {
  86648. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86649. if (!this._effects[effectIndex].isReady()) {
  86650. return false;
  86651. }
  86652. }
  86653. return true;
  86654. };
  86655. return DepthOfFieldEffect;
  86656. }(BABYLON.PostProcessRenderEffect));
  86657. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  86658. })(BABYLON || (BABYLON = {}));
  86659. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  86660. var BABYLON;
  86661. (function (BABYLON) {
  86662. /**
  86663. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  86664. */
  86665. var BloomMergePostProcess = /** @class */ (function (_super) {
  86666. __extends(BloomMergePostProcess, _super);
  86667. /**
  86668. * Creates a new instance of @see BloomMergePostProcess
  86669. * @param name The name of the effect.
  86670. * @param originalFromInput Post process which's input will be used for the merge.
  86671. * @param blurred Blurred highlights post process which's output will be used.
  86672. * @param weight Weight of the bloom to be added to the original input.
  86673. * @param options The required width/height ratio to downsize to before computing the render pass.
  86674. * @param camera The camera to apply the render pass to.
  86675. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86676. * @param engine The engine which the post process will be applied. (default: current engine)
  86677. * @param reusable If the post process can be reused on the same frame. (default: false)
  86678. * @param textureType Type of textures used when performing the post process. (default: 0)
  86679. * @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)
  86680. */
  86681. function BloomMergePostProcess(name, originalFromInput, blurred,
  86682. /** Weight of the bloom to be added to the original input. */
  86683. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86684. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86685. if (blockCompilation === void 0) { blockCompilation = false; }
  86686. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  86687. _this.weight = weight;
  86688. _this.onApplyObservable.add(function (effect) {
  86689. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  86690. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  86691. effect.setFloat("bloomWeight", _this.weight);
  86692. });
  86693. if (!blockCompilation) {
  86694. _this.updateEffect();
  86695. }
  86696. return _this;
  86697. }
  86698. return BloomMergePostProcess;
  86699. }(BABYLON.PostProcess));
  86700. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  86701. })(BABYLON || (BABYLON = {}));
  86702. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  86703. var BABYLON;
  86704. (function (BABYLON) {
  86705. /**
  86706. * 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.
  86707. */
  86708. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  86709. __extends(ExtractHighlightsPostProcess, _super);
  86710. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86711. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86712. if (blockCompilation === void 0) { blockCompilation = false; }
  86713. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  86714. /**
  86715. * The luminance threshold, pixels below this value will be set to black.
  86716. */
  86717. _this.threshold = 0.9;
  86718. /** @hidden */
  86719. _this._exposure = 1;
  86720. /**
  86721. * Post process which has the input texture to be used when performing highlight extraction
  86722. * @hidden
  86723. */
  86724. _this._inputPostProcess = null;
  86725. _this.onApplyObservable.add(function (effect) {
  86726. if (_this._inputPostProcess) {
  86727. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  86728. }
  86729. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  86730. effect.setFloat('exposure', _this._exposure);
  86731. });
  86732. return _this;
  86733. }
  86734. return ExtractHighlightsPostProcess;
  86735. }(BABYLON.PostProcess));
  86736. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  86737. })(BABYLON || (BABYLON = {}));
  86738. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  86739. var BABYLON;
  86740. (function (BABYLON) {
  86741. /**
  86742. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  86743. */
  86744. var BloomEffect = /** @class */ (function (_super) {
  86745. __extends(BloomEffect, _super);
  86746. /**
  86747. * Creates a new instance of @see BloomEffect
  86748. * @param scene The scene the effect belongs to.
  86749. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  86750. * @param bloomKernel The size of the kernel to be used when applying the blur.
  86751. * @param bloomWeight The the strength of bloom.
  86752. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  86753. * @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)
  86754. */
  86755. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  86756. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  86757. if (blockCompilation === void 0) { blockCompilation = false; }
  86758. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  86759. return _this._effects;
  86760. }, true) || this;
  86761. _this.bloomScale = bloomScale;
  86762. /**
  86763. * @hidden Internal
  86764. */
  86765. _this._effects = [];
  86766. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86767. _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);
  86768. _this._blurX.alwaysForcePOT = true;
  86769. _this._blurX.autoClear = false;
  86770. _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);
  86771. _this._blurY.alwaysForcePOT = true;
  86772. _this._blurY.autoClear = false;
  86773. _this.kernel = bloomKernel;
  86774. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  86775. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86776. _this._merge.autoClear = false;
  86777. _this._effects.push(_this._merge);
  86778. return _this;
  86779. }
  86780. Object.defineProperty(BloomEffect.prototype, "threshold", {
  86781. /**
  86782. * The luminance threshold to find bright areas of the image to bloom.
  86783. */
  86784. get: function () {
  86785. return this._downscale.threshold;
  86786. },
  86787. set: function (value) {
  86788. this._downscale.threshold = value;
  86789. },
  86790. enumerable: true,
  86791. configurable: true
  86792. });
  86793. Object.defineProperty(BloomEffect.prototype, "weight", {
  86794. /**
  86795. * The strength of the bloom.
  86796. */
  86797. get: function () {
  86798. return this._merge.weight;
  86799. },
  86800. set: function (value) {
  86801. this._merge.weight = value;
  86802. },
  86803. enumerable: true,
  86804. configurable: true
  86805. });
  86806. Object.defineProperty(BloomEffect.prototype, "kernel", {
  86807. /**
  86808. * Specifies the size of the bloom blur kernel, relative to the final output size
  86809. */
  86810. get: function () {
  86811. return this._blurX.kernel / this.bloomScale;
  86812. },
  86813. set: function (value) {
  86814. this._blurX.kernel = value * this.bloomScale;
  86815. this._blurY.kernel = value * this.bloomScale;
  86816. },
  86817. enumerable: true,
  86818. configurable: true
  86819. });
  86820. /**
  86821. * Disposes each of the internal effects for a given camera.
  86822. * @param camera The camera to dispose the effect on.
  86823. */
  86824. BloomEffect.prototype.disposeEffects = function (camera) {
  86825. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86826. this._effects[effectIndex].dispose(camera);
  86827. }
  86828. };
  86829. /**
  86830. * @hidden Internal
  86831. */
  86832. BloomEffect.prototype._updateEffects = function () {
  86833. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86834. this._effects[effectIndex].updateEffect();
  86835. }
  86836. };
  86837. /**
  86838. * Internal
  86839. * @returns if all the contained post processes are ready.
  86840. * @hidden
  86841. */
  86842. BloomEffect.prototype._isReady = function () {
  86843. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86844. if (!this._effects[effectIndex].isReady()) {
  86845. return false;
  86846. }
  86847. }
  86848. return true;
  86849. };
  86850. return BloomEffect;
  86851. }(BABYLON.PostProcessRenderEffect));
  86852. BABYLON.BloomEffect = BloomEffect;
  86853. })(BABYLON || (BABYLON = {}));
  86854. //# sourceMappingURL=babylon.bloomEffect.js.map
  86855. var BABYLON;
  86856. (function (BABYLON) {
  86857. /**
  86858. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  86859. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  86860. */
  86861. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  86862. __extends(DefaultRenderingPipeline, _super);
  86863. /**
  86864. * @constructor
  86865. * @param name - The rendering pipeline name (default: "")
  86866. * @param hdr - If high dynamic range textures should be used (default: true)
  86867. * @param scene - The scene linked to this pipeline (default: the last created scene)
  86868. * @param cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  86869. * @param automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  86870. */
  86871. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  86872. if (name === void 0) { name = ""; }
  86873. if (hdr === void 0) { hdr = true; }
  86874. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  86875. if (automaticBuild === void 0) { automaticBuild = true; }
  86876. var _this = _super.call(this, scene.getEngine(), name) || this;
  86877. _this._camerasToBeAttached = [];
  86878. /**
  86879. * ID of the sharpen post process,
  86880. */
  86881. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  86882. /**
  86883. * @ignore
  86884. * ID of the image processing post process;
  86885. */
  86886. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  86887. /**
  86888. * @ignore
  86889. * ID of the Fast Approximate Anti-Aliasing post process;
  86890. */
  86891. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  86892. /**
  86893. * ID of the chromatic aberration post process,
  86894. */
  86895. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  86896. /**
  86897. * ID of the grain post process
  86898. */
  86899. _this.GrainPostProcessId = "GrainPostProcessEffect";
  86900. /**
  86901. * Glow post process which adds a glow to emmisive areas of the image
  86902. */
  86903. _this._glowLayer = null;
  86904. /**
  86905. * Animations which can be used to tweak settings over a period of time
  86906. */
  86907. _this.animations = [];
  86908. _this._imageProcessingConfigurationObserver = null;
  86909. // Values
  86910. _this._sharpenEnabled = false;
  86911. _this._bloomEnabled = false;
  86912. _this._depthOfFieldEnabled = false;
  86913. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  86914. _this._fxaaEnabled = false;
  86915. _this._imageProcessingEnabled = true;
  86916. _this._bloomScale = 0.5;
  86917. _this._chromaticAberrationEnabled = false;
  86918. _this._grainEnabled = false;
  86919. _this._buildAllowed = true;
  86920. _this._resizeObserver = null;
  86921. _this._hardwareScaleLevel = 1.0;
  86922. _this._bloomKernel = 64;
  86923. /**
  86924. * Specifies the weight of the bloom in the final rendering
  86925. */
  86926. _this._bloomWeight = 0.15;
  86927. /**
  86928. * Specifies the luma threshold for the area that will be blurred by the bloom
  86929. */
  86930. _this._bloomThreshold = 0.9;
  86931. _this._samples = 1;
  86932. _this._hasCleared = false;
  86933. _this._prevPostProcess = null;
  86934. _this._prevPrevPostProcess = null;
  86935. _this._depthOfFieldSceneObserver = null;
  86936. _this._cameras = cameras || scene.cameras;
  86937. _this._cameras = _this._cameras.slice();
  86938. _this._camerasToBeAttached = _this._cameras.slice();
  86939. _this._buildAllowed = automaticBuild;
  86940. // Initialize
  86941. _this._scene = scene;
  86942. var caps = _this._scene.getEngine().getCaps();
  86943. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  86944. // Misc
  86945. if (_this._hdr) {
  86946. if (caps.textureHalfFloatRender) {
  86947. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86948. }
  86949. else if (caps.textureFloatRender) {
  86950. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86951. }
  86952. }
  86953. else {
  86954. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86955. }
  86956. // Attach
  86957. scene.postProcessRenderPipelineManager.addPipeline(_this);
  86958. var engine = _this._scene.getEngine();
  86959. // Create post processes before hand so they can be modified before enabled.
  86960. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  86961. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  86962. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  86963. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  86964. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  86965. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  86966. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  86967. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  86968. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  86969. _this._resizeObserver = engine.onResizeObservable.add(function () {
  86970. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  86971. _this.bloomKernel = _this.bloomKernel;
  86972. });
  86973. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  86974. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  86975. });
  86976. _this._buildPipeline();
  86977. return _this;
  86978. }
  86979. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  86980. get: function () {
  86981. return this._sharpenEnabled;
  86982. },
  86983. /**
  86984. * Enable or disable the sharpen process from the pipeline
  86985. */
  86986. set: function (enabled) {
  86987. if (this._sharpenEnabled === enabled) {
  86988. return;
  86989. }
  86990. this._sharpenEnabled = enabled;
  86991. this._buildPipeline();
  86992. },
  86993. enumerable: true,
  86994. configurable: true
  86995. });
  86996. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  86997. /**
  86998. * Specifies the size of the bloom blur kernel, relative to the final output size
  86999. */
  87000. get: function () {
  87001. return this._bloomKernel;
  87002. },
  87003. set: function (value) {
  87004. this._bloomKernel = value;
  87005. this.bloom.kernel = value / this._hardwareScaleLevel;
  87006. },
  87007. enumerable: true,
  87008. configurable: true
  87009. });
  87010. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  87011. get: function () {
  87012. return this._bloomWeight;
  87013. },
  87014. /**
  87015. * The strength of the bloom.
  87016. */
  87017. set: function (value) {
  87018. if (this._bloomWeight === value) {
  87019. return;
  87020. }
  87021. this.bloom.weight = value;
  87022. this._bloomWeight = value;
  87023. },
  87024. enumerable: true,
  87025. configurable: true
  87026. });
  87027. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  87028. get: function () {
  87029. return this._bloomThreshold;
  87030. },
  87031. /**
  87032. * The strength of the bloom.
  87033. */
  87034. set: function (value) {
  87035. if (this._bloomThreshold === value) {
  87036. return;
  87037. }
  87038. this.bloom.threshold = value;
  87039. this._bloomThreshold = value;
  87040. },
  87041. enumerable: true,
  87042. configurable: true
  87043. });
  87044. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  87045. get: function () {
  87046. return this._bloomScale;
  87047. },
  87048. /**
  87049. * The scale of the bloom, lower value will provide better performance.
  87050. */
  87051. set: function (value) {
  87052. if (this._bloomScale === value) {
  87053. return;
  87054. }
  87055. this._bloomScale = value;
  87056. // recreate bloom and dispose old as this setting is not dynamic
  87057. this._rebuildBloom();
  87058. this._buildPipeline();
  87059. },
  87060. enumerable: true,
  87061. configurable: true
  87062. });
  87063. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  87064. get: function () {
  87065. return this._bloomEnabled;
  87066. },
  87067. /**
  87068. * Enable or disable the bloom from the pipeline
  87069. */
  87070. set: function (enabled) {
  87071. if (this._bloomEnabled === enabled) {
  87072. return;
  87073. }
  87074. this._bloomEnabled = enabled;
  87075. this._buildPipeline();
  87076. },
  87077. enumerable: true,
  87078. configurable: true
  87079. });
  87080. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  87081. // recreate bloom and dispose old as this setting is not dynamic
  87082. var oldBloom = this.bloom;
  87083. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  87084. this.bloom.threshold = oldBloom.threshold;
  87085. for (var i = 0; i < this._cameras.length; i++) {
  87086. oldBloom.disposeEffects(this._cameras[i]);
  87087. }
  87088. };
  87089. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  87090. /**
  87091. * If the depth of field is enabled.
  87092. */
  87093. get: function () {
  87094. return this._depthOfFieldEnabled;
  87095. },
  87096. set: function (enabled) {
  87097. if (this._depthOfFieldEnabled === enabled) {
  87098. return;
  87099. }
  87100. this._depthOfFieldEnabled = enabled;
  87101. this._buildPipeline();
  87102. },
  87103. enumerable: true,
  87104. configurable: true
  87105. });
  87106. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  87107. /**
  87108. * Blur level of the depth of field effect. (Higher blur will effect performance)
  87109. */
  87110. get: function () {
  87111. return this._depthOfFieldBlurLevel;
  87112. },
  87113. set: function (value) {
  87114. if (this._depthOfFieldBlurLevel === value) {
  87115. return;
  87116. }
  87117. this._depthOfFieldBlurLevel = value;
  87118. // recreate dof and dispose old as this setting is not dynamic
  87119. var oldDof = this.depthOfField;
  87120. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  87121. this.depthOfField.focalLength = oldDof.focalLength;
  87122. this.depthOfField.focusDistance = oldDof.focusDistance;
  87123. this.depthOfField.fStop = oldDof.fStop;
  87124. this.depthOfField.lensSize = oldDof.lensSize;
  87125. for (var i = 0; i < this._cameras.length; i++) {
  87126. oldDof.disposeEffects(this._cameras[i]);
  87127. }
  87128. this._buildPipeline();
  87129. },
  87130. enumerable: true,
  87131. configurable: true
  87132. });
  87133. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  87134. get: function () {
  87135. return this._fxaaEnabled;
  87136. },
  87137. /**
  87138. * If the anti aliasing is enabled.
  87139. */
  87140. set: function (enabled) {
  87141. if (this._fxaaEnabled === enabled) {
  87142. return;
  87143. }
  87144. this._fxaaEnabled = enabled;
  87145. this._buildPipeline();
  87146. },
  87147. enumerable: true,
  87148. configurable: true
  87149. });
  87150. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  87151. get: function () {
  87152. return this._samples;
  87153. },
  87154. /**
  87155. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  87156. */
  87157. set: function (sampleCount) {
  87158. if (this._samples === sampleCount) {
  87159. return;
  87160. }
  87161. this._samples = sampleCount;
  87162. this._buildPipeline();
  87163. },
  87164. enumerable: true,
  87165. configurable: true
  87166. });
  87167. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  87168. get: function () {
  87169. return this._imageProcessingEnabled;
  87170. },
  87171. /**
  87172. * If image processing is enabled.
  87173. */
  87174. set: function (enabled) {
  87175. if (this._imageProcessingEnabled === enabled) {
  87176. return;
  87177. }
  87178. this._imageProcessingEnabled = enabled;
  87179. this._buildPipeline();
  87180. },
  87181. enumerable: true,
  87182. configurable: true
  87183. });
  87184. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  87185. get: function () {
  87186. return this._glowLayer == null;
  87187. },
  87188. /**
  87189. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  87190. */
  87191. set: function (enabled) {
  87192. if (enabled && !this._glowLayer) {
  87193. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  87194. }
  87195. else if (!enabled && this._glowLayer) {
  87196. this._glowLayer.dispose();
  87197. this._glowLayer = null;
  87198. }
  87199. },
  87200. enumerable: true,
  87201. configurable: true
  87202. });
  87203. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  87204. get: function () {
  87205. return this._chromaticAberrationEnabled;
  87206. },
  87207. /**
  87208. * Enable or disable the chromaticAberration process from the pipeline
  87209. */
  87210. set: function (enabled) {
  87211. if (this._chromaticAberrationEnabled === enabled) {
  87212. return;
  87213. }
  87214. this._chromaticAberrationEnabled = enabled;
  87215. this._buildPipeline();
  87216. },
  87217. enumerable: true,
  87218. configurable: true
  87219. });
  87220. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  87221. get: function () {
  87222. return this._grainEnabled;
  87223. },
  87224. /**
  87225. * Enable or disable the grain process from the pipeline
  87226. */
  87227. set: function (enabled) {
  87228. if (this._grainEnabled === enabled) {
  87229. return;
  87230. }
  87231. this._grainEnabled = enabled;
  87232. this._buildPipeline();
  87233. },
  87234. enumerable: true,
  87235. configurable: true
  87236. });
  87237. /**
  87238. * Force the compilation of the entire pipeline.
  87239. */
  87240. DefaultRenderingPipeline.prototype.prepare = function () {
  87241. var previousState = this._buildAllowed;
  87242. this._buildAllowed = true;
  87243. this._buildPipeline();
  87244. this._buildAllowed = previousState;
  87245. };
  87246. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  87247. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  87248. if (this._hasCleared) {
  87249. postProcess.autoClear = false;
  87250. }
  87251. else {
  87252. postProcess.autoClear = true;
  87253. this._scene.autoClear = false;
  87254. this._hasCleared = true;
  87255. }
  87256. if (!skipTextureSharing) {
  87257. if (this._prevPrevPostProcess) {
  87258. postProcess.shareOutputWith(this._prevPrevPostProcess);
  87259. }
  87260. else {
  87261. postProcess.useOwnOutput();
  87262. }
  87263. if (this._prevPostProcess) {
  87264. this._prevPrevPostProcess = this._prevPostProcess;
  87265. }
  87266. this._prevPostProcess = postProcess;
  87267. }
  87268. };
  87269. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  87270. var _this = this;
  87271. if (!this._buildAllowed) {
  87272. return;
  87273. }
  87274. this._scene.autoClear = true;
  87275. var engine = this._scene.getEngine();
  87276. this._disposePostProcesses();
  87277. if (this._cameras !== null) {
  87278. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  87279. // get back cameras to be used to reattach pipeline
  87280. this._cameras = this._camerasToBeAttached.slice();
  87281. }
  87282. this._reset();
  87283. this._prevPostProcess = null;
  87284. this._prevPrevPostProcess = null;
  87285. this._hasCleared = false;
  87286. if (this.depthOfFieldEnabled) {
  87287. // Multi camera suport
  87288. if (this._cameras.length > 1) {
  87289. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  87290. var camera = _a[_i];
  87291. var depthRenderer = this._scene.enableDepthRenderer(camera);
  87292. depthRenderer.useOnlyInActiveCamera = true;
  87293. }
  87294. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  87295. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  87296. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  87297. }
  87298. });
  87299. }
  87300. else {
  87301. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  87302. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  87303. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  87304. }
  87305. if (!this.depthOfField._isReady()) {
  87306. this.depthOfField._updateEffects();
  87307. }
  87308. this.addEffect(this.depthOfField);
  87309. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  87310. }
  87311. else {
  87312. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  87313. }
  87314. if (this.bloomEnabled) {
  87315. if (!this.bloom._isReady()) {
  87316. this.bloom._updateEffects();
  87317. }
  87318. this.addEffect(this.bloom);
  87319. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  87320. }
  87321. if (this._imageProcessingEnabled) {
  87322. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  87323. if (this._hdr) {
  87324. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  87325. this._setAutoClearAndTextureSharing(this.imageProcessing);
  87326. }
  87327. else {
  87328. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  87329. }
  87330. }
  87331. if (this.sharpenEnabled) {
  87332. if (!this.sharpen.isReady()) {
  87333. this.sharpen.updateEffect();
  87334. }
  87335. this.addEffect(this._sharpenEffect);
  87336. this._setAutoClearAndTextureSharing(this.sharpen);
  87337. }
  87338. if (this.grainEnabled) {
  87339. if (!this.grain.isReady()) {
  87340. this.grain.updateEffect();
  87341. }
  87342. this.addEffect(this._grainEffect);
  87343. this._setAutoClearAndTextureSharing(this.grain);
  87344. }
  87345. if (this.chromaticAberrationEnabled) {
  87346. if (!this.chromaticAberration.isReady()) {
  87347. this.chromaticAberration.updateEffect();
  87348. }
  87349. this.addEffect(this._chromaticAberrationEffect);
  87350. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  87351. }
  87352. if (this.fxaaEnabled) {
  87353. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  87354. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  87355. this._setAutoClearAndTextureSharing(this.fxaa, true);
  87356. }
  87357. if (this._cameras !== null) {
  87358. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  87359. }
  87360. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  87361. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  87362. }
  87363. };
  87364. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  87365. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  87366. for (var i = 0; i < this._cameras.length; i++) {
  87367. var camera = this._cameras[i];
  87368. if (this.imageProcessing) {
  87369. this.imageProcessing.dispose(camera);
  87370. }
  87371. if (this.fxaa) {
  87372. this.fxaa.dispose(camera);
  87373. }
  87374. // These are created in the constructor and should not be disposed on every pipeline change
  87375. if (disposeNonRecreated) {
  87376. if (this.sharpen) {
  87377. this.sharpen.dispose(camera);
  87378. }
  87379. if (this.depthOfField) {
  87380. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  87381. this.depthOfField.disposeEffects(camera);
  87382. }
  87383. if (this.bloom) {
  87384. this.bloom.disposeEffects(camera);
  87385. }
  87386. if (this.chromaticAberration) {
  87387. this.chromaticAberration.dispose(camera);
  87388. }
  87389. if (this.grain) {
  87390. this.grain.dispose(camera);
  87391. }
  87392. if (this._glowLayer) {
  87393. this._glowLayer.dispose();
  87394. }
  87395. }
  87396. }
  87397. this.imageProcessing = null;
  87398. this.fxaa = null;
  87399. if (disposeNonRecreated) {
  87400. this.sharpen = null;
  87401. this._sharpenEffect = null;
  87402. this.depthOfField = null;
  87403. this.bloom = null;
  87404. this.chromaticAberration = null;
  87405. this._chromaticAberrationEffect = null;
  87406. this.grain = null;
  87407. this._grainEffect = null;
  87408. this._glowLayer = null;
  87409. }
  87410. };
  87411. /**
  87412. * Adds a camera to the pipeline
  87413. * @param camera the camera to be added
  87414. */
  87415. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  87416. this._camerasToBeAttached.push(camera);
  87417. this._buildPipeline();
  87418. };
  87419. /**
  87420. * Removes a camera from the pipeline
  87421. * @param camera the camera to remove
  87422. */
  87423. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  87424. var index = this._camerasToBeAttached.indexOf(camera);
  87425. this._camerasToBeAttached.splice(index, 1);
  87426. this._buildPipeline();
  87427. };
  87428. /**
  87429. * Dispose of the pipeline and stop all post processes
  87430. */
  87431. DefaultRenderingPipeline.prototype.dispose = function () {
  87432. this._disposePostProcesses(true);
  87433. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  87434. this._scene.autoClear = true;
  87435. if (this._resizeObserver) {
  87436. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  87437. this._resizeObserver = null;
  87438. }
  87439. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  87440. _super.prototype.dispose.call(this);
  87441. };
  87442. /**
  87443. * Serialize the rendering pipeline (Used when exporting)
  87444. * @returns the serialized object
  87445. */
  87446. DefaultRenderingPipeline.prototype.serialize = function () {
  87447. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  87448. serializationObject.customType = "DefaultRenderingPipeline";
  87449. return serializationObject;
  87450. };
  87451. /**
  87452. * Parse the serialized pipeline
  87453. * @param source Source pipeline.
  87454. * @param scene The scene to load the pipeline to.
  87455. * @param rootUrl The URL of the serialized pipeline.
  87456. * @returns An instantiated pipeline from the serialized object.
  87457. */
  87458. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  87459. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  87460. };
  87461. __decorate([
  87462. BABYLON.serialize()
  87463. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  87464. __decorate([
  87465. BABYLON.serialize()
  87466. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  87467. __decorate([
  87468. BABYLON.serialize()
  87469. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  87470. __decorate([
  87471. BABYLON.serialize()
  87472. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  87473. __decorate([
  87474. BABYLON.serialize()
  87475. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  87476. __decorate([
  87477. BABYLON.serialize()
  87478. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  87479. __decorate([
  87480. BABYLON.serialize()
  87481. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  87482. __decorate([
  87483. BABYLON.serialize()
  87484. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  87485. __decorate([
  87486. BABYLON.serialize()
  87487. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  87488. __decorate([
  87489. BABYLON.serialize()
  87490. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  87491. __decorate([
  87492. BABYLON.serialize()
  87493. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  87494. __decorate([
  87495. BABYLON.serialize()
  87496. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  87497. __decorate([
  87498. BABYLON.serialize()
  87499. ], DefaultRenderingPipeline.prototype, "samples", null);
  87500. __decorate([
  87501. BABYLON.serialize()
  87502. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  87503. __decorate([
  87504. BABYLON.serialize()
  87505. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  87506. __decorate([
  87507. BABYLON.serialize()
  87508. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  87509. __decorate([
  87510. BABYLON.serialize()
  87511. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  87512. return DefaultRenderingPipeline;
  87513. }(BABYLON.PostProcessRenderPipeline));
  87514. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  87515. })(BABYLON || (BABYLON = {}));
  87516. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  87517. var BABYLON;
  87518. (function (BABYLON) {
  87519. /**
  87520. * @hidden
  87521. */
  87522. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  87523. __extends(ImageProcessingConfigurationDefines, _super);
  87524. function ImageProcessingConfigurationDefines() {
  87525. var _this = _super.call(this) || this;
  87526. _this.IMAGEPROCESSING = false;
  87527. _this.VIGNETTE = false;
  87528. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  87529. _this.VIGNETTEBLENDMODEOPAQUE = false;
  87530. _this.TONEMAPPING = false;
  87531. _this.TONEMAPPING_ACES = false;
  87532. _this.CONTRAST = false;
  87533. _this.COLORCURVES = false;
  87534. _this.COLORGRADING = false;
  87535. _this.COLORGRADING3D = false;
  87536. _this.SAMPLER3DGREENDEPTH = false;
  87537. _this.SAMPLER3DBGRMAP = false;
  87538. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  87539. _this.EXPOSURE = false;
  87540. _this.rebuild();
  87541. return _this;
  87542. }
  87543. return ImageProcessingConfigurationDefines;
  87544. }(BABYLON.MaterialDefines));
  87545. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  87546. /**
  87547. * This groups together the common properties used for image processing either in direct forward pass
  87548. * or through post processing effect depending on the use of the image processing pipeline in your scene
  87549. * or not.
  87550. */
  87551. var ImageProcessingConfiguration = /** @class */ (function () {
  87552. function ImageProcessingConfiguration() {
  87553. /**
  87554. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  87555. */
  87556. this.colorCurves = new BABYLON.ColorCurves();
  87557. this._colorCurvesEnabled = false;
  87558. this._colorGradingEnabled = false;
  87559. this._colorGradingWithGreenDepth = true;
  87560. this._colorGradingBGR = true;
  87561. /** @hidden */
  87562. this._exposure = 1.0;
  87563. this._toneMappingEnabled = false;
  87564. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  87565. this._contrast = 1.0;
  87566. /**
  87567. * Vignette stretch size.
  87568. */
  87569. this.vignetteStretch = 0;
  87570. /**
  87571. * Vignette centre X Offset.
  87572. */
  87573. this.vignetteCentreX = 0;
  87574. /**
  87575. * Vignette centre Y Offset.
  87576. */
  87577. this.vignetteCentreY = 0;
  87578. /**
  87579. * Vignette weight or intensity of the vignette effect.
  87580. */
  87581. this.vignetteWeight = 1.5;
  87582. /**
  87583. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  87584. * if vignetteEnabled is set to true.
  87585. */
  87586. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  87587. /**
  87588. * Camera field of view used by the Vignette effect.
  87589. */
  87590. this.vignetteCameraFov = 0.5;
  87591. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  87592. this._vignetteEnabled = false;
  87593. this._applyByPostProcess = false;
  87594. this._isEnabled = true;
  87595. /**
  87596. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  87597. */
  87598. this.onUpdateParameters = new BABYLON.Observable();
  87599. }
  87600. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  87601. /**
  87602. * Gets wether the color curves effect is enabled.
  87603. */
  87604. get: function () {
  87605. return this._colorCurvesEnabled;
  87606. },
  87607. /**
  87608. * Sets wether the color curves effect is enabled.
  87609. */
  87610. set: function (value) {
  87611. if (this._colorCurvesEnabled === value) {
  87612. return;
  87613. }
  87614. this._colorCurvesEnabled = value;
  87615. this._updateParameters();
  87616. },
  87617. enumerable: true,
  87618. configurable: true
  87619. });
  87620. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingTexture", {
  87621. /**
  87622. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  87623. */
  87624. get: function () {
  87625. return this._colorGradingTexture;
  87626. },
  87627. /**
  87628. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  87629. */
  87630. set: function (value) {
  87631. if (this._colorGradingTexture === value) {
  87632. return;
  87633. }
  87634. this._colorGradingTexture = value;
  87635. this._updateParameters();
  87636. },
  87637. enumerable: true,
  87638. configurable: true
  87639. });
  87640. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  87641. /**
  87642. * Gets wether the color grading effect is enabled.
  87643. */
  87644. get: function () {
  87645. return this._colorGradingEnabled;
  87646. },
  87647. /**
  87648. * Sets wether the color grading effect is enabled.
  87649. */
  87650. set: function (value) {
  87651. if (this._colorGradingEnabled === value) {
  87652. return;
  87653. }
  87654. this._colorGradingEnabled = value;
  87655. this._updateParameters();
  87656. },
  87657. enumerable: true,
  87658. configurable: true
  87659. });
  87660. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  87661. /**
  87662. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  87663. */
  87664. get: function () {
  87665. return this._colorGradingWithGreenDepth;
  87666. },
  87667. /**
  87668. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  87669. */
  87670. set: function (value) {
  87671. if (this._colorGradingWithGreenDepth === value) {
  87672. return;
  87673. }
  87674. this._colorGradingWithGreenDepth = value;
  87675. this._updateParameters();
  87676. },
  87677. enumerable: true,
  87678. configurable: true
  87679. });
  87680. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  87681. /**
  87682. * Gets wether the color grading texture contains BGR values.
  87683. */
  87684. get: function () {
  87685. return this._colorGradingBGR;
  87686. },
  87687. /**
  87688. * Sets wether the color grading texture contains BGR values.
  87689. */
  87690. set: function (value) {
  87691. if (this._colorGradingBGR === value) {
  87692. return;
  87693. }
  87694. this._colorGradingBGR = value;
  87695. this._updateParameters();
  87696. },
  87697. enumerable: true,
  87698. configurable: true
  87699. });
  87700. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  87701. /**
  87702. * Gets the Exposure used in the effect.
  87703. */
  87704. get: function () {
  87705. return this._exposure;
  87706. },
  87707. /**
  87708. * Sets the Exposure used in the effect.
  87709. */
  87710. set: function (value) {
  87711. if (this._exposure === value) {
  87712. return;
  87713. }
  87714. this._exposure = value;
  87715. this._updateParameters();
  87716. },
  87717. enumerable: true,
  87718. configurable: true
  87719. });
  87720. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  87721. /**
  87722. * Gets wether the tone mapping effect is enabled.
  87723. */
  87724. get: function () {
  87725. return this._toneMappingEnabled;
  87726. },
  87727. /**
  87728. * Sets wether the tone mapping effect is enabled.
  87729. */
  87730. set: function (value) {
  87731. if (this._toneMappingEnabled === value) {
  87732. return;
  87733. }
  87734. this._toneMappingEnabled = value;
  87735. this._updateParameters();
  87736. },
  87737. enumerable: true,
  87738. configurable: true
  87739. });
  87740. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  87741. /**
  87742. * Gets the type of tone mapping effect.
  87743. */
  87744. get: function () {
  87745. return this._toneMappingType;
  87746. },
  87747. /**
  87748. * Sets the type of tone mapping effect used in BabylonJS.
  87749. */
  87750. set: function (value) {
  87751. if (this._toneMappingType === value) {
  87752. return;
  87753. }
  87754. this._toneMappingType = value;
  87755. this._updateParameters();
  87756. },
  87757. enumerable: true,
  87758. configurable: true
  87759. });
  87760. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  87761. /**
  87762. * Gets the contrast used in the effect.
  87763. */
  87764. get: function () {
  87765. return this._contrast;
  87766. },
  87767. /**
  87768. * Sets the contrast used in the effect.
  87769. */
  87770. set: function (value) {
  87771. if (this._contrast === value) {
  87772. return;
  87773. }
  87774. this._contrast = value;
  87775. this._updateParameters();
  87776. },
  87777. enumerable: true,
  87778. configurable: true
  87779. });
  87780. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  87781. /**
  87782. * Gets the vignette blend mode allowing different kind of effect.
  87783. */
  87784. get: function () {
  87785. return this._vignetteBlendMode;
  87786. },
  87787. /**
  87788. * Sets the vignette blend mode allowing different kind of effect.
  87789. */
  87790. set: function (value) {
  87791. if (this._vignetteBlendMode === value) {
  87792. return;
  87793. }
  87794. this._vignetteBlendMode = value;
  87795. this._updateParameters();
  87796. },
  87797. enumerable: true,
  87798. configurable: true
  87799. });
  87800. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  87801. /**
  87802. * Gets wether the vignette effect is enabled.
  87803. */
  87804. get: function () {
  87805. return this._vignetteEnabled;
  87806. },
  87807. /**
  87808. * Sets wether the vignette effect is enabled.
  87809. */
  87810. set: function (value) {
  87811. if (this._vignetteEnabled === value) {
  87812. return;
  87813. }
  87814. this._vignetteEnabled = value;
  87815. this._updateParameters();
  87816. },
  87817. enumerable: true,
  87818. configurable: true
  87819. });
  87820. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  87821. /**
  87822. * Gets wether the image processing is applied through a post process or not.
  87823. */
  87824. get: function () {
  87825. return this._applyByPostProcess;
  87826. },
  87827. /**
  87828. * Sets wether the image processing is applied through a post process or not.
  87829. */
  87830. set: function (value) {
  87831. if (this._applyByPostProcess === value) {
  87832. return;
  87833. }
  87834. this._applyByPostProcess = value;
  87835. this._updateParameters();
  87836. },
  87837. enumerable: true,
  87838. configurable: true
  87839. });
  87840. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  87841. /**
  87842. * Gets wether the image processing is enabled or not.
  87843. */
  87844. get: function () {
  87845. return this._isEnabled;
  87846. },
  87847. /**
  87848. * Sets wether the image processing is enabled or not.
  87849. */
  87850. set: function (value) {
  87851. if (this._isEnabled === value) {
  87852. return;
  87853. }
  87854. this._isEnabled = value;
  87855. this._updateParameters();
  87856. },
  87857. enumerable: true,
  87858. configurable: true
  87859. });
  87860. /**
  87861. * Method called each time the image processing information changes requires to recompile the effect.
  87862. */
  87863. ImageProcessingConfiguration.prototype._updateParameters = function () {
  87864. this.onUpdateParameters.notifyObservers(this);
  87865. };
  87866. /**
  87867. * Gets the current class name.
  87868. * @return "ImageProcessingConfiguration"
  87869. */
  87870. ImageProcessingConfiguration.prototype.getClassName = function () {
  87871. return "ImageProcessingConfiguration";
  87872. };
  87873. /**
  87874. * Prepare the list of uniforms associated with the Image Processing effects.
  87875. * @param uniforms The list of uniforms used in the effect
  87876. * @param defines the list of defines currently in use
  87877. */
  87878. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  87879. if (defines.EXPOSURE) {
  87880. uniforms.push("exposureLinear");
  87881. }
  87882. if (defines.CONTRAST) {
  87883. uniforms.push("contrast");
  87884. }
  87885. if (defines.COLORGRADING) {
  87886. uniforms.push("colorTransformSettings");
  87887. }
  87888. if (defines.VIGNETTE) {
  87889. uniforms.push("vInverseScreenSize");
  87890. uniforms.push("vignetteSettings1");
  87891. uniforms.push("vignetteSettings2");
  87892. }
  87893. if (defines.COLORCURVES) {
  87894. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  87895. }
  87896. };
  87897. /**
  87898. * Prepare the list of samplers associated with the Image Processing effects.
  87899. * @param samplersList The list of uniforms used in the effect
  87900. * @param defines the list of defines currently in use
  87901. */
  87902. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  87903. if (defines.COLORGRADING) {
  87904. samplersList.push("txColorTransform");
  87905. }
  87906. };
  87907. /**
  87908. * Prepare the list of defines associated to the shader.
  87909. * @param defines the list of defines to complete
  87910. * @param forPostProcess Define if we are currently in post process mode or not
  87911. */
  87912. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  87913. if (forPostProcess === void 0) { forPostProcess = false; }
  87914. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  87915. defines.VIGNETTE = false;
  87916. defines.TONEMAPPING = false;
  87917. defines.TONEMAPPING_ACES = false;
  87918. defines.CONTRAST = false;
  87919. defines.EXPOSURE = false;
  87920. defines.COLORCURVES = false;
  87921. defines.COLORGRADING = false;
  87922. defines.COLORGRADING3D = false;
  87923. defines.IMAGEPROCESSING = false;
  87924. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  87925. return;
  87926. }
  87927. defines.VIGNETTE = this.vignetteEnabled;
  87928. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  87929. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  87930. defines.TONEMAPPING = this.toneMappingEnabled;
  87931. switch (this._toneMappingType) {
  87932. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  87933. defines.TONEMAPPING_ACES = true;
  87934. break;
  87935. }
  87936. defines.CONTRAST = (this.contrast !== 1.0);
  87937. defines.EXPOSURE = (this.exposure !== 1.0);
  87938. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  87939. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  87940. if (defines.COLORGRADING) {
  87941. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  87942. }
  87943. else {
  87944. defines.COLORGRADING3D = false;
  87945. }
  87946. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  87947. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  87948. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  87949. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  87950. };
  87951. /**
  87952. * Returns true if all the image processing information are ready.
  87953. * @returns True if ready, otherwise, false
  87954. */
  87955. ImageProcessingConfiguration.prototype.isReady = function () {
  87956. // Color Grading texure can not be none blocking.
  87957. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  87958. };
  87959. /**
  87960. * Binds the image processing to the shader.
  87961. * @param effect The effect to bind to
  87962. * @param aspectRatio Define the current aspect ratio of the effect
  87963. */
  87964. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  87965. if (aspectRatio === void 0) { aspectRatio = 1; }
  87966. // Color Curves
  87967. if (this._colorCurvesEnabled && this.colorCurves) {
  87968. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  87969. }
  87970. // Vignette
  87971. if (this._vignetteEnabled) {
  87972. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  87973. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  87974. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  87975. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  87976. var vignetteScaleX = vignetteScaleY * aspectRatio;
  87977. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  87978. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  87979. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  87980. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  87981. var vignettePower = -2.0 * this.vignetteWeight;
  87982. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  87983. }
  87984. // Exposure
  87985. effect.setFloat("exposureLinear", this.exposure);
  87986. // Contrast
  87987. effect.setFloat("contrast", this.contrast);
  87988. // Color transform settings
  87989. if (this.colorGradingTexture) {
  87990. effect.setTexture("txColorTransform", this.colorGradingTexture);
  87991. var textureSize = this.colorGradingTexture.getSize().height;
  87992. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  87993. 0.5 / textureSize, // textureOffset
  87994. textureSize, // textureSize
  87995. this.colorGradingTexture.level // weight
  87996. );
  87997. }
  87998. };
  87999. /**
  88000. * Clones the current image processing instance.
  88001. * @return The cloned image processing
  88002. */
  88003. ImageProcessingConfiguration.prototype.clone = function () {
  88004. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  88005. };
  88006. /**
  88007. * Serializes the current image processing instance to a json representation.
  88008. * @return a JSON representation
  88009. */
  88010. ImageProcessingConfiguration.prototype.serialize = function () {
  88011. return BABYLON.SerializationHelper.Serialize(this);
  88012. };
  88013. /**
  88014. * Parses the image processing from a json representation.
  88015. * @param source the JSON source to parse
  88016. * @return The parsed image processing
  88017. */
  88018. ImageProcessingConfiguration.Parse = function (source) {
  88019. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  88020. };
  88021. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  88022. /**
  88023. * Used to apply the vignette as a mix with the pixel color.
  88024. */
  88025. get: function () {
  88026. return this._VIGNETTEMODE_MULTIPLY;
  88027. },
  88028. enumerable: true,
  88029. configurable: true
  88030. });
  88031. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  88032. /**
  88033. * Used to apply the vignette as a replacement of the pixel color.
  88034. */
  88035. get: function () {
  88036. return this._VIGNETTEMODE_OPAQUE;
  88037. },
  88038. enumerable: true,
  88039. configurable: true
  88040. });
  88041. /**
  88042. * Default tone mapping applied in BabylonJS.
  88043. */
  88044. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  88045. /**
  88046. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  88047. * to other engines rendering to increase portability.
  88048. */
  88049. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  88050. // Static constants associated to the image processing.
  88051. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  88052. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  88053. __decorate([
  88054. BABYLON.serializeAsColorCurves()
  88055. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  88056. __decorate([
  88057. BABYLON.serialize()
  88058. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  88059. __decorate([
  88060. BABYLON.serializeAsTexture("colorGradingTexture")
  88061. ], ImageProcessingConfiguration.prototype, "_colorGradingTexture", void 0);
  88062. __decorate([
  88063. BABYLON.serialize()
  88064. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  88065. __decorate([
  88066. BABYLON.serialize()
  88067. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  88068. __decorate([
  88069. BABYLON.serialize()
  88070. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  88071. __decorate([
  88072. BABYLON.serialize()
  88073. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  88074. __decorate([
  88075. BABYLON.serialize()
  88076. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  88077. __decorate([
  88078. BABYLON.serialize()
  88079. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  88080. __decorate([
  88081. BABYLON.serialize()
  88082. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  88083. __decorate([
  88084. BABYLON.serialize()
  88085. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  88086. __decorate([
  88087. BABYLON.serialize()
  88088. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  88089. __decorate([
  88090. BABYLON.serialize()
  88091. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  88092. __decorate([
  88093. BABYLON.serialize()
  88094. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  88095. __decorate([
  88096. BABYLON.serializeAsColor4()
  88097. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  88098. __decorate([
  88099. BABYLON.serialize()
  88100. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  88101. __decorate([
  88102. BABYLON.serialize()
  88103. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  88104. __decorate([
  88105. BABYLON.serialize()
  88106. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  88107. __decorate([
  88108. BABYLON.serialize()
  88109. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  88110. __decorate([
  88111. BABYLON.serialize()
  88112. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  88113. return ImageProcessingConfiguration;
  88114. }());
  88115. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  88116. })(BABYLON || (BABYLON = {}));
  88117. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  88118. var BABYLON;
  88119. (function (BABYLON) {
  88120. /**
  88121. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  88122. * It can help converting any input color in a desired output one. This can then be used to create effects
  88123. * from sepia, black and white to sixties or futuristic rendering...
  88124. *
  88125. * The only supported format is currently 3dl.
  88126. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table
  88127. */
  88128. var ColorGradingTexture = /** @class */ (function (_super) {
  88129. __extends(ColorGradingTexture, _super);
  88130. /**
  88131. * Instantiates a ColorGradingTexture from the following parameters.
  88132. *
  88133. * @param url The location of the color gradind data (currently only supporting 3dl)
  88134. * @param scene The scene the texture will be used in
  88135. */
  88136. function ColorGradingTexture(url, scene) {
  88137. var _this = _super.call(this, scene) || this;
  88138. if (!url) {
  88139. return _this;
  88140. }
  88141. _this._engine = scene.getEngine();
  88142. _this._textureMatrix = BABYLON.Matrix.Identity();
  88143. _this.name = url;
  88144. _this.url = url;
  88145. _this.hasAlpha = false;
  88146. _this.isCube = false;
  88147. _this.is3D = _this._engine.webGLVersion > 1;
  88148. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88149. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88150. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88151. _this.anisotropicFilteringLevel = 1;
  88152. _this._texture = _this._getFromCache(url, true);
  88153. if (!_this._texture) {
  88154. if (!scene.useDelayedTextureLoading) {
  88155. _this.loadTexture();
  88156. }
  88157. else {
  88158. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  88159. }
  88160. }
  88161. return _this;
  88162. }
  88163. /**
  88164. * Returns the texture matrix used in most of the material.
  88165. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  88166. */
  88167. ColorGradingTexture.prototype.getTextureMatrix = function () {
  88168. return this._textureMatrix;
  88169. };
  88170. /**
  88171. * Occurs when the file being loaded is a .3dl LUT file.
  88172. */
  88173. ColorGradingTexture.prototype.load3dlTexture = function () {
  88174. var engine = this._engine;
  88175. var texture;
  88176. if (engine.webGLVersion === 1) {
  88177. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88178. }
  88179. else {
  88180. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88181. }
  88182. this._texture = texture;
  88183. var callback = function (text) {
  88184. if (typeof text !== "string") {
  88185. return;
  88186. }
  88187. var data = null;
  88188. var tempData = null;
  88189. var line;
  88190. var lines = text.split('\n');
  88191. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  88192. var maxColor = 0;
  88193. for (var i = 0; i < lines.length; i++) {
  88194. line = lines[i];
  88195. if (!ColorGradingTexture._noneEmptyLineRegex.test(line)) {
  88196. continue;
  88197. }
  88198. if (line.indexOf('#') === 0) {
  88199. continue;
  88200. }
  88201. var words = line.split(" ");
  88202. if (size === 0) {
  88203. // Number of space + one
  88204. size = words.length;
  88205. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  88206. tempData = new Float32Array(size * size * size * 4);
  88207. continue;
  88208. }
  88209. if (size != 0) {
  88210. var r = Math.max(parseInt(words[0]), 0);
  88211. var g = Math.max(parseInt(words[1]), 0);
  88212. var b = Math.max(parseInt(words[2]), 0);
  88213. maxColor = Math.max(r, maxColor);
  88214. maxColor = Math.max(g, maxColor);
  88215. maxColor = Math.max(b, maxColor);
  88216. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  88217. if (tempData) {
  88218. tempData[pixelStorageIndex + 0] = r;
  88219. tempData[pixelStorageIndex + 1] = g;
  88220. tempData[pixelStorageIndex + 2] = b;
  88221. }
  88222. // Keep for reference in case of back compat problems.
  88223. // pixelIndexSlice++;
  88224. // if (pixelIndexSlice % size == 0) {
  88225. // pixelIndexH++;
  88226. // pixelIndexSlice = 0;
  88227. // if (pixelIndexH % size == 0) {
  88228. // pixelIndexW++;
  88229. // pixelIndexH = 0;
  88230. // }
  88231. // }
  88232. pixelIndexH++;
  88233. if (pixelIndexH % size == 0) {
  88234. pixelIndexSlice++;
  88235. pixelIndexH = 0;
  88236. if (pixelIndexSlice % size == 0) {
  88237. pixelIndexW++;
  88238. pixelIndexSlice = 0;
  88239. }
  88240. }
  88241. }
  88242. }
  88243. if (tempData && data) {
  88244. for (var i = 0; i < tempData.length; i++) {
  88245. if (i > 0 && (i + 1) % 4 === 0) {
  88246. data[i] = 255;
  88247. }
  88248. else {
  88249. var value = tempData[i];
  88250. data[i] = (value / maxColor * 255);
  88251. }
  88252. }
  88253. }
  88254. if (texture.is3D) {
  88255. texture.updateSize(size, size, size);
  88256. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  88257. }
  88258. else {
  88259. texture.updateSize(size * size, size);
  88260. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  88261. }
  88262. };
  88263. var scene = this.getScene();
  88264. if (scene) {
  88265. scene._loadFile(this.url, callback);
  88266. }
  88267. else {
  88268. this._engine._loadFile(this.url, callback);
  88269. }
  88270. return this._texture;
  88271. };
  88272. /**
  88273. * Starts the loading process of the texture.
  88274. */
  88275. ColorGradingTexture.prototype.loadTexture = function () {
  88276. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  88277. this.load3dlTexture();
  88278. }
  88279. };
  88280. /**
  88281. * Clones the color gradind texture.
  88282. */
  88283. ColorGradingTexture.prototype.clone = function () {
  88284. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  88285. // Base texture
  88286. newTexture.level = this.level;
  88287. return newTexture;
  88288. };
  88289. /**
  88290. * Called during delayed load for textures.
  88291. */
  88292. ColorGradingTexture.prototype.delayLoad = function () {
  88293. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  88294. return;
  88295. }
  88296. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  88297. this._texture = this._getFromCache(this.url, true);
  88298. if (!this._texture) {
  88299. this.loadTexture();
  88300. }
  88301. };
  88302. /**
  88303. * Parses a color grading texture serialized by Babylon.
  88304. * @param parsedTexture The texture information being parsedTexture
  88305. * @param scene The scene to load the texture in
  88306. * @param rootUrl The root url of the data assets to load
  88307. * @return A color gradind texture
  88308. */
  88309. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  88310. var texture = null;
  88311. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  88312. texture = new ColorGradingTexture(parsedTexture.name, scene);
  88313. texture.name = parsedTexture.name;
  88314. texture.level = parsedTexture.level;
  88315. }
  88316. return texture;
  88317. };
  88318. /**
  88319. * Serializes the LUT texture to json format.
  88320. */
  88321. ColorGradingTexture.prototype.serialize = function () {
  88322. if (!this.name) {
  88323. return null;
  88324. }
  88325. var serializationObject = {};
  88326. serializationObject.name = this.name;
  88327. serializationObject.level = this.level;
  88328. serializationObject.customType = "BABYLON.ColorGradingTexture";
  88329. return serializationObject;
  88330. };
  88331. /**
  88332. * Empty line regex stored for GC.
  88333. */
  88334. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  88335. return ColorGradingTexture;
  88336. }(BABYLON.BaseTexture));
  88337. BABYLON.ColorGradingTexture = ColorGradingTexture;
  88338. })(BABYLON || (BABYLON = {}));
  88339. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  88340. var BABYLON;
  88341. (function (BABYLON) {
  88342. /**
  88343. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  88344. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  88345. * 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;
  88346. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  88347. */
  88348. var ColorCurves = /** @class */ (function () {
  88349. function ColorCurves() {
  88350. this._dirty = true;
  88351. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  88352. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  88353. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  88354. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  88355. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  88356. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  88357. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  88358. this._globalHue = 30;
  88359. this._globalDensity = 0;
  88360. this._globalSaturation = 0;
  88361. this._globalExposure = 0;
  88362. this._highlightsHue = 30;
  88363. this._highlightsDensity = 0;
  88364. this._highlightsSaturation = 0;
  88365. this._highlightsExposure = 0;
  88366. this._midtonesHue = 30;
  88367. this._midtonesDensity = 0;
  88368. this._midtonesSaturation = 0;
  88369. this._midtonesExposure = 0;
  88370. this._shadowsHue = 30;
  88371. this._shadowsDensity = 0;
  88372. this._shadowsSaturation = 0;
  88373. this._shadowsExposure = 0;
  88374. }
  88375. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  88376. /**
  88377. * Gets the global Hue value.
  88378. * 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).
  88379. */
  88380. get: function () {
  88381. return this._globalHue;
  88382. },
  88383. /**
  88384. * Sets the global Hue value.
  88385. * 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).
  88386. */
  88387. set: function (value) {
  88388. this._globalHue = value;
  88389. this._dirty = true;
  88390. },
  88391. enumerable: true,
  88392. configurable: true
  88393. });
  88394. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  88395. /**
  88396. * Gets the global Density value.
  88397. * 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.
  88398. * Values less than zero provide a filter of opposite hue.
  88399. */
  88400. get: function () {
  88401. return this._globalDensity;
  88402. },
  88403. /**
  88404. * Sets the global Density value.
  88405. * 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.
  88406. * Values less than zero provide a filter of opposite hue.
  88407. */
  88408. set: function (value) {
  88409. this._globalDensity = value;
  88410. this._dirty = true;
  88411. },
  88412. enumerable: true,
  88413. configurable: true
  88414. });
  88415. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  88416. /**
  88417. * Gets the global Saturation value.
  88418. * 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.
  88419. */
  88420. get: function () {
  88421. return this._globalSaturation;
  88422. },
  88423. /**
  88424. * Sets the global Saturation value.
  88425. * 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.
  88426. */
  88427. set: function (value) {
  88428. this._globalSaturation = value;
  88429. this._dirty = true;
  88430. },
  88431. enumerable: true,
  88432. configurable: true
  88433. });
  88434. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  88435. /**
  88436. * Gets the global Exposure value.
  88437. * 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.
  88438. */
  88439. get: function () {
  88440. return this._globalExposure;
  88441. },
  88442. /**
  88443. * Sets the global Exposure value.
  88444. * 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.
  88445. */
  88446. set: function (value) {
  88447. this._globalExposure = value;
  88448. this._dirty = true;
  88449. },
  88450. enumerable: true,
  88451. configurable: true
  88452. });
  88453. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  88454. /**
  88455. * Gets the highlights Hue value.
  88456. * 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).
  88457. */
  88458. get: function () {
  88459. return this._highlightsHue;
  88460. },
  88461. /**
  88462. * Sets the highlights Hue value.
  88463. * 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).
  88464. */
  88465. set: function (value) {
  88466. this._highlightsHue = value;
  88467. this._dirty = true;
  88468. },
  88469. enumerable: true,
  88470. configurable: true
  88471. });
  88472. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  88473. /**
  88474. * Gets the highlights Density value.
  88475. * 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.
  88476. * Values less than zero provide a filter of opposite hue.
  88477. */
  88478. get: function () {
  88479. return this._highlightsDensity;
  88480. },
  88481. /**
  88482. * Sets the highlights Density value.
  88483. * 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.
  88484. * Values less than zero provide a filter of opposite hue.
  88485. */
  88486. set: function (value) {
  88487. this._highlightsDensity = value;
  88488. this._dirty = true;
  88489. },
  88490. enumerable: true,
  88491. configurable: true
  88492. });
  88493. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  88494. /**
  88495. * Gets the highlights Saturation value.
  88496. * 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.
  88497. */
  88498. get: function () {
  88499. return this._highlightsSaturation;
  88500. },
  88501. /**
  88502. * Sets the highlights Saturation value.
  88503. * 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.
  88504. */
  88505. set: function (value) {
  88506. this._highlightsSaturation = value;
  88507. this._dirty = true;
  88508. },
  88509. enumerable: true,
  88510. configurable: true
  88511. });
  88512. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  88513. /**
  88514. * Gets the highlights Exposure value.
  88515. * 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.
  88516. */
  88517. get: function () {
  88518. return this._highlightsExposure;
  88519. },
  88520. /**
  88521. * Sets the highlights Exposure value.
  88522. * 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.
  88523. */
  88524. set: function (value) {
  88525. this._highlightsExposure = value;
  88526. this._dirty = true;
  88527. },
  88528. enumerable: true,
  88529. configurable: true
  88530. });
  88531. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  88532. /**
  88533. * Gets the midtones Hue value.
  88534. * 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).
  88535. */
  88536. get: function () {
  88537. return this._midtonesHue;
  88538. },
  88539. /**
  88540. * Sets the midtones Hue value.
  88541. * 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).
  88542. */
  88543. set: function (value) {
  88544. this._midtonesHue = value;
  88545. this._dirty = true;
  88546. },
  88547. enumerable: true,
  88548. configurable: true
  88549. });
  88550. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  88551. /**
  88552. * Gets the midtones Density value.
  88553. * 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.
  88554. * Values less than zero provide a filter of opposite hue.
  88555. */
  88556. get: function () {
  88557. return this._midtonesDensity;
  88558. },
  88559. /**
  88560. * Sets the midtones Density value.
  88561. * 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.
  88562. * Values less than zero provide a filter of opposite hue.
  88563. */
  88564. set: function (value) {
  88565. this._midtonesDensity = value;
  88566. this._dirty = true;
  88567. },
  88568. enumerable: true,
  88569. configurable: true
  88570. });
  88571. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  88572. /**
  88573. * Gets the midtones Saturation value.
  88574. * 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.
  88575. */
  88576. get: function () {
  88577. return this._midtonesSaturation;
  88578. },
  88579. /**
  88580. * Sets the midtones Saturation value.
  88581. * 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.
  88582. */
  88583. set: function (value) {
  88584. this._midtonesSaturation = value;
  88585. this._dirty = true;
  88586. },
  88587. enumerable: true,
  88588. configurable: true
  88589. });
  88590. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  88591. /**
  88592. * Gets the midtones Exposure value.
  88593. * 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.
  88594. */
  88595. get: function () {
  88596. return this._midtonesExposure;
  88597. },
  88598. /**
  88599. * Sets the midtones Exposure value.
  88600. * 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.
  88601. */
  88602. set: function (value) {
  88603. this._midtonesExposure = value;
  88604. this._dirty = true;
  88605. },
  88606. enumerable: true,
  88607. configurable: true
  88608. });
  88609. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  88610. /**
  88611. * Gets the shadows Hue value.
  88612. * 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).
  88613. */
  88614. get: function () {
  88615. return this._shadowsHue;
  88616. },
  88617. /**
  88618. * Sets the shadows Hue value.
  88619. * 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).
  88620. */
  88621. set: function (value) {
  88622. this._shadowsHue = value;
  88623. this._dirty = true;
  88624. },
  88625. enumerable: true,
  88626. configurable: true
  88627. });
  88628. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  88629. /**
  88630. * Gets the shadows Density value.
  88631. * 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.
  88632. * Values less than zero provide a filter of opposite hue.
  88633. */
  88634. get: function () {
  88635. return this._shadowsDensity;
  88636. },
  88637. /**
  88638. * Sets the shadows Density value.
  88639. * 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.
  88640. * Values less than zero provide a filter of opposite hue.
  88641. */
  88642. set: function (value) {
  88643. this._shadowsDensity = value;
  88644. this._dirty = true;
  88645. },
  88646. enumerable: true,
  88647. configurable: true
  88648. });
  88649. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  88650. /**
  88651. * Gets the shadows Saturation value.
  88652. * 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.
  88653. */
  88654. get: function () {
  88655. return this._shadowsSaturation;
  88656. },
  88657. /**
  88658. * Sets the shadows Saturation value.
  88659. * 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.
  88660. */
  88661. set: function (value) {
  88662. this._shadowsSaturation = value;
  88663. this._dirty = true;
  88664. },
  88665. enumerable: true,
  88666. configurable: true
  88667. });
  88668. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  88669. /**
  88670. * Gets the shadows Exposure value.
  88671. * 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.
  88672. */
  88673. get: function () {
  88674. return this._shadowsExposure;
  88675. },
  88676. /**
  88677. * Sets the shadows Exposure value.
  88678. * 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.
  88679. */
  88680. set: function (value) {
  88681. this._shadowsExposure = value;
  88682. this._dirty = true;
  88683. },
  88684. enumerable: true,
  88685. configurable: true
  88686. });
  88687. /**
  88688. * Returns the class name
  88689. * @returns The class name
  88690. */
  88691. ColorCurves.prototype.getClassName = function () {
  88692. return "ColorCurves";
  88693. };
  88694. /**
  88695. * Binds the color curves to the shader.
  88696. * @param colorCurves The color curve to bind
  88697. * @param effect The effect to bind to
  88698. * @param positiveUniform The positive uniform shader parameter
  88699. * @param neutralUniform The neutral uniform shader parameter
  88700. * @param negativeUniform The negative uniform shader parameter
  88701. */
  88702. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  88703. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  88704. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  88705. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  88706. if (colorCurves._dirty) {
  88707. colorCurves._dirty = false;
  88708. // Fill in global info.
  88709. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  88710. // Compute highlights info.
  88711. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  88712. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  88713. // Compute midtones info.
  88714. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  88715. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  88716. // Compute shadows info.
  88717. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  88718. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  88719. // Compute deltas (neutral is midtones).
  88720. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  88721. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  88722. }
  88723. if (effect) {
  88724. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  88725. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  88726. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  88727. }
  88728. };
  88729. /**
  88730. * Prepare the list of uniforms associated with the ColorCurves effects.
  88731. * @param uniformsList The list of uniforms used in the effect
  88732. */
  88733. ColorCurves.PrepareUniforms = function (uniformsList) {
  88734. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  88735. };
  88736. /**
  88737. * Returns color grading data based on a hue, density, saturation and exposure value.
  88738. * @param filterHue The hue of the color filter.
  88739. * @param filterDensity The density of the color filter.
  88740. * @param saturation The saturation.
  88741. * @param exposure The exposure.
  88742. * @param result The result data container.
  88743. */
  88744. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  88745. if (hue == null) {
  88746. return;
  88747. }
  88748. hue = ColorCurves.clamp(hue, 0, 360);
  88749. density = ColorCurves.clamp(density, -100, 100);
  88750. saturation = ColorCurves.clamp(saturation, -100, 100);
  88751. exposure = ColorCurves.clamp(exposure, -100, 100);
  88752. // Remap the slider/config filter density with non-linear mapping and also scale by half
  88753. // so that the maximum filter density is only 50% control. This provides fine control
  88754. // for small values and reasonable range.
  88755. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  88756. density *= 0.5;
  88757. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  88758. if (density < 0) {
  88759. density *= -1;
  88760. hue = (hue + 180) % 360;
  88761. }
  88762. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  88763. result.scaleToRef(2, result);
  88764. result.a = 1 + 0.01 * saturation;
  88765. };
  88766. /**
  88767. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  88768. * @param value The input slider value in range [-100,100].
  88769. * @returns Adjusted value.
  88770. */
  88771. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  88772. value /= 100;
  88773. var x = Math.abs(value);
  88774. x = Math.pow(x, 2);
  88775. if (value < 0) {
  88776. x *= -1;
  88777. }
  88778. x *= 100;
  88779. return x;
  88780. };
  88781. /**
  88782. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  88783. * @param hue The hue (H) input.
  88784. * @param saturation The saturation (S) input.
  88785. * @param brightness The brightness (B) input.
  88786. * @result An RGBA color represented as Vector4.
  88787. */
  88788. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  88789. var h = ColorCurves.clamp(hue, 0, 360);
  88790. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  88791. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  88792. if (s === 0) {
  88793. result.r = v;
  88794. result.g = v;
  88795. result.b = v;
  88796. }
  88797. else {
  88798. // sector 0 to 5
  88799. h /= 60;
  88800. var i = Math.floor(h);
  88801. // fractional part of h
  88802. var f = h - i;
  88803. var p = v * (1 - s);
  88804. var q = v * (1 - s * f);
  88805. var t = v * (1 - s * (1 - f));
  88806. switch (i) {
  88807. case 0:
  88808. result.r = v;
  88809. result.g = t;
  88810. result.b = p;
  88811. break;
  88812. case 1:
  88813. result.r = q;
  88814. result.g = v;
  88815. result.b = p;
  88816. break;
  88817. case 2:
  88818. result.r = p;
  88819. result.g = v;
  88820. result.b = t;
  88821. break;
  88822. case 3:
  88823. result.r = p;
  88824. result.g = q;
  88825. result.b = v;
  88826. break;
  88827. case 4:
  88828. result.r = t;
  88829. result.g = p;
  88830. result.b = v;
  88831. break;
  88832. default: // case 5:
  88833. result.r = v;
  88834. result.g = p;
  88835. result.b = q;
  88836. break;
  88837. }
  88838. }
  88839. result.a = 1;
  88840. };
  88841. /**
  88842. * Returns a value clamped between min and max
  88843. * @param value The value to clamp
  88844. * @param min The minimum of value
  88845. * @param max The maximum of value
  88846. * @returns The clamped value.
  88847. */
  88848. ColorCurves.clamp = function (value, min, max) {
  88849. return Math.min(Math.max(value, min), max);
  88850. };
  88851. /**
  88852. * Clones the current color curve instance.
  88853. * @return The cloned curves
  88854. */
  88855. ColorCurves.prototype.clone = function () {
  88856. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  88857. };
  88858. /**
  88859. * Serializes the current color curve instance to a json representation.
  88860. * @return a JSON representation
  88861. */
  88862. ColorCurves.prototype.serialize = function () {
  88863. return BABYLON.SerializationHelper.Serialize(this);
  88864. };
  88865. /**
  88866. * Parses the color curve from a json representation.
  88867. * @param source the JSON source to parse
  88868. * @return The parsed curves
  88869. */
  88870. ColorCurves.Parse = function (source) {
  88871. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  88872. };
  88873. __decorate([
  88874. BABYLON.serialize()
  88875. ], ColorCurves.prototype, "_globalHue", void 0);
  88876. __decorate([
  88877. BABYLON.serialize()
  88878. ], ColorCurves.prototype, "_globalDensity", void 0);
  88879. __decorate([
  88880. BABYLON.serialize()
  88881. ], ColorCurves.prototype, "_globalSaturation", void 0);
  88882. __decorate([
  88883. BABYLON.serialize()
  88884. ], ColorCurves.prototype, "_globalExposure", void 0);
  88885. __decorate([
  88886. BABYLON.serialize()
  88887. ], ColorCurves.prototype, "_highlightsHue", void 0);
  88888. __decorate([
  88889. BABYLON.serialize()
  88890. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  88891. __decorate([
  88892. BABYLON.serialize()
  88893. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  88894. __decorate([
  88895. BABYLON.serialize()
  88896. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  88897. __decorate([
  88898. BABYLON.serialize()
  88899. ], ColorCurves.prototype, "_midtonesHue", void 0);
  88900. __decorate([
  88901. BABYLON.serialize()
  88902. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  88903. __decorate([
  88904. BABYLON.serialize()
  88905. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  88906. __decorate([
  88907. BABYLON.serialize()
  88908. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  88909. return ColorCurves;
  88910. }());
  88911. BABYLON.ColorCurves = ColorCurves;
  88912. })(BABYLON || (BABYLON = {}));
  88913. //# sourceMappingURL=babylon.colorCurves.js.map
  88914. var BABYLON;
  88915. (function (BABYLON) {
  88916. /**
  88917. * Post process which applies a refractin texture
  88918. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  88919. */
  88920. var RefractionPostProcess = /** @class */ (function (_super) {
  88921. __extends(RefractionPostProcess, _super);
  88922. /**
  88923. * Initializes the RefractionPostProcess
  88924. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  88925. * @param name The name of the effect.
  88926. * @param refractionTextureUrl Url of the refraction texture to use
  88927. * @param color the base color of the refraction (used to taint the rendering)
  88928. * @param depth simulated refraction depth
  88929. * @param colorLevel the coefficient of the base color (0 to remove base color tainting)
  88930. * @param camera The camera to apply the render pass to.
  88931. * @param options The required width/height ratio to downsize to before computing the render pass.
  88932. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88933. * @param engine The engine which the post process will be applied. (default: current engine)
  88934. * @param reusable If the post process can be reused on the same frame. (default: false)
  88935. */
  88936. function RefractionPostProcess(name, refractionTextureUrl,
  88937. /** the base color of the refraction (used to taint the rendering) */
  88938. color,
  88939. /** simulated refraction depth */
  88940. depth,
  88941. /** the coefficient of the base color (0 to remove base color tainting) */
  88942. colorLevel, options, camera, samplingMode, engine, reusable) {
  88943. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  88944. _this.color = color;
  88945. _this.depth = depth;
  88946. _this.colorLevel = colorLevel;
  88947. _this._ownRefractionTexture = true;
  88948. _this.onActivateObservable.add(function (cam) {
  88949. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  88950. });
  88951. _this.onApplyObservable.add(function (effect) {
  88952. effect.setColor3("baseColor", _this.color);
  88953. effect.setFloat("depth", _this.depth);
  88954. effect.setFloat("colorLevel", _this.colorLevel);
  88955. effect.setTexture("refractionSampler", _this._refTexture);
  88956. });
  88957. return _this;
  88958. }
  88959. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  88960. /**
  88961. * Gets or sets the refraction texture
  88962. * Please note that you are responsible for disposing the texture if you set it manually
  88963. */
  88964. get: function () {
  88965. return this._refTexture;
  88966. },
  88967. set: function (value) {
  88968. if (this._refTexture && this._ownRefractionTexture) {
  88969. this._refTexture.dispose();
  88970. }
  88971. this._refTexture = value;
  88972. this._ownRefractionTexture = false;
  88973. },
  88974. enumerable: true,
  88975. configurable: true
  88976. });
  88977. // Methods
  88978. /**
  88979. * Disposes of the post process
  88980. * @param camera Camera to dispose post process on
  88981. */
  88982. RefractionPostProcess.prototype.dispose = function (camera) {
  88983. if (this._refTexture && this._ownRefractionTexture) {
  88984. this._refTexture.dispose();
  88985. this._refTexture = null;
  88986. }
  88987. _super.prototype.dispose.call(this, camera);
  88988. };
  88989. return RefractionPostProcess;
  88990. }(BABYLON.PostProcess));
  88991. BABYLON.RefractionPostProcess = RefractionPostProcess;
  88992. })(BABYLON || (BABYLON = {}));
  88993. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  88994. var BABYLON;
  88995. (function (BABYLON) {
  88996. /**
  88997. * Post process used to render in black and white
  88998. */
  88999. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  89000. __extends(BlackAndWhitePostProcess, _super);
  89001. /**
  89002. * Creates a black and white post process
  89003. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#black-and-white
  89004. * @param name The name of the effect.
  89005. * @param options The required width/height ratio to downsize to before computing the render pass.
  89006. * @param camera The camera to apply the render pass to.
  89007. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  89008. * @param engine The engine which the post process will be applied. (default: current engine)
  89009. * @param reusable If the post process can be reused on the same frame. (default: false)
  89010. */
  89011. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  89012. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  89013. /**
  89014. * Linear about to convert he result to black and white (default: 1)
  89015. */
  89016. _this.degree = 1;
  89017. _this.onApplyObservable.add(function (effect) {
  89018. effect.setFloat("degree", _this.degree);
  89019. });
  89020. return _this;
  89021. }
  89022. return BlackAndWhitePostProcess;
  89023. }(BABYLON.PostProcess));
  89024. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  89025. })(BABYLON || (BABYLON = {}));
  89026. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  89027. var BABYLON;
  89028. (function (BABYLON) {
  89029. /**
  89030. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  89031. * input texture to perform effects such as edge detection or sharpening
  89032. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  89033. */
  89034. var ConvolutionPostProcess = /** @class */ (function (_super) {
  89035. __extends(ConvolutionPostProcess, _super);
  89036. /**
  89037. * Creates a new instance ConvolutionPostProcess
  89038. * @param name The name of the effect.
  89039. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  89040. * @param options The required width/height ratio to downsize to before computing the render pass.
  89041. * @param camera The camera to apply the render pass to.
  89042. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  89043. * @param engine The engine which the post process will be applied. (default: current engine)
  89044. * @param reusable If the post process can be reused on the same frame. (default: false)
  89045. * @param textureType Type of textures used when performing the post process. (default: 0)
  89046. */
  89047. function ConvolutionPostProcess(name,
  89048. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  89049. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  89050. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  89051. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  89052. _this.kernel = kernel;
  89053. _this.onApply = function (effect) {
  89054. effect.setFloat2("screenSize", _this.width, _this.height);
  89055. effect.setArray("kernel", _this.kernel);
  89056. };
  89057. return _this;
  89058. }
  89059. // Statics
  89060. /**
  89061. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  89062. */
  89063. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  89064. /**
  89065. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  89066. */
  89067. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  89068. /**
  89069. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  89070. */
  89071. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  89072. /**
  89073. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  89074. */
  89075. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  89076. /**
  89077. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  89078. */
  89079. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  89080. /**
  89081. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  89082. */
  89083. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  89084. return ConvolutionPostProcess;
  89085. }(BABYLON.PostProcess));
  89086. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  89087. })(BABYLON || (BABYLON = {}));
  89088. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  89089. var BABYLON;
  89090. (function (BABYLON) {
  89091. /**
  89092. * Applies a kernel filter to the image
  89093. */
  89094. var FilterPostProcess = /** @class */ (function (_super) {
  89095. __extends(FilterPostProcess, _super);
  89096. /**
  89097. *
  89098. * @param name The name of the effect.
  89099. * @param kernelMatrix The matrix to be applied to the image
  89100. * @param options The required width/height ratio to downsize to before computing the render pass.
  89101. * @param camera The camera to apply the render pass to.
  89102. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  89103. * @param engine The engine which the post process will be applied. (default: current engine)
  89104. * @param reusable If the post process can be reused on the same frame. (default: false)
  89105. */
  89106. function FilterPostProcess(name,
  89107. /** The matrix to be applied to the image */
  89108. kernelMatrix, options, camera, samplingMode, engine, reusable) {
  89109. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  89110. _this.kernelMatrix = kernelMatrix;
  89111. _this.onApply = function (effect) {
  89112. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  89113. };
  89114. return _this;
  89115. }
  89116. return FilterPostProcess;
  89117. }(BABYLON.PostProcess));
  89118. BABYLON.FilterPostProcess = FilterPostProcess;
  89119. })(BABYLON || (BABYLON = {}));
  89120. //# sourceMappingURL=babylon.filterPostProcess.js.map
  89121. var BABYLON;
  89122. (function (BABYLON) {
  89123. /**
  89124. * Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  89125. */
  89126. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  89127. __extends(VolumetricLightScatteringPostProcess, _super);
  89128. /**
  89129. * @constructor
  89130. * @param name The post-process name
  89131. * @param 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)
  89132. * @param camera The camera that the post-process will be attached to
  89133. * @param mesh The mesh used to create the light scattering
  89134. * @param samples The post-process quality, default 100
  89135. * @param samplingModeThe post-process filtering mode
  89136. * @param engine The babylon engine
  89137. * @param reusable If the post-process is reusable
  89138. * @param scene The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  89139. */
  89140. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  89141. if (samples === void 0) { samples = 100; }
  89142. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  89143. 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;
  89144. _this._screenCoordinates = BABYLON.Vector2.Zero();
  89145. /**
  89146. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  89147. */
  89148. _this.customMeshPosition = BABYLON.Vector3.Zero();
  89149. /**
  89150. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  89151. */
  89152. _this.useCustomMeshPosition = false;
  89153. /**
  89154. * If the post-process should inverse the light scattering direction
  89155. */
  89156. _this.invert = true;
  89157. /**
  89158. * Array containing the excluded meshes not rendered in the internal pass
  89159. */
  89160. _this.excludedMeshes = new Array();
  89161. /**
  89162. * Controls the overall intensity of the post-process
  89163. */
  89164. _this.exposure = 0.3;
  89165. /**
  89166. * Dissipates each sample's contribution in range [0, 1]
  89167. */
  89168. _this.decay = 0.96815;
  89169. /**
  89170. * Controls the overall intensity of each sample
  89171. */
  89172. _this.weight = 0.58767;
  89173. /**
  89174. * Controls the density of each sample
  89175. */
  89176. _this.density = 0.926;
  89177. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  89178. engine = scene.getEngine();
  89179. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  89180. // Configure mesh
  89181. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  89182. // Configure
  89183. _this._createPass(scene, ratio.passRatio || ratio);
  89184. _this.onActivate = function (camera) {
  89185. if (!_this.isSupported) {
  89186. _this.dispose(camera);
  89187. }
  89188. _this.onActivate = null;
  89189. };
  89190. _this.onApplyObservable.add(function (effect) {
  89191. _this._updateMeshScreenCoordinates(scene);
  89192. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  89193. effect.setFloat("exposure", _this.exposure);
  89194. effect.setFloat("decay", _this.decay);
  89195. effect.setFloat("weight", _this.weight);
  89196. effect.setFloat("density", _this.density);
  89197. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  89198. });
  89199. return _this;
  89200. }
  89201. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  89202. /**
  89203. * @hidden
  89204. * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
  89205. */
  89206. get: function () {
  89207. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  89208. return false;
  89209. },
  89210. set: function (useDiffuseColor) {
  89211. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  89212. },
  89213. enumerable: true,
  89214. configurable: true
  89215. });
  89216. /**
  89217. * Returns the string "VolumetricLightScatteringPostProcess"
  89218. * @returns "VolumetricLightScatteringPostProcess"
  89219. */
  89220. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  89221. return "VolumetricLightScatteringPostProcess";
  89222. };
  89223. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  89224. var mesh = subMesh.getMesh();
  89225. // Render this.mesh as default
  89226. if (mesh === this.mesh && mesh.material) {
  89227. return mesh.material.isReady(mesh);
  89228. }
  89229. var defines = [];
  89230. var attribs = [BABYLON.VertexBuffer.PositionKind];
  89231. var material = subMesh.getMaterial();
  89232. // Alpha test
  89233. if (material) {
  89234. if (material.needAlphaTesting()) {
  89235. defines.push("#define ALPHATEST");
  89236. }
  89237. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  89238. attribs.push(BABYLON.VertexBuffer.UVKind);
  89239. defines.push("#define UV1");
  89240. }
  89241. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  89242. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  89243. defines.push("#define UV2");
  89244. }
  89245. }
  89246. // Bones
  89247. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  89248. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  89249. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  89250. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  89251. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  89252. }
  89253. else {
  89254. defines.push("#define NUM_BONE_INFLUENCERS 0");
  89255. }
  89256. // Instances
  89257. if (useInstances) {
  89258. defines.push("#define INSTANCES");
  89259. attribs.push("world0");
  89260. attribs.push("world1");
  89261. attribs.push("world2");
  89262. attribs.push("world3");
  89263. }
  89264. // Get correct effect
  89265. var join = defines.join("\n");
  89266. if (this._cachedDefines !== join) {
  89267. this._cachedDefines = join;
  89268. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  89269. }
  89270. return this._volumetricLightScatteringPass.isReady();
  89271. };
  89272. /**
  89273. * Sets the new light position for light scattering effect
  89274. * @param position The new custom light position
  89275. */
  89276. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  89277. this.customMeshPosition = position;
  89278. };
  89279. /**
  89280. * Returns the light position for light scattering effect
  89281. * @return Vector3 The custom light position
  89282. */
  89283. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  89284. return this.customMeshPosition;
  89285. };
  89286. /**
  89287. * Disposes the internal assets and detaches the post-process from the camera
  89288. */
  89289. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  89290. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  89291. if (rttIndex !== -1) {
  89292. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  89293. }
  89294. this._volumetricLightScatteringRTT.dispose();
  89295. _super.prototype.dispose.call(this, camera);
  89296. };
  89297. /**
  89298. * Returns the render target texture used by the post-process
  89299. * @return the render target texture used by the post-process
  89300. */
  89301. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  89302. return this._volumetricLightScatteringRTT;
  89303. };
  89304. // Private methods
  89305. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  89306. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  89307. return true;
  89308. }
  89309. return false;
  89310. };
  89311. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  89312. var _this = this;
  89313. var engine = scene.getEngine();
  89314. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  89315. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89316. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89317. this._volumetricLightScatteringRTT.renderList = null;
  89318. this._volumetricLightScatteringRTT.renderParticles = false;
  89319. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  89320. var camera = this.getCamera();
  89321. if (camera) {
  89322. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  89323. }
  89324. else {
  89325. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  89326. }
  89327. // Custom render function for submeshes
  89328. var renderSubMesh = function (subMesh) {
  89329. var mesh = subMesh.getRenderingMesh();
  89330. if (_this._meshExcluded(mesh)) {
  89331. return;
  89332. }
  89333. var material = subMesh.getMaterial();
  89334. if (!material) {
  89335. return;
  89336. }
  89337. var scene = mesh.getScene();
  89338. var engine = scene.getEngine();
  89339. // Culling
  89340. engine.setState(material.backFaceCulling);
  89341. // Managing instances
  89342. var batch = mesh._getInstancesRenderList(subMesh._id);
  89343. if (batch.mustReturn) {
  89344. return;
  89345. }
  89346. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  89347. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  89348. var effect = _this._volumetricLightScatteringPass;
  89349. if (mesh === _this.mesh) {
  89350. if (subMesh.effect) {
  89351. effect = subMesh.effect;
  89352. }
  89353. else {
  89354. effect = material.getEffect();
  89355. }
  89356. }
  89357. engine.enableEffect(effect);
  89358. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  89359. if (mesh === _this.mesh) {
  89360. material.bind(mesh.getWorldMatrix(), mesh);
  89361. }
  89362. else {
  89363. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  89364. // Alpha test
  89365. if (material && material.needAlphaTesting()) {
  89366. var alphaTexture = material.getAlphaTestTexture();
  89367. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  89368. if (alphaTexture) {
  89369. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  89370. }
  89371. }
  89372. // Bones
  89373. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  89374. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  89375. }
  89376. }
  89377. // Draw
  89378. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  89379. }
  89380. };
  89381. // Render target texture callbacks
  89382. var savedSceneClearColor;
  89383. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  89384. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  89385. savedSceneClearColor = scene.clearColor;
  89386. scene.clearColor = sceneClearColor;
  89387. });
  89388. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  89389. scene.clearColor = savedSceneClearColor;
  89390. });
  89391. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  89392. var engine = scene.getEngine();
  89393. var index;
  89394. if (depthOnlySubMeshes.length) {
  89395. engine.setColorWrite(false);
  89396. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  89397. renderSubMesh(depthOnlySubMeshes.data[index]);
  89398. }
  89399. engine.setColorWrite(true);
  89400. }
  89401. for (index = 0; index < opaqueSubMeshes.length; index++) {
  89402. renderSubMesh(opaqueSubMeshes.data[index]);
  89403. }
  89404. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  89405. renderSubMesh(alphaTestSubMeshes.data[index]);
  89406. }
  89407. if (transparentSubMeshes.length) {
  89408. // Sort sub meshes
  89409. for (index = 0; index < transparentSubMeshes.length; index++) {
  89410. var submesh = transparentSubMeshes.data[index];
  89411. var boundingInfo = submesh.getBoundingInfo();
  89412. if (boundingInfo && scene.activeCamera) {
  89413. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  89414. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  89415. }
  89416. }
  89417. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  89418. sortedArray.sort(function (a, b) {
  89419. // Alpha index first
  89420. if (a._alphaIndex > b._alphaIndex) {
  89421. return 1;
  89422. }
  89423. if (a._alphaIndex < b._alphaIndex) {
  89424. return -1;
  89425. }
  89426. // Then distance to camera
  89427. if (a._distanceToCamera < b._distanceToCamera) {
  89428. return 1;
  89429. }
  89430. if (a._distanceToCamera > b._distanceToCamera) {
  89431. return -1;
  89432. }
  89433. return 0;
  89434. });
  89435. // Render sub meshes
  89436. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  89437. for (index = 0; index < sortedArray.length; index++) {
  89438. renderSubMesh(sortedArray[index]);
  89439. }
  89440. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  89441. }
  89442. };
  89443. };
  89444. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  89445. var transform = scene.getTransformMatrix();
  89446. var meshPosition;
  89447. if (this.useCustomMeshPosition) {
  89448. meshPosition = this.customMeshPosition;
  89449. }
  89450. else if (this.attachedNode) {
  89451. meshPosition = this.attachedNode.position;
  89452. }
  89453. else {
  89454. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  89455. }
  89456. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  89457. this._screenCoordinates.x = pos.x / this._viewPort.width;
  89458. this._screenCoordinates.y = pos.y / this._viewPort.height;
  89459. if (this.invert) {
  89460. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  89461. }
  89462. };
  89463. // Static methods
  89464. /**
  89465. * Creates a default mesh for the Volumeric Light Scattering post-process
  89466. * @param name The mesh name
  89467. * @param scene The scene where to create the mesh
  89468. * @return the default mesh
  89469. */
  89470. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  89471. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  89472. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  89473. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  89474. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  89475. mesh.material = material;
  89476. return mesh;
  89477. };
  89478. __decorate([
  89479. BABYLON.serializeAsVector3()
  89480. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  89481. __decorate([
  89482. BABYLON.serialize()
  89483. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  89484. __decorate([
  89485. BABYLON.serialize()
  89486. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  89487. __decorate([
  89488. BABYLON.serializeAsMeshReference()
  89489. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  89490. __decorate([
  89491. BABYLON.serialize()
  89492. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  89493. __decorate([
  89494. BABYLON.serialize()
  89495. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  89496. __decorate([
  89497. BABYLON.serialize()
  89498. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  89499. __decorate([
  89500. BABYLON.serialize()
  89501. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  89502. __decorate([
  89503. BABYLON.serialize()
  89504. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  89505. return VolumetricLightScatteringPostProcess;
  89506. }(BABYLON.PostProcess));
  89507. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  89508. })(BABYLON || (BABYLON = {}));
  89509. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  89510. var BABYLON;
  89511. (function (BABYLON) {
  89512. /**
  89513. *
  89514. * This post-process allows the modification of rendered colors by using
  89515. * a 'look-up table' (LUT). This effect is also called Color Grading.
  89516. *
  89517. * The object needs to be provided an url to a texture containing the color
  89518. * look-up table: the texture must be 256 pixels wide and 16 pixels high.
  89519. * Use an image editing software to tweak the LUT to match your needs.
  89520. *
  89521. * For an example of a color LUT, see here:
  89522. * @see http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  89523. * For explanations on color grading, see here:
  89524. * @see http://udn.epicgames.com/Three/ColorGrading.html
  89525. *
  89526. */
  89527. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  89528. __extends(ColorCorrectionPostProcess, _super);
  89529. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  89530. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  89531. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  89532. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  89533. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89534. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89535. _this.onApply = function (effect) {
  89536. effect.setTexture("colorTable", _this._colorTableTexture);
  89537. };
  89538. return _this;
  89539. }
  89540. return ColorCorrectionPostProcess;
  89541. }(BABYLON.PostProcess));
  89542. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  89543. })(BABYLON || (BABYLON = {}));
  89544. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  89545. var BABYLON;
  89546. (function (BABYLON) {
  89547. /** Defines operator used for tonemapping */
  89548. var TonemappingOperator;
  89549. (function (TonemappingOperator) {
  89550. /** Hable */
  89551. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  89552. /** Reinhard */
  89553. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  89554. /** HejiDawson */
  89555. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  89556. /** Photographic */
  89557. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  89558. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  89559. /**
  89560. * Defines a post process to apply tone mapping
  89561. */
  89562. var TonemapPostProcess = /** @class */ (function (_super) {
  89563. __extends(TonemapPostProcess, _super);
  89564. /**
  89565. * Creates a new TonemapPostProcess
  89566. * @param name defines the name of the postprocess
  89567. * @param _operator defines the operator to use
  89568. * @param exposureAdjustment defines the required exposure adjustement
  89569. * @param camera defines the camera to use (can be null)
  89570. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  89571. * @param engine defines the hosting engine (can be ignore if camera is set)
  89572. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  89573. */
  89574. function TonemapPostProcess(name, _operator,
  89575. /** Defines the required exposure adjustement */
  89576. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  89577. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  89578. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  89579. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  89580. _this._operator = _operator;
  89581. _this.exposureAdjustment = exposureAdjustment;
  89582. var defines = "#define ";
  89583. if (_this._operator === TonemappingOperator.Hable) {
  89584. defines += "HABLE_TONEMAPPING";
  89585. }
  89586. else if (_this._operator === TonemappingOperator.Reinhard) {
  89587. defines += "REINHARD_TONEMAPPING";
  89588. }
  89589. else if (_this._operator === TonemappingOperator.HejiDawson) {
  89590. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  89591. }
  89592. else if (_this._operator === TonemappingOperator.Photographic) {
  89593. defines += "PHOTOGRAPHIC_TONEMAPPING";
  89594. }
  89595. //sadly a second call to create the effect.
  89596. _this.updateEffect(defines);
  89597. _this.onApply = function (effect) {
  89598. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  89599. };
  89600. return _this;
  89601. }
  89602. return TonemapPostProcess;
  89603. }(BABYLON.PostProcess));
  89604. BABYLON.TonemapPostProcess = TonemapPostProcess;
  89605. })(BABYLON || (BABYLON = {}));
  89606. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  89607. var BABYLON;
  89608. (function (BABYLON) {
  89609. /**
  89610. * DisplayPassPostProcess which produces an output the same as it's input
  89611. */
  89612. var DisplayPassPostProcess = /** @class */ (function (_super) {
  89613. __extends(DisplayPassPostProcess, _super);
  89614. /**
  89615. * Creates the DisplayPassPostProcess
  89616. * @param name The name of the effect.
  89617. * @param options The required width/height ratio to downsize to before computing the render pass.
  89618. * @param camera The camera to apply the render pass to.
  89619. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  89620. * @param engine The engine which the post process will be applied. (default: current engine)
  89621. * @param reusable If the post process can be reused on the same frame. (default: false)
  89622. */
  89623. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  89624. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  89625. }
  89626. return DisplayPassPostProcess;
  89627. }(BABYLON.PostProcess));
  89628. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  89629. })(BABYLON || (BABYLON = {}));
  89630. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  89631. var BABYLON;
  89632. (function (BABYLON) {
  89633. /**
  89634. * Extracts highlights from the image
  89635. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  89636. */
  89637. var HighlightsPostProcess = /** @class */ (function (_super) {
  89638. __extends(HighlightsPostProcess, _super);
  89639. /**
  89640. * Extracts highlights from the image
  89641. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  89642. * @param name The name of the effect.
  89643. * @param options The required width/height ratio to downsize to before computing the render pass.
  89644. * @param camera The camera to apply the render pass to.
  89645. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  89646. * @param engine The engine which the post process will be applied. (default: current engine)
  89647. * @param reusable If the post process can be reused on the same frame. (default: false)
  89648. * @param textureType Type of texture for the post process (default: Engine.TEXTURETYPE_UNSIGNED_INT)
  89649. */
  89650. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  89651. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  89652. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  89653. }
  89654. return HighlightsPostProcess;
  89655. }(BABYLON.PostProcess));
  89656. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  89657. })(BABYLON || (BABYLON = {}));
  89658. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  89659. var BABYLON;
  89660. (function (BABYLON) {
  89661. /**
  89662. * ImageProcessingPostProcess
  89663. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#imageprocessing
  89664. */
  89665. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  89666. __extends(ImageProcessingPostProcess, _super);
  89667. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  89668. if (camera === void 0) { camera = null; }
  89669. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  89670. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  89671. _this._fromLinearSpace = true;
  89672. /**
  89673. * Defines cache preventing GC.
  89674. */
  89675. _this._defines = {
  89676. IMAGEPROCESSING: false,
  89677. VIGNETTE: false,
  89678. VIGNETTEBLENDMODEMULTIPLY: false,
  89679. VIGNETTEBLENDMODEOPAQUE: false,
  89680. TONEMAPPING: false,
  89681. TONEMAPPING_ACES: false,
  89682. CONTRAST: false,
  89683. COLORCURVES: false,
  89684. COLORGRADING: false,
  89685. COLORGRADING3D: false,
  89686. FROMLINEARSPACE: false,
  89687. SAMPLER3DGREENDEPTH: false,
  89688. SAMPLER3DBGRMAP: false,
  89689. IMAGEPROCESSINGPOSTPROCESS: false,
  89690. EXPOSURE: false,
  89691. };
  89692. // Setup the configuration as forced by the constructor. This would then not force the
  89693. // scene materials output in linear space and let untouched the default forward pass.
  89694. if (imageProcessingConfiguration) {
  89695. imageProcessingConfiguration.applyByPostProcess = true;
  89696. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  89697. // This will cause the shader to be compiled
  89698. _this.fromLinearSpace = false;
  89699. }
  89700. // Setup the default processing configuration to the scene.
  89701. else {
  89702. _this._attachImageProcessingConfiguration(null, true);
  89703. _this.imageProcessingConfiguration.applyByPostProcess = true;
  89704. }
  89705. _this.onApply = function (effect) {
  89706. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  89707. };
  89708. return _this;
  89709. }
  89710. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  89711. /**
  89712. * Gets the image processing configuration used either in this material.
  89713. */
  89714. get: function () {
  89715. return this._imageProcessingConfiguration;
  89716. },
  89717. /**
  89718. * Sets the Default image processing configuration used either in the this material.
  89719. *
  89720. * If sets to null, the scene one is in use.
  89721. */
  89722. set: function (value) {
  89723. this._attachImageProcessingConfiguration(value);
  89724. },
  89725. enumerable: true,
  89726. configurable: true
  89727. });
  89728. /**
  89729. * Attaches a new image processing configuration to the PBR Material.
  89730. * @param configuration
  89731. */
  89732. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  89733. var _this = this;
  89734. if (doNotBuild === void 0) { doNotBuild = false; }
  89735. if (configuration === this._imageProcessingConfiguration) {
  89736. return;
  89737. }
  89738. // Detaches observer.
  89739. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89740. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89741. }
  89742. // Pick the scene configuration if needed.
  89743. if (!configuration) {
  89744. var scene = null;
  89745. var engine = this.getEngine();
  89746. var camera = this.getCamera();
  89747. if (camera) {
  89748. scene = camera.getScene();
  89749. }
  89750. else if (engine && engine.scenes) {
  89751. var scenes = engine.scenes;
  89752. scene = scenes[scenes.length - 1];
  89753. }
  89754. else {
  89755. scene = BABYLON.Engine.LastCreatedScene;
  89756. }
  89757. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  89758. }
  89759. else {
  89760. this._imageProcessingConfiguration = configuration;
  89761. }
  89762. // Attaches observer.
  89763. if (this._imageProcessingConfiguration) {
  89764. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  89765. _this._updateParameters();
  89766. });
  89767. }
  89768. // Ensure the effect will be rebuilt.
  89769. if (!doNotBuild) {
  89770. this._updateParameters();
  89771. }
  89772. };
  89773. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  89774. /**
  89775. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  89776. */
  89777. get: function () {
  89778. return this.imageProcessingConfiguration.colorCurves;
  89779. },
  89780. /**
  89781. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  89782. */
  89783. set: function (value) {
  89784. this.imageProcessingConfiguration.colorCurves = value;
  89785. },
  89786. enumerable: true,
  89787. configurable: true
  89788. });
  89789. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  89790. /**
  89791. * Gets wether the color curves effect is enabled.
  89792. */
  89793. get: function () {
  89794. return this.imageProcessingConfiguration.colorCurvesEnabled;
  89795. },
  89796. /**
  89797. * Sets wether the color curves effect is enabled.
  89798. */
  89799. set: function (value) {
  89800. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  89801. },
  89802. enumerable: true,
  89803. configurable: true
  89804. });
  89805. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  89806. /**
  89807. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  89808. */
  89809. get: function () {
  89810. return this.imageProcessingConfiguration.colorGradingTexture;
  89811. },
  89812. /**
  89813. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  89814. */
  89815. set: function (value) {
  89816. this.imageProcessingConfiguration.colorGradingTexture = value;
  89817. },
  89818. enumerable: true,
  89819. configurable: true
  89820. });
  89821. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  89822. /**
  89823. * Gets wether the color grading effect is enabled.
  89824. */
  89825. get: function () {
  89826. return this.imageProcessingConfiguration.colorGradingEnabled;
  89827. },
  89828. /**
  89829. * Gets wether the color grading effect is enabled.
  89830. */
  89831. set: function (value) {
  89832. this.imageProcessingConfiguration.colorGradingEnabled = value;
  89833. },
  89834. enumerable: true,
  89835. configurable: true
  89836. });
  89837. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  89838. /**
  89839. * Gets exposure used in the effect.
  89840. */
  89841. get: function () {
  89842. return this.imageProcessingConfiguration.exposure;
  89843. },
  89844. /**
  89845. * Sets exposure used in the effect.
  89846. */
  89847. set: function (value) {
  89848. this.imageProcessingConfiguration.exposure = value;
  89849. },
  89850. enumerable: true,
  89851. configurable: true
  89852. });
  89853. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  89854. /**
  89855. * Gets wether tonemapping is enabled or not.
  89856. */
  89857. get: function () {
  89858. return this._imageProcessingConfiguration.toneMappingEnabled;
  89859. },
  89860. /**
  89861. * Sets wether tonemapping is enabled or not
  89862. */
  89863. set: function (value) {
  89864. this._imageProcessingConfiguration.toneMappingEnabled = value;
  89865. },
  89866. enumerable: true,
  89867. configurable: true
  89868. });
  89869. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  89870. /**
  89871. * Gets contrast used in the effect.
  89872. */
  89873. get: function () {
  89874. return this.imageProcessingConfiguration.contrast;
  89875. },
  89876. /**
  89877. * Sets contrast used in the effect.
  89878. */
  89879. set: function (value) {
  89880. this.imageProcessingConfiguration.contrast = value;
  89881. },
  89882. enumerable: true,
  89883. configurable: true
  89884. });
  89885. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  89886. /**
  89887. * Gets Vignette stretch size.
  89888. */
  89889. get: function () {
  89890. return this.imageProcessingConfiguration.vignetteStretch;
  89891. },
  89892. /**
  89893. * Sets Vignette stretch size.
  89894. */
  89895. set: function (value) {
  89896. this.imageProcessingConfiguration.vignetteStretch = value;
  89897. },
  89898. enumerable: true,
  89899. configurable: true
  89900. });
  89901. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  89902. /**
  89903. * Gets Vignette centre X Offset.
  89904. */
  89905. get: function () {
  89906. return this.imageProcessingConfiguration.vignetteCentreX;
  89907. },
  89908. /**
  89909. * Sets Vignette centre X Offset.
  89910. */
  89911. set: function (value) {
  89912. this.imageProcessingConfiguration.vignetteCentreX = value;
  89913. },
  89914. enumerable: true,
  89915. configurable: true
  89916. });
  89917. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  89918. /**
  89919. * Gets Vignette centre Y Offset.
  89920. */
  89921. get: function () {
  89922. return this.imageProcessingConfiguration.vignetteCentreY;
  89923. },
  89924. /**
  89925. * Sets Vignette centre Y Offset.
  89926. */
  89927. set: function (value) {
  89928. this.imageProcessingConfiguration.vignetteCentreY = value;
  89929. },
  89930. enumerable: true,
  89931. configurable: true
  89932. });
  89933. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  89934. /**
  89935. * Gets Vignette weight or intensity of the vignette effect.
  89936. */
  89937. get: function () {
  89938. return this.imageProcessingConfiguration.vignetteWeight;
  89939. },
  89940. /**
  89941. * Sets Vignette weight or intensity of the vignette effect.
  89942. */
  89943. set: function (value) {
  89944. this.imageProcessingConfiguration.vignetteWeight = value;
  89945. },
  89946. enumerable: true,
  89947. configurable: true
  89948. });
  89949. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  89950. /**
  89951. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  89952. * if vignetteEnabled is set to true.
  89953. */
  89954. get: function () {
  89955. return this.imageProcessingConfiguration.vignetteColor;
  89956. },
  89957. /**
  89958. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  89959. * if vignetteEnabled is set to true.
  89960. */
  89961. set: function (value) {
  89962. this.imageProcessingConfiguration.vignetteColor = value;
  89963. },
  89964. enumerable: true,
  89965. configurable: true
  89966. });
  89967. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  89968. /**
  89969. * Gets Camera field of view used by the Vignette effect.
  89970. */
  89971. get: function () {
  89972. return this.imageProcessingConfiguration.vignetteCameraFov;
  89973. },
  89974. /**
  89975. * Sets Camera field of view used by the Vignette effect.
  89976. */
  89977. set: function (value) {
  89978. this.imageProcessingConfiguration.vignetteCameraFov = value;
  89979. },
  89980. enumerable: true,
  89981. configurable: true
  89982. });
  89983. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  89984. /**
  89985. * Gets the vignette blend mode allowing different kind of effect.
  89986. */
  89987. get: function () {
  89988. return this.imageProcessingConfiguration.vignetteBlendMode;
  89989. },
  89990. /**
  89991. * Sets the vignette blend mode allowing different kind of effect.
  89992. */
  89993. set: function (value) {
  89994. this.imageProcessingConfiguration.vignetteBlendMode = value;
  89995. },
  89996. enumerable: true,
  89997. configurable: true
  89998. });
  89999. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  90000. /**
  90001. * Gets wether the vignette effect is enabled.
  90002. */
  90003. get: function () {
  90004. return this.imageProcessingConfiguration.vignetteEnabled;
  90005. },
  90006. /**
  90007. * Sets wether the vignette effect is enabled.
  90008. */
  90009. set: function (value) {
  90010. this.imageProcessingConfiguration.vignetteEnabled = value;
  90011. },
  90012. enumerable: true,
  90013. configurable: true
  90014. });
  90015. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  90016. /**
  90017. * Gets wether the input of the processing is in Gamma or Linear Space.
  90018. */
  90019. get: function () {
  90020. return this._fromLinearSpace;
  90021. },
  90022. /**
  90023. * Sets wether the input of the processing is in Gamma or Linear Space.
  90024. */
  90025. set: function (value) {
  90026. if (this._fromLinearSpace === value) {
  90027. return;
  90028. }
  90029. this._fromLinearSpace = value;
  90030. this._updateParameters();
  90031. },
  90032. enumerable: true,
  90033. configurable: true
  90034. });
  90035. /**
  90036. * "ImageProcessingPostProcess"
  90037. * @returns "ImageProcessingPostProcess"
  90038. */
  90039. ImageProcessingPostProcess.prototype.getClassName = function () {
  90040. return "ImageProcessingPostProcess";
  90041. };
  90042. ImageProcessingPostProcess.prototype._updateParameters = function () {
  90043. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  90044. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  90045. var defines = "";
  90046. for (var define in this._defines) {
  90047. if (this._defines[define]) {
  90048. defines += "#define " + define + ";\r\n";
  90049. }
  90050. }
  90051. var samplers = ["textureSampler"];
  90052. var uniforms = ["scale"];
  90053. if (BABYLON.ImageProcessingConfiguration) {
  90054. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  90055. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  90056. }
  90057. this.updateEffect(defines, uniforms, samplers);
  90058. };
  90059. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  90060. _super.prototype.dispose.call(this, camera);
  90061. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90062. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90063. }
  90064. if (this._imageProcessingConfiguration) {
  90065. this.imageProcessingConfiguration.applyByPostProcess = false;
  90066. }
  90067. };
  90068. __decorate([
  90069. BABYLON.serialize()
  90070. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  90071. return ImageProcessingPostProcess;
  90072. }(BABYLON.PostProcess));
  90073. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  90074. })(BABYLON || (BABYLON = {}));
  90075. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  90076. var BABYLON;
  90077. (function (BABYLON) {
  90078. /**
  90079. * Class used to store bone information
  90080. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  90081. */
  90082. var Bone = /** @class */ (function (_super) {
  90083. __extends(Bone, _super);
  90084. /**
  90085. * Create a new bone
  90086. * @param name defines the bone name
  90087. * @param skeleton defines the parent skeleton
  90088. * @param parentBone defines the parent (can be null if the bone is the root)
  90089. * @param localMatrix defines the local matrix
  90090. * @param restPose defines the rest pose matrix
  90091. * @param baseMatrix defines the base matrix
  90092. * @param index defines index of the bone in the hiearchy
  90093. */
  90094. function Bone(
  90095. /**
  90096. * defines the bone name
  90097. */
  90098. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  90099. if (parentBone === void 0) { parentBone = null; }
  90100. if (localMatrix === void 0) { localMatrix = null; }
  90101. if (restPose === void 0) { restPose = null; }
  90102. if (baseMatrix === void 0) { baseMatrix = null; }
  90103. if (index === void 0) { index = null; }
  90104. var _this = _super.call(this, name, skeleton.getScene()) || this;
  90105. _this.name = name;
  90106. /**
  90107. * Gets the list of child bones
  90108. */
  90109. _this.children = new Array();
  90110. /** Gets the animations associated with this bone */
  90111. _this.animations = new Array();
  90112. /**
  90113. * @hidden Internal only
  90114. * Set this value to map this bone to a different index in the transform matrices
  90115. * Set this value to -1 to exclude the bone from the transform matrices
  90116. */
  90117. _this._index = null;
  90118. _this._absoluteTransform = new BABYLON.Matrix();
  90119. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  90120. _this._scalingDeterminant = 1;
  90121. _this._worldTransform = new BABYLON.Matrix();
  90122. _this._needToDecompose = true;
  90123. _this._needToCompose = false;
  90124. _this._skeleton = skeleton;
  90125. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  90126. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  90127. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  90128. _this._index = index;
  90129. skeleton.bones.push(_this);
  90130. _this.setParent(parentBone, false);
  90131. if (baseMatrix || localMatrix) {
  90132. _this._updateDifferenceMatrix();
  90133. }
  90134. return _this;
  90135. }
  90136. Object.defineProperty(Bone.prototype, "_matrix", {
  90137. /** @hidden */
  90138. get: function () {
  90139. this._compose();
  90140. return this._localMatrix;
  90141. },
  90142. /** @hidden */
  90143. set: function (value) {
  90144. this._localMatrix.copyFrom(value);
  90145. this._needToDecompose = true;
  90146. },
  90147. enumerable: true,
  90148. configurable: true
  90149. });
  90150. // Members
  90151. /**
  90152. * Gets the parent skeleton
  90153. * @returns a skeleton
  90154. */
  90155. Bone.prototype.getSkeleton = function () {
  90156. return this._skeleton;
  90157. };
  90158. /**
  90159. * Gets parent bone
  90160. * @returns a bone or null if the bone is the root of the bone hierarchy
  90161. */
  90162. Bone.prototype.getParent = function () {
  90163. return this._parent;
  90164. };
  90165. /**
  90166. * Sets the parent bone
  90167. * @param parent defines the parent (can be null if the bone is the root)
  90168. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  90169. */
  90170. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  90171. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  90172. if (this._parent === parent) {
  90173. return;
  90174. }
  90175. if (this._parent) {
  90176. var index = this._parent.children.indexOf(this);
  90177. if (index !== -1) {
  90178. this._parent.children.splice(index, 1);
  90179. }
  90180. }
  90181. this._parent = parent;
  90182. if (this._parent) {
  90183. this._parent.children.push(this);
  90184. }
  90185. if (updateDifferenceMatrix) {
  90186. this._updateDifferenceMatrix();
  90187. }
  90188. this.markAsDirty();
  90189. };
  90190. /**
  90191. * Gets the local matrix
  90192. * @returns a matrix
  90193. */
  90194. Bone.prototype.getLocalMatrix = function () {
  90195. this._compose();
  90196. return this._localMatrix;
  90197. };
  90198. /**
  90199. * Gets the base matrix (initial matrix which remains unchanged)
  90200. * @returns a matrix
  90201. */
  90202. Bone.prototype.getBaseMatrix = function () {
  90203. return this._baseMatrix;
  90204. };
  90205. /**
  90206. * Gets the rest pose matrix
  90207. * @returns a matrix
  90208. */
  90209. Bone.prototype.getRestPose = function () {
  90210. return this._restPose;
  90211. };
  90212. /**
  90213. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  90214. */
  90215. Bone.prototype.getWorldMatrix = function () {
  90216. return this._worldTransform;
  90217. };
  90218. /**
  90219. * Sets the local matrix to rest pose matrix
  90220. */
  90221. Bone.prototype.returnToRest = function () {
  90222. this.updateMatrix(this._restPose.clone());
  90223. };
  90224. /**
  90225. * Gets the inverse of the absolute transform matrix.
  90226. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  90227. * @returns a matrix
  90228. */
  90229. Bone.prototype.getInvertedAbsoluteTransform = function () {
  90230. return this._invertedAbsoluteTransform;
  90231. };
  90232. /**
  90233. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  90234. * @returns a matrix
  90235. */
  90236. Bone.prototype.getAbsoluteTransform = function () {
  90237. return this._absoluteTransform;
  90238. };
  90239. Object.defineProperty(Bone.prototype, "position", {
  90240. // Properties (matches AbstractMesh properties)
  90241. /** Gets or sets current position (in local space) */
  90242. get: function () {
  90243. this._decompose();
  90244. return this._localPosition;
  90245. },
  90246. set: function (newPosition) {
  90247. this._decompose();
  90248. this._localPosition.copyFrom(newPosition);
  90249. this._markAsDirtyAndCompose();
  90250. },
  90251. enumerable: true,
  90252. configurable: true
  90253. });
  90254. Object.defineProperty(Bone.prototype, "rotation", {
  90255. /** Gets or sets current rotation (in local space) */
  90256. get: function () {
  90257. return this.getRotation();
  90258. },
  90259. set: function (newRotation) {
  90260. this.setRotation(newRotation);
  90261. },
  90262. enumerable: true,
  90263. configurable: true
  90264. });
  90265. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  90266. /** Gets or sets current rotation quaternion (in local space) */
  90267. get: function () {
  90268. this._decompose();
  90269. return this._localRotation;
  90270. },
  90271. set: function (newRotation) {
  90272. this.setRotationQuaternion(newRotation);
  90273. },
  90274. enumerable: true,
  90275. configurable: true
  90276. });
  90277. Object.defineProperty(Bone.prototype, "scaling", {
  90278. /** Gets or sets current scaling (in local space) */
  90279. get: function () {
  90280. return this.getScale();
  90281. },
  90282. set: function (newScaling) {
  90283. this.setScale(newScaling);
  90284. },
  90285. enumerable: true,
  90286. configurable: true
  90287. });
  90288. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  90289. /**
  90290. * Gets the animation properties override
  90291. */
  90292. get: function () {
  90293. return this._skeleton.animationPropertiesOverride;
  90294. },
  90295. enumerable: true,
  90296. configurable: true
  90297. });
  90298. // Methods
  90299. Bone.prototype._decompose = function () {
  90300. if (!this._needToDecompose) {
  90301. return;
  90302. }
  90303. this._needToDecompose = false;
  90304. if (!this._localScaling) {
  90305. this._localScaling = BABYLON.Vector3.Zero();
  90306. this._localRotation = BABYLON.Quaternion.Zero();
  90307. this._localPosition = BABYLON.Vector3.Zero();
  90308. }
  90309. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  90310. };
  90311. Bone.prototype._compose = function () {
  90312. if (!this._needToCompose) {
  90313. return;
  90314. }
  90315. this._needToCompose = false;
  90316. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  90317. };
  90318. /**
  90319. * Update the base and local matrices
  90320. * @param matrix defines the new base or local matrix
  90321. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  90322. * @param updateLocalMatrix defines if the local matrix should be updated
  90323. */
  90324. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  90325. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  90326. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  90327. this._baseMatrix.copyFrom(matrix);
  90328. if (updateDifferenceMatrix) {
  90329. this._updateDifferenceMatrix();
  90330. }
  90331. if (updateLocalMatrix) {
  90332. this._localMatrix.copyFrom(matrix);
  90333. this._markAsDirtyAndDecompose();
  90334. }
  90335. else {
  90336. this.markAsDirty();
  90337. }
  90338. };
  90339. /** @hidden */
  90340. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  90341. if (updateChildren === void 0) { updateChildren = true; }
  90342. if (!rootMatrix) {
  90343. rootMatrix = this._baseMatrix;
  90344. }
  90345. if (this._parent) {
  90346. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  90347. }
  90348. else {
  90349. this._absoluteTransform.copyFrom(rootMatrix);
  90350. }
  90351. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  90352. if (updateChildren) {
  90353. for (var index = 0; index < this.children.length; index++) {
  90354. this.children[index]._updateDifferenceMatrix();
  90355. }
  90356. }
  90357. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  90358. };
  90359. /**
  90360. * Flag the bone as dirty (Forcing it to update everything)
  90361. */
  90362. Bone.prototype.markAsDirty = function () {
  90363. this._currentRenderId++;
  90364. this._childRenderId++;
  90365. this._skeleton._markAsDirty();
  90366. };
  90367. Bone.prototype._markAsDirtyAndCompose = function () {
  90368. this.markAsDirty();
  90369. this._needToCompose = true;
  90370. };
  90371. Bone.prototype._markAsDirtyAndDecompose = function () {
  90372. this.markAsDirty();
  90373. this._needToDecompose = true;
  90374. };
  90375. /**
  90376. * Copy an animation range from another bone
  90377. * @param source defines the source bone
  90378. * @param rangeName defines the range name to copy
  90379. * @param frameOffset defines the frame offset
  90380. * @param rescaleAsRequired defines if rescaling must be applied if required
  90381. * @param skelDimensionsRatio defines the scaling ratio
  90382. * @returns true if operation was successful
  90383. */
  90384. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  90385. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  90386. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  90387. // all animation may be coming from a library skeleton, so may need to create animation
  90388. if (this.animations.length === 0) {
  90389. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  90390. this.animations[0].setKeys([]);
  90391. }
  90392. // get animation info / verify there is such a range from the source bone
  90393. var sourceRange = source.animations[0].getRange(rangeName);
  90394. if (!sourceRange) {
  90395. return false;
  90396. }
  90397. var from = sourceRange.from;
  90398. var to = sourceRange.to;
  90399. var sourceKeys = source.animations[0].getKeys();
  90400. // rescaling prep
  90401. var sourceBoneLength = source.length;
  90402. var sourceParent = source.getParent();
  90403. var parent = this.getParent();
  90404. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  90405. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  90406. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  90407. var destKeys = this.animations[0].getKeys();
  90408. // loop vars declaration
  90409. var orig;
  90410. var origTranslation;
  90411. var mat;
  90412. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  90413. orig = sourceKeys[key];
  90414. if (orig.frame >= from && orig.frame <= to) {
  90415. if (rescaleAsRequired) {
  90416. mat = orig.value.clone();
  90417. // scale based on parent ratio, when bone has parent
  90418. if (parentScalingReqd) {
  90419. origTranslation = mat.getTranslation();
  90420. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  90421. // scale based on skeleton dimension ratio when root bone, and value is passed
  90422. }
  90423. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  90424. origTranslation = mat.getTranslation();
  90425. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  90426. // use original when root bone, and no data for skelDimensionsRatio
  90427. }
  90428. else {
  90429. mat = orig.value;
  90430. }
  90431. }
  90432. else {
  90433. mat = orig.value;
  90434. }
  90435. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  90436. }
  90437. }
  90438. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  90439. return true;
  90440. };
  90441. /**
  90442. * Translate the bone in local or world space
  90443. * @param vec The amount to translate the bone
  90444. * @param space The space that the translation is in
  90445. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90446. */
  90447. Bone.prototype.translate = function (vec, space, mesh) {
  90448. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90449. var lm = this.getLocalMatrix();
  90450. if (space == BABYLON.Space.LOCAL) {
  90451. lm.m[12] += vec.x;
  90452. lm.m[13] += vec.y;
  90453. lm.m[14] += vec.z;
  90454. }
  90455. else {
  90456. var wm = null;
  90457. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90458. if (mesh) {
  90459. wm = mesh.getWorldMatrix();
  90460. }
  90461. this._skeleton.computeAbsoluteTransforms();
  90462. var tmat = Bone._tmpMats[0];
  90463. var tvec = Bone._tmpVecs[0];
  90464. if (this._parent) {
  90465. if (mesh && wm) {
  90466. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90467. tmat.multiplyToRef(wm, tmat);
  90468. }
  90469. else {
  90470. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90471. }
  90472. }
  90473. tmat.m[12] = 0;
  90474. tmat.m[13] = 0;
  90475. tmat.m[14] = 0;
  90476. tmat.invert();
  90477. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  90478. lm.m[12] += tvec.x;
  90479. lm.m[13] += tvec.y;
  90480. lm.m[14] += tvec.z;
  90481. }
  90482. this._markAsDirtyAndDecompose();
  90483. };
  90484. /**
  90485. * Set the postion of the bone in local or world space
  90486. * @param position The position to set the bone
  90487. * @param space The space that the position is in
  90488. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90489. */
  90490. Bone.prototype.setPosition = function (position, space, mesh) {
  90491. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90492. var lm = this.getLocalMatrix();
  90493. if (space == BABYLON.Space.LOCAL) {
  90494. lm.m[12] = position.x;
  90495. lm.m[13] = position.y;
  90496. lm.m[14] = position.z;
  90497. }
  90498. else {
  90499. var wm = null;
  90500. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90501. if (mesh) {
  90502. wm = mesh.getWorldMatrix();
  90503. }
  90504. this._skeleton.computeAbsoluteTransforms();
  90505. var tmat = Bone._tmpMats[0];
  90506. var vec = Bone._tmpVecs[0];
  90507. if (this._parent) {
  90508. if (mesh && wm) {
  90509. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90510. tmat.multiplyToRef(wm, tmat);
  90511. }
  90512. else {
  90513. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90514. }
  90515. }
  90516. tmat.invert();
  90517. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  90518. lm.m[12] = vec.x;
  90519. lm.m[13] = vec.y;
  90520. lm.m[14] = vec.z;
  90521. }
  90522. this._markAsDirtyAndDecompose();
  90523. };
  90524. /**
  90525. * Set the absolute position of the bone (world space)
  90526. * @param position The position to set the bone
  90527. * @param mesh The mesh that this bone is attached to
  90528. */
  90529. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  90530. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  90531. };
  90532. /**
  90533. * Scale the bone on the x, y and z axes (in local space)
  90534. * @param x The amount to scale the bone on the x axis
  90535. * @param y The amount to scale the bone on the y axis
  90536. * @param z The amount to scale the bone on the z axis
  90537. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  90538. */
  90539. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  90540. if (scaleChildren === void 0) { scaleChildren = false; }
  90541. var locMat = this.getLocalMatrix();
  90542. // Apply new scaling on top of current local matrix
  90543. var scaleMat = Bone._tmpMats[0];
  90544. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  90545. scaleMat.multiplyToRef(locMat, locMat);
  90546. // Invert scaling matrix and apply the inverse to all children
  90547. scaleMat.invert();
  90548. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  90549. var child = _a[_i];
  90550. var cm = child.getLocalMatrix();
  90551. cm.multiplyToRef(scaleMat, cm);
  90552. cm.m[12] *= x;
  90553. cm.m[13] *= y;
  90554. cm.m[14] *= z;
  90555. child._markAsDirtyAndDecompose();
  90556. }
  90557. this._markAsDirtyAndDecompose();
  90558. if (scaleChildren) {
  90559. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  90560. var child = _c[_b];
  90561. child.scale(x, y, z, scaleChildren);
  90562. }
  90563. }
  90564. };
  90565. /**
  90566. * Set the bone scaling in local space
  90567. * @param scale defines the scaling vector
  90568. */
  90569. Bone.prototype.setScale = function (scale) {
  90570. this._decompose();
  90571. this._localScaling.copyFrom(scale);
  90572. this._markAsDirtyAndCompose();
  90573. };
  90574. /**
  90575. * Gets the current scaling in local space
  90576. * @returns the current scaling vector
  90577. */
  90578. Bone.prototype.getScale = function () {
  90579. this._decompose();
  90580. return this._localScaling;
  90581. };
  90582. /**
  90583. * Gets the current scaling in local space and stores it in a target vector
  90584. * @param result defines the target vector
  90585. */
  90586. Bone.prototype.getScaleToRef = function (result) {
  90587. this._decompose();
  90588. result.copyFrom(this._localScaling);
  90589. };
  90590. /**
  90591. * Set the yaw, pitch, and roll of the bone in local or world space
  90592. * @param yaw The rotation of the bone on the y axis
  90593. * @param pitch The rotation of the bone on the x axis
  90594. * @param roll The rotation of the bone on the z axis
  90595. * @param space The space that the axes of rotation are in
  90596. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90597. */
  90598. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  90599. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90600. if (space === BABYLON.Space.LOCAL) {
  90601. var quat = Bone._tmpQuat;
  90602. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  90603. this.setRotationQuaternion(quat, space, mesh);
  90604. return;
  90605. }
  90606. var rotMatInv = Bone._tmpMats[0];
  90607. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90608. return;
  90609. }
  90610. var rotMat = Bone._tmpMats[1];
  90611. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  90612. rotMatInv.multiplyToRef(rotMat, rotMat);
  90613. this._rotateWithMatrix(rotMat, space, mesh);
  90614. };
  90615. /**
  90616. * Add a rotation to the bone on an axis in local or world space
  90617. * @param axis The axis to rotate the bone on
  90618. * @param amount The amount to rotate the bone
  90619. * @param space The space that the axis is in
  90620. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90621. */
  90622. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  90623. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90624. var rmat = Bone._tmpMats[0];
  90625. rmat.m[12] = 0;
  90626. rmat.m[13] = 0;
  90627. rmat.m[14] = 0;
  90628. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  90629. this._rotateWithMatrix(rmat, space, mesh);
  90630. };
  90631. /**
  90632. * Set the rotation of the bone to a particular axis angle in local or world space
  90633. * @param axis The axis to rotate the bone on
  90634. * @param angle The angle that the bone should be rotated to
  90635. * @param space The space that the axis is in
  90636. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90637. */
  90638. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  90639. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90640. if (space === BABYLON.Space.LOCAL) {
  90641. var quat = Bone._tmpQuat;
  90642. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  90643. this.setRotationQuaternion(quat, space, mesh);
  90644. return;
  90645. }
  90646. var rotMatInv = Bone._tmpMats[0];
  90647. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90648. return;
  90649. }
  90650. var rotMat = Bone._tmpMats[1];
  90651. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  90652. rotMatInv.multiplyToRef(rotMat, rotMat);
  90653. this._rotateWithMatrix(rotMat, space, mesh);
  90654. };
  90655. /**
  90656. * Set the euler rotation of the bone in local of world space
  90657. * @param rotation The euler rotation that the bone should be set to
  90658. * @param space The space that the rotation is in
  90659. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90660. */
  90661. Bone.prototype.setRotation = function (rotation, space, mesh) {
  90662. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90663. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  90664. };
  90665. /**
  90666. * Set the quaternion rotation of the bone in local of world space
  90667. * @param quat The quaternion rotation that the bone should be set to
  90668. * @param space The space that the rotation is in
  90669. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90670. */
  90671. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  90672. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90673. if (space === BABYLON.Space.LOCAL) {
  90674. this._decompose();
  90675. this._localRotation.copyFrom(quat);
  90676. this._markAsDirtyAndCompose();
  90677. return;
  90678. }
  90679. var rotMatInv = Bone._tmpMats[0];
  90680. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90681. return;
  90682. }
  90683. var rotMat = Bone._tmpMats[1];
  90684. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  90685. rotMatInv.multiplyToRef(rotMat, rotMat);
  90686. this._rotateWithMatrix(rotMat, space, mesh);
  90687. };
  90688. /**
  90689. * Set the rotation matrix of the bone in local of world space
  90690. * @param rotMat The rotation matrix that the bone should be set to
  90691. * @param space The space that the rotation is in
  90692. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90693. */
  90694. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  90695. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90696. if (space === BABYLON.Space.LOCAL) {
  90697. var quat = Bone._tmpQuat;
  90698. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  90699. this.setRotationQuaternion(quat, space, mesh);
  90700. return;
  90701. }
  90702. var rotMatInv = Bone._tmpMats[0];
  90703. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90704. return;
  90705. }
  90706. var rotMat2 = Bone._tmpMats[1];
  90707. rotMat2.copyFrom(rotMat);
  90708. rotMatInv.multiplyToRef(rotMat, rotMat2);
  90709. this._rotateWithMatrix(rotMat2, space, mesh);
  90710. };
  90711. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  90712. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90713. var lmat = this.getLocalMatrix();
  90714. var lx = lmat.m[12];
  90715. var ly = lmat.m[13];
  90716. var lz = lmat.m[14];
  90717. var parent = this.getParent();
  90718. var parentScale = Bone._tmpMats[3];
  90719. var parentScaleInv = Bone._tmpMats[4];
  90720. if (parent && space == BABYLON.Space.WORLD) {
  90721. if (mesh) {
  90722. parentScale.copyFrom(mesh.getWorldMatrix());
  90723. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  90724. }
  90725. else {
  90726. parentScale.copyFrom(parent.getAbsoluteTransform());
  90727. }
  90728. parentScaleInv.copyFrom(parentScale);
  90729. parentScaleInv.invert();
  90730. lmat.multiplyToRef(parentScale, lmat);
  90731. lmat.multiplyToRef(rmat, lmat);
  90732. lmat.multiplyToRef(parentScaleInv, lmat);
  90733. }
  90734. else {
  90735. if (space == BABYLON.Space.WORLD && mesh) {
  90736. parentScale.copyFrom(mesh.getWorldMatrix());
  90737. parentScaleInv.copyFrom(parentScale);
  90738. parentScaleInv.invert();
  90739. lmat.multiplyToRef(parentScale, lmat);
  90740. lmat.multiplyToRef(rmat, lmat);
  90741. lmat.multiplyToRef(parentScaleInv, lmat);
  90742. }
  90743. else {
  90744. lmat.multiplyToRef(rmat, lmat);
  90745. }
  90746. }
  90747. lmat.m[12] = lx;
  90748. lmat.m[13] = ly;
  90749. lmat.m[14] = lz;
  90750. this.computeAbsoluteTransforms();
  90751. this._markAsDirtyAndDecompose();
  90752. };
  90753. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  90754. var scaleMatrix = Bone._tmpMats[2];
  90755. rotMatInv.copyFrom(this.getAbsoluteTransform());
  90756. if (mesh) {
  90757. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  90758. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  90759. }
  90760. rotMatInv.invert();
  90761. if (isNaN(rotMatInv.m[0])) {
  90762. // Matrix failed to invert.
  90763. // This can happen if scale is zero for example.
  90764. return false;
  90765. }
  90766. scaleMatrix.m[0] *= this._scalingDeterminant;
  90767. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  90768. return true;
  90769. };
  90770. /**
  90771. * Get the position of the bone in local or world space
  90772. * @param space The space that the returned position is in
  90773. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90774. * @returns The position of the bone
  90775. */
  90776. Bone.prototype.getPosition = function (space, mesh) {
  90777. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90778. if (mesh === void 0) { mesh = null; }
  90779. var pos = BABYLON.Vector3.Zero();
  90780. this.getPositionToRef(space, mesh, pos);
  90781. return pos;
  90782. };
  90783. /**
  90784. * Copy the position of the bone to a vector3 in local or world space
  90785. * @param space The space that the returned position is in
  90786. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90787. * @param result The vector3 to copy the position to
  90788. */
  90789. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  90790. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90791. if (space == BABYLON.Space.LOCAL) {
  90792. var lm = this.getLocalMatrix();
  90793. result.x = lm.m[12];
  90794. result.y = lm.m[13];
  90795. result.z = lm.m[14];
  90796. }
  90797. else {
  90798. var wm = null;
  90799. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90800. if (mesh) {
  90801. wm = mesh.getWorldMatrix();
  90802. }
  90803. this._skeleton.computeAbsoluteTransforms();
  90804. var tmat = Bone._tmpMats[0];
  90805. if (mesh && wm) {
  90806. tmat.copyFrom(this.getAbsoluteTransform());
  90807. tmat.multiplyToRef(wm, tmat);
  90808. }
  90809. else {
  90810. tmat = this.getAbsoluteTransform();
  90811. }
  90812. result.x = tmat.m[12];
  90813. result.y = tmat.m[13];
  90814. result.z = tmat.m[14];
  90815. }
  90816. };
  90817. /**
  90818. * Get the absolute position of the bone (world space)
  90819. * @param mesh The mesh that this bone is attached to
  90820. * @returns The absolute position of the bone
  90821. */
  90822. Bone.prototype.getAbsolutePosition = function (mesh) {
  90823. if (mesh === void 0) { mesh = null; }
  90824. var pos = BABYLON.Vector3.Zero();
  90825. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  90826. return pos;
  90827. };
  90828. /**
  90829. * Copy the absolute position of the bone (world space) to the result param
  90830. * @param mesh The mesh that this bone is attached to
  90831. * @param result The vector3 to copy the absolute position to
  90832. */
  90833. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  90834. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  90835. };
  90836. /**
  90837. * Compute the absolute transforms of this bone and its children
  90838. */
  90839. Bone.prototype.computeAbsoluteTransforms = function () {
  90840. this._compose();
  90841. if (this._parent) {
  90842. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  90843. }
  90844. else {
  90845. this._absoluteTransform.copyFrom(this._localMatrix);
  90846. var poseMatrix = this._skeleton.getPoseMatrix();
  90847. if (poseMatrix) {
  90848. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  90849. }
  90850. }
  90851. var children = this.children;
  90852. var len = children.length;
  90853. for (var i = 0; i < len; i++) {
  90854. children[i].computeAbsoluteTransforms();
  90855. }
  90856. };
  90857. /**
  90858. * Get the world direction from an axis that is in the local space of the bone
  90859. * @param localAxis The local direction that is used to compute the world direction
  90860. * @param mesh The mesh that this bone is attached to
  90861. * @returns The world direction
  90862. */
  90863. Bone.prototype.getDirection = function (localAxis, mesh) {
  90864. if (mesh === void 0) { mesh = null; }
  90865. var result = BABYLON.Vector3.Zero();
  90866. this.getDirectionToRef(localAxis, mesh, result);
  90867. return result;
  90868. };
  90869. /**
  90870. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  90871. * @param localAxis The local direction that is used to compute the world direction
  90872. * @param mesh The mesh that this bone is attached to
  90873. * @param result The vector3 that the world direction will be copied to
  90874. */
  90875. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  90876. if (mesh === void 0) { mesh = null; }
  90877. var wm = null;
  90878. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90879. if (mesh) {
  90880. wm = mesh.getWorldMatrix();
  90881. }
  90882. this._skeleton.computeAbsoluteTransforms();
  90883. var mat = Bone._tmpMats[0];
  90884. mat.copyFrom(this.getAbsoluteTransform());
  90885. if (mesh && wm) {
  90886. mat.multiplyToRef(wm, mat);
  90887. }
  90888. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  90889. result.normalize();
  90890. };
  90891. /**
  90892. * Get the euler rotation of the bone in local or world space
  90893. * @param space The space that the rotation should be in
  90894. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90895. * @returns The euler rotation
  90896. */
  90897. Bone.prototype.getRotation = function (space, mesh) {
  90898. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90899. if (mesh === void 0) { mesh = null; }
  90900. var result = BABYLON.Vector3.Zero();
  90901. this.getRotationToRef(space, mesh, result);
  90902. return result;
  90903. };
  90904. /**
  90905. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  90906. * @param space The space that the rotation should be in
  90907. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90908. * @param result The vector3 that the rotation should be copied to
  90909. */
  90910. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  90911. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90912. if (mesh === void 0) { mesh = null; }
  90913. var quat = Bone._tmpQuat;
  90914. this.getRotationQuaternionToRef(space, mesh, quat);
  90915. quat.toEulerAnglesToRef(result);
  90916. };
  90917. /**
  90918. * Get the quaternion rotation of the bone in either local or world space
  90919. * @param space The space that the rotation should be in
  90920. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90921. * @returns The quaternion rotation
  90922. */
  90923. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  90924. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90925. if (mesh === void 0) { mesh = null; }
  90926. var result = BABYLON.Quaternion.Identity();
  90927. this.getRotationQuaternionToRef(space, mesh, result);
  90928. return result;
  90929. };
  90930. /**
  90931. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  90932. * @param space The space that the rotation should be in
  90933. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90934. * @param result The quaternion that the rotation should be copied to
  90935. */
  90936. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  90937. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90938. if (mesh === void 0) { mesh = null; }
  90939. if (space == BABYLON.Space.LOCAL) {
  90940. this._decompose();
  90941. result.copyFrom(this._localRotation);
  90942. }
  90943. else {
  90944. var mat = Bone._tmpMats[0];
  90945. var amat = this.getAbsoluteTransform();
  90946. if (mesh) {
  90947. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  90948. }
  90949. else {
  90950. mat.copyFrom(amat);
  90951. }
  90952. mat.m[0] *= this._scalingDeterminant;
  90953. mat.m[1] *= this._scalingDeterminant;
  90954. mat.m[2] *= this._scalingDeterminant;
  90955. mat.decompose(undefined, result, undefined);
  90956. }
  90957. };
  90958. /**
  90959. * Get the rotation matrix of the bone in local or world space
  90960. * @param space The space that the rotation should be in
  90961. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90962. * @returns The rotation matrix
  90963. */
  90964. Bone.prototype.getRotationMatrix = function (space, mesh) {
  90965. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90966. var result = BABYLON.Matrix.Identity();
  90967. this.getRotationMatrixToRef(space, mesh, result);
  90968. return result;
  90969. };
  90970. /**
  90971. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  90972. * @param space The space that the rotation should be in
  90973. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90974. * @param result The quaternion that the rotation should be copied to
  90975. */
  90976. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  90977. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90978. if (space == BABYLON.Space.LOCAL) {
  90979. this.getLocalMatrix().getRotationMatrixToRef(result);
  90980. }
  90981. else {
  90982. var mat = Bone._tmpMats[0];
  90983. var amat = this.getAbsoluteTransform();
  90984. if (mesh) {
  90985. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  90986. }
  90987. else {
  90988. mat.copyFrom(amat);
  90989. }
  90990. mat.m[0] *= this._scalingDeterminant;
  90991. mat.m[1] *= this._scalingDeterminant;
  90992. mat.m[2] *= this._scalingDeterminant;
  90993. mat.getRotationMatrixToRef(result);
  90994. }
  90995. };
  90996. /**
  90997. * Get the world position of a point that is in the local space of the bone
  90998. * @param position The local position
  90999. * @param mesh The mesh that this bone is attached to
  91000. * @returns The world position
  91001. */
  91002. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  91003. if (mesh === void 0) { mesh = null; }
  91004. var result = BABYLON.Vector3.Zero();
  91005. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  91006. return result;
  91007. };
  91008. /**
  91009. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  91010. * @param position The local position
  91011. * @param mesh The mesh that this bone is attached to
  91012. * @param result The vector3 that the world position should be copied to
  91013. */
  91014. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  91015. if (mesh === void 0) { mesh = null; }
  91016. var wm = null;
  91017. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  91018. if (mesh) {
  91019. wm = mesh.getWorldMatrix();
  91020. }
  91021. this._skeleton.computeAbsoluteTransforms();
  91022. var tmat = Bone._tmpMats[0];
  91023. if (mesh && wm) {
  91024. tmat.copyFrom(this.getAbsoluteTransform());
  91025. tmat.multiplyToRef(wm, tmat);
  91026. }
  91027. else {
  91028. tmat = this.getAbsoluteTransform();
  91029. }
  91030. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  91031. };
  91032. /**
  91033. * Get the local position of a point that is in world space
  91034. * @param position The world position
  91035. * @param mesh The mesh that this bone is attached to
  91036. * @returns The local position
  91037. */
  91038. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  91039. if (mesh === void 0) { mesh = null; }
  91040. var result = BABYLON.Vector3.Zero();
  91041. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  91042. return result;
  91043. };
  91044. /**
  91045. * Get the local position of a point that is in world space and copy it to the result param
  91046. * @param position The world position
  91047. * @param mesh The mesh that this bone is attached to
  91048. * @param result The vector3 that the local position should be copied to
  91049. */
  91050. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  91051. if (mesh === void 0) { mesh = null; }
  91052. var wm = null;
  91053. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  91054. if (mesh) {
  91055. wm = mesh.getWorldMatrix();
  91056. }
  91057. this._skeleton.computeAbsoluteTransforms();
  91058. var tmat = Bone._tmpMats[0];
  91059. tmat.copyFrom(this.getAbsoluteTransform());
  91060. if (mesh && wm) {
  91061. tmat.multiplyToRef(wm, tmat);
  91062. }
  91063. tmat.invert();
  91064. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  91065. };
  91066. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  91067. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  91068. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  91069. return Bone;
  91070. }(BABYLON.Node));
  91071. BABYLON.Bone = Bone;
  91072. })(BABYLON || (BABYLON = {}));
  91073. //# sourceMappingURL=babylon.bone.js.map
  91074. var BABYLON;
  91075. (function (BABYLON) {
  91076. /**
  91077. * Class used to apply inverse kinematics to bones
  91078. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  91079. */
  91080. var BoneIKController = /** @class */ (function () {
  91081. /**
  91082. * Creates a new BoneIKController
  91083. * @param mesh defines the mesh to control
  91084. * @param bone defines the bone to control
  91085. * @param options defines options to set up the controller
  91086. */
  91087. function BoneIKController(mesh, bone, options) {
  91088. /**
  91089. * Gets or sets the target position
  91090. */
  91091. this.targetPosition = BABYLON.Vector3.Zero();
  91092. /**
  91093. * Gets or sets the pole target position
  91094. */
  91095. this.poleTargetPosition = BABYLON.Vector3.Zero();
  91096. /**
  91097. * Gets or sets the pole target local offset
  91098. */
  91099. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  91100. /**
  91101. * Gets or sets the pole angle
  91102. */
  91103. this.poleAngle = 0;
  91104. /**
  91105. * 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)
  91106. */
  91107. this.slerpAmount = 1;
  91108. this._bone1Quat = BABYLON.Quaternion.Identity();
  91109. this._bone1Mat = BABYLON.Matrix.Identity();
  91110. this._bone2Ang = Math.PI;
  91111. this._maxAngle = Math.PI;
  91112. this._rightHandedSystem = false;
  91113. this._bendAxis = BABYLON.Vector3.Right();
  91114. this._slerping = false;
  91115. this._adjustRoll = 0;
  91116. this._bone2 = bone;
  91117. this._bone1 = bone.getParent();
  91118. if (!this._bone1) {
  91119. return;
  91120. }
  91121. this.mesh = mesh;
  91122. var bonePos = bone.getPosition();
  91123. if (bone.getAbsoluteTransform().determinant() > 0) {
  91124. this._rightHandedSystem = true;
  91125. this._bendAxis.x = 0;
  91126. this._bendAxis.y = 0;
  91127. this._bendAxis.z = -1;
  91128. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  91129. this._adjustRoll = Math.PI * .5;
  91130. this._bendAxis.z = 1;
  91131. }
  91132. }
  91133. if (this._bone1.length) {
  91134. var boneScale1 = this._bone1.getScale();
  91135. var boneScale2 = this._bone2.getScale();
  91136. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  91137. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  91138. }
  91139. else if (this._bone1.children[0]) {
  91140. mesh.computeWorldMatrix(true);
  91141. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  91142. var pos2 = this._bone2.getAbsolutePosition(mesh);
  91143. var pos3 = this._bone1.getAbsolutePosition(mesh);
  91144. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  91145. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  91146. }
  91147. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  91148. this.maxAngle = Math.PI;
  91149. if (options) {
  91150. if (options.targetMesh) {
  91151. this.targetMesh = options.targetMesh;
  91152. this.targetMesh.computeWorldMatrix(true);
  91153. }
  91154. if (options.poleTargetMesh) {
  91155. this.poleTargetMesh = options.poleTargetMesh;
  91156. this.poleTargetMesh.computeWorldMatrix(true);
  91157. }
  91158. else if (options.poleTargetBone) {
  91159. this.poleTargetBone = options.poleTargetBone;
  91160. }
  91161. else if (this._bone1.getParent()) {
  91162. this.poleTargetBone = this._bone1.getParent();
  91163. }
  91164. if (options.poleTargetLocalOffset) {
  91165. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  91166. }
  91167. if (options.poleAngle) {
  91168. this.poleAngle = options.poleAngle;
  91169. }
  91170. if (options.bendAxis) {
  91171. this._bendAxis.copyFrom(options.bendAxis);
  91172. }
  91173. if (options.maxAngle) {
  91174. this.maxAngle = options.maxAngle;
  91175. }
  91176. if (options.slerpAmount) {
  91177. this.slerpAmount = options.slerpAmount;
  91178. }
  91179. }
  91180. }
  91181. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  91182. /**
  91183. * Gets or sets maximum allowed angle
  91184. */
  91185. get: function () {
  91186. return this._maxAngle;
  91187. },
  91188. set: function (value) {
  91189. this._setMaxAngle(value);
  91190. },
  91191. enumerable: true,
  91192. configurable: true
  91193. });
  91194. BoneIKController.prototype._setMaxAngle = function (ang) {
  91195. if (ang < 0) {
  91196. ang = 0;
  91197. }
  91198. if (ang > Math.PI || ang == undefined) {
  91199. ang = Math.PI;
  91200. }
  91201. this._maxAngle = ang;
  91202. var a = this._bone1Length;
  91203. var b = this._bone2Length;
  91204. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  91205. };
  91206. /**
  91207. * Force the controller to update the bones
  91208. */
  91209. BoneIKController.prototype.update = function () {
  91210. var bone1 = this._bone1;
  91211. if (!bone1) {
  91212. return;
  91213. }
  91214. var target = this.targetPosition;
  91215. var poleTarget = this.poleTargetPosition;
  91216. var mat1 = BoneIKController._tmpMats[0];
  91217. var mat2 = BoneIKController._tmpMats[1];
  91218. if (this.targetMesh) {
  91219. target.copyFrom(this.targetMesh.getAbsolutePosition());
  91220. }
  91221. if (this.poleTargetBone) {
  91222. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  91223. }
  91224. else if (this.poleTargetMesh) {
  91225. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  91226. }
  91227. var bonePos = BoneIKController._tmpVecs[0];
  91228. var zaxis = BoneIKController._tmpVecs[1];
  91229. var xaxis = BoneIKController._tmpVecs[2];
  91230. var yaxis = BoneIKController._tmpVecs[3];
  91231. var upAxis = BoneIKController._tmpVecs[4];
  91232. var _tmpQuat = BoneIKController._tmpQuat;
  91233. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  91234. poleTarget.subtractToRef(bonePos, upAxis);
  91235. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  91236. upAxis.y = 1;
  91237. }
  91238. else {
  91239. upAxis.normalize();
  91240. }
  91241. target.subtractToRef(bonePos, yaxis);
  91242. yaxis.normalize();
  91243. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  91244. zaxis.normalize();
  91245. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  91246. xaxis.normalize();
  91247. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  91248. var a = this._bone1Length;
  91249. var b = this._bone2Length;
  91250. var c = BABYLON.Vector3.Distance(bonePos, target);
  91251. if (this._maxReach > 0) {
  91252. c = Math.min(this._maxReach, c);
  91253. }
  91254. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  91255. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  91256. if (acosa > 1) {
  91257. acosa = 1;
  91258. }
  91259. if (acosb > 1) {
  91260. acosb = 1;
  91261. }
  91262. if (acosa < -1) {
  91263. acosa = -1;
  91264. }
  91265. if (acosb < -1) {
  91266. acosb = -1;
  91267. }
  91268. var angA = Math.acos(acosa);
  91269. var angB = Math.acos(acosb);
  91270. var angC = -angA - angB;
  91271. if (this._rightHandedSystem) {
  91272. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  91273. mat2.multiplyToRef(mat1, mat1);
  91274. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  91275. mat2.multiplyToRef(mat1, mat1);
  91276. }
  91277. else {
  91278. var _tmpVec = BoneIKController._tmpVecs[5];
  91279. _tmpVec.copyFrom(this._bendAxis);
  91280. _tmpVec.x *= -1;
  91281. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  91282. mat2.multiplyToRef(mat1, mat1);
  91283. }
  91284. if (this.poleAngle) {
  91285. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  91286. mat1.multiplyToRef(mat2, mat1);
  91287. }
  91288. if (this._bone1) {
  91289. if (this.slerpAmount < 1) {
  91290. if (!this._slerping) {
  91291. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  91292. }
  91293. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  91294. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  91295. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  91296. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  91297. this._slerping = true;
  91298. }
  91299. else {
  91300. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  91301. this._bone1Mat.copyFrom(mat1);
  91302. this._slerping = false;
  91303. }
  91304. }
  91305. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  91306. this._bone2Ang = angC;
  91307. };
  91308. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  91309. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  91310. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  91311. return BoneIKController;
  91312. }());
  91313. BABYLON.BoneIKController = BoneIKController;
  91314. })(BABYLON || (BABYLON = {}));
  91315. //# sourceMappingURL=babylon.boneIKController.js.map
  91316. var BABYLON;
  91317. (function (BABYLON) {
  91318. /**
  91319. * Class used to make a bone look toward a point in space
  91320. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  91321. */
  91322. var BoneLookController = /** @class */ (function () {
  91323. /**
  91324. * Create a BoneLookController
  91325. * @param mesh the mesh that the bone belongs to
  91326. * @param bone the bone that will be looking to the target
  91327. * @param target the target Vector3 to look at
  91328. * @param settings optional settings:
  91329. * * maxYaw: the maximum angle the bone will yaw to
  91330. * * minYaw: the minimum angle the bone will yaw to
  91331. * * maxPitch: the maximum angle the bone will pitch to
  91332. * * minPitch: the minimum angle the bone will yaw to
  91333. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  91334. * * upAxis: the up axis of the coordinate system
  91335. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  91336. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  91337. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  91338. * * adjustYaw: used to make an adjustment to the yaw of the bone
  91339. * * adjustPitch: used to make an adjustment to the pitch of the bone
  91340. * * adjustRoll: used to make an adjustment to the roll of the bone
  91341. **/
  91342. function BoneLookController(mesh, bone, target, options) {
  91343. /**
  91344. * The up axis of the coordinate system that is used when the bone is rotated
  91345. */
  91346. this.upAxis = BABYLON.Vector3.Up();
  91347. /**
  91348. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  91349. */
  91350. this.upAxisSpace = BABYLON.Space.LOCAL;
  91351. /**
  91352. * Used to make an adjustment to the yaw of the bone
  91353. */
  91354. this.adjustYaw = 0;
  91355. /**
  91356. * Used to make an adjustment to the pitch of the bone
  91357. */
  91358. this.adjustPitch = 0;
  91359. /**
  91360. * Used to make an adjustment to the roll of the bone
  91361. */
  91362. this.adjustRoll = 0;
  91363. /**
  91364. * 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)
  91365. */
  91366. this.slerpAmount = 1;
  91367. this._boneQuat = BABYLON.Quaternion.Identity();
  91368. this._slerping = false;
  91369. this._firstFrameSkipped = false;
  91370. this._fowardAxis = BABYLON.Vector3.Forward();
  91371. this.mesh = mesh;
  91372. this.bone = bone;
  91373. this.target = target;
  91374. if (options) {
  91375. if (options.adjustYaw) {
  91376. this.adjustYaw = options.adjustYaw;
  91377. }
  91378. if (options.adjustPitch) {
  91379. this.adjustPitch = options.adjustPitch;
  91380. }
  91381. if (options.adjustRoll) {
  91382. this.adjustRoll = options.adjustRoll;
  91383. }
  91384. if (options.maxYaw != null) {
  91385. this.maxYaw = options.maxYaw;
  91386. }
  91387. else {
  91388. this.maxYaw = Math.PI;
  91389. }
  91390. if (options.minYaw != null) {
  91391. this.minYaw = options.minYaw;
  91392. }
  91393. else {
  91394. this.minYaw = -Math.PI;
  91395. }
  91396. if (options.maxPitch != null) {
  91397. this.maxPitch = options.maxPitch;
  91398. }
  91399. else {
  91400. this.maxPitch = Math.PI;
  91401. }
  91402. if (options.minPitch != null) {
  91403. this.minPitch = options.minPitch;
  91404. }
  91405. else {
  91406. this.minPitch = -Math.PI;
  91407. }
  91408. if (options.slerpAmount != null) {
  91409. this.slerpAmount = options.slerpAmount;
  91410. }
  91411. if (options.upAxis != null) {
  91412. this.upAxis = options.upAxis;
  91413. }
  91414. if (options.upAxisSpace != null) {
  91415. this.upAxisSpace = options.upAxisSpace;
  91416. }
  91417. if (options.yawAxis != null || options.pitchAxis != null) {
  91418. var newYawAxis = BABYLON.Axis.Y;
  91419. var newPitchAxis = BABYLON.Axis.X;
  91420. if (options.yawAxis != null) {
  91421. newYawAxis = options.yawAxis.clone();
  91422. newYawAxis.normalize();
  91423. }
  91424. if (options.pitchAxis != null) {
  91425. newPitchAxis = options.pitchAxis.clone();
  91426. newPitchAxis.normalize();
  91427. }
  91428. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  91429. this._transformYawPitch = BABYLON.Matrix.Identity();
  91430. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  91431. this._transformYawPitchInv = this._transformYawPitch.clone();
  91432. this._transformYawPitch.invert();
  91433. }
  91434. }
  91435. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  91436. this.upAxisSpace = BABYLON.Space.LOCAL;
  91437. }
  91438. }
  91439. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  91440. /**
  91441. * Gets or sets the minimum yaw angle that the bone can look to
  91442. */
  91443. get: function () {
  91444. return this._minYaw;
  91445. },
  91446. set: function (value) {
  91447. this._minYaw = value;
  91448. this._minYawSin = Math.sin(value);
  91449. this._minYawCos = Math.cos(value);
  91450. if (this._maxYaw != null) {
  91451. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  91452. this._yawRange = this._maxYaw - this._minYaw;
  91453. }
  91454. },
  91455. enumerable: true,
  91456. configurable: true
  91457. });
  91458. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  91459. /**
  91460. * Gets or sets the maximum yaw angle that the bone can look to
  91461. */
  91462. get: function () {
  91463. return this._maxYaw;
  91464. },
  91465. set: function (value) {
  91466. this._maxYaw = value;
  91467. this._maxYawSin = Math.sin(value);
  91468. this._maxYawCos = Math.cos(value);
  91469. if (this._minYaw != null) {
  91470. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  91471. this._yawRange = this._maxYaw - this._minYaw;
  91472. }
  91473. },
  91474. enumerable: true,
  91475. configurable: true
  91476. });
  91477. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  91478. /**
  91479. * Gets or sets the minimum pitch angle that the bone can look to
  91480. */
  91481. get: function () {
  91482. return this._minPitch;
  91483. },
  91484. set: function (value) {
  91485. this._minPitch = value;
  91486. this._minPitchTan = Math.tan(value);
  91487. },
  91488. enumerable: true,
  91489. configurable: true
  91490. });
  91491. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  91492. /**
  91493. * Gets or sets the maximum pitch angle that the bone can look to
  91494. */
  91495. get: function () {
  91496. return this._maxPitch;
  91497. },
  91498. set: function (value) {
  91499. this._maxPitch = value;
  91500. this._maxPitchTan = Math.tan(value);
  91501. },
  91502. enumerable: true,
  91503. configurable: true
  91504. });
  91505. /**
  91506. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  91507. */
  91508. BoneLookController.prototype.update = function () {
  91509. //skip the first frame when slerping so that the mesh rotation is correct
  91510. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  91511. this._firstFrameSkipped = true;
  91512. return;
  91513. }
  91514. var bone = this.bone;
  91515. var bonePos = BoneLookController._tmpVecs[0];
  91516. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  91517. var target = this.target;
  91518. var _tmpMat1 = BoneLookController._tmpMats[0];
  91519. var _tmpMat2 = BoneLookController._tmpMats[1];
  91520. var mesh = this.mesh;
  91521. var parentBone = bone.getParent();
  91522. var upAxis = BoneLookController._tmpVecs[1];
  91523. upAxis.copyFrom(this.upAxis);
  91524. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  91525. if (this._transformYawPitch) {
  91526. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  91527. }
  91528. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  91529. }
  91530. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  91531. mesh.getDirectionToRef(upAxis, upAxis);
  91532. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  91533. upAxis.normalize();
  91534. }
  91535. }
  91536. var checkYaw = false;
  91537. var checkPitch = false;
  91538. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  91539. checkYaw = true;
  91540. }
  91541. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  91542. checkPitch = true;
  91543. }
  91544. if (checkYaw || checkPitch) {
  91545. var spaceMat = BoneLookController._tmpMats[2];
  91546. var spaceMatInv = BoneLookController._tmpMats[3];
  91547. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  91548. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  91549. }
  91550. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  91551. spaceMat.copyFrom(mesh.getWorldMatrix());
  91552. }
  91553. else {
  91554. var forwardAxis = BoneLookController._tmpVecs[2];
  91555. forwardAxis.copyFrom(this._fowardAxis);
  91556. if (this._transformYawPitch) {
  91557. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  91558. }
  91559. if (parentBone) {
  91560. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  91561. }
  91562. else {
  91563. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  91564. }
  91565. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  91566. rightAxis.normalize();
  91567. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  91568. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  91569. }
  91570. spaceMat.invertToRef(spaceMatInv);
  91571. var xzlen = null;
  91572. if (checkPitch) {
  91573. var localTarget = BoneLookController._tmpVecs[3];
  91574. target.subtractToRef(bonePos, localTarget);
  91575. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  91576. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  91577. var pitch = Math.atan2(localTarget.y, xzlen);
  91578. var newPitch = pitch;
  91579. if (pitch > this._maxPitch) {
  91580. localTarget.y = this._maxPitchTan * xzlen;
  91581. newPitch = this._maxPitch;
  91582. }
  91583. else if (pitch < this._minPitch) {
  91584. localTarget.y = this._minPitchTan * xzlen;
  91585. newPitch = this._minPitch;
  91586. }
  91587. if (pitch != newPitch) {
  91588. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  91589. localTarget.addInPlace(bonePos);
  91590. target = localTarget;
  91591. }
  91592. }
  91593. if (checkYaw) {
  91594. var localTarget = BoneLookController._tmpVecs[4];
  91595. target.subtractToRef(bonePos, localTarget);
  91596. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  91597. var yaw = Math.atan2(localTarget.x, localTarget.z);
  91598. var newYaw = yaw;
  91599. if (yaw > this._maxYaw || yaw < this._minYaw) {
  91600. if (xzlen == null) {
  91601. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  91602. }
  91603. if (this._yawRange > Math.PI) {
  91604. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  91605. localTarget.z = this._maxYawCos * xzlen;
  91606. localTarget.x = this._maxYawSin * xzlen;
  91607. newYaw = this._maxYaw;
  91608. }
  91609. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  91610. localTarget.z = this._minYawCos * xzlen;
  91611. localTarget.x = this._minYawSin * xzlen;
  91612. newYaw = this._minYaw;
  91613. }
  91614. }
  91615. else {
  91616. if (yaw > this._maxYaw) {
  91617. localTarget.z = this._maxYawCos * xzlen;
  91618. localTarget.x = this._maxYawSin * xzlen;
  91619. newYaw = this._maxYaw;
  91620. }
  91621. else if (yaw < this._minYaw) {
  91622. localTarget.z = this._minYawCos * xzlen;
  91623. localTarget.x = this._minYawSin * xzlen;
  91624. newYaw = this._minYaw;
  91625. }
  91626. }
  91627. }
  91628. if (this._slerping && this._yawRange > Math.PI) {
  91629. //are we going to be crossing into the min/max region?
  91630. var boneFwd = BoneLookController._tmpVecs[8];
  91631. boneFwd.copyFrom(BABYLON.Axis.Z);
  91632. if (this._transformYawPitch) {
  91633. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  91634. }
  91635. var boneRotMat = BoneLookController._tmpMats[4];
  91636. this._boneQuat.toRotationMatrix(boneRotMat);
  91637. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  91638. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  91639. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  91640. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  91641. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  91642. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  91643. if (angBtwTar > angBtwMidYaw) {
  91644. if (xzlen == null) {
  91645. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  91646. }
  91647. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  91648. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  91649. if (angBtwMin < angBtwMax) {
  91650. newYaw = boneYaw + Math.PI * .75;
  91651. localTarget.z = Math.cos(newYaw) * xzlen;
  91652. localTarget.x = Math.sin(newYaw) * xzlen;
  91653. }
  91654. else {
  91655. newYaw = boneYaw - Math.PI * .75;
  91656. localTarget.z = Math.cos(newYaw) * xzlen;
  91657. localTarget.x = Math.sin(newYaw) * xzlen;
  91658. }
  91659. }
  91660. }
  91661. if (yaw != newYaw) {
  91662. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  91663. localTarget.addInPlace(bonePos);
  91664. target = localTarget;
  91665. }
  91666. }
  91667. }
  91668. var zaxis = BoneLookController._tmpVecs[5];
  91669. var xaxis = BoneLookController._tmpVecs[6];
  91670. var yaxis = BoneLookController._tmpVecs[7];
  91671. var _tmpQuat = BoneLookController._tmpQuat;
  91672. target.subtractToRef(bonePos, zaxis);
  91673. zaxis.normalize();
  91674. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  91675. xaxis.normalize();
  91676. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  91677. yaxis.normalize();
  91678. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  91679. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  91680. return;
  91681. }
  91682. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  91683. return;
  91684. }
  91685. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  91686. return;
  91687. }
  91688. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  91689. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  91690. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  91691. }
  91692. if (this.slerpAmount < 1) {
  91693. if (!this._slerping) {
  91694. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  91695. }
  91696. if (this._transformYawPitch) {
  91697. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  91698. }
  91699. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  91700. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  91701. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  91702. this._slerping = true;
  91703. }
  91704. else {
  91705. if (this._transformYawPitch) {
  91706. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  91707. }
  91708. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  91709. this._slerping = false;
  91710. }
  91711. };
  91712. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  91713. var angDiff = ang2 - ang1;
  91714. angDiff %= Math.PI * 2;
  91715. if (angDiff > Math.PI) {
  91716. angDiff -= Math.PI * 2;
  91717. }
  91718. else if (angDiff < -Math.PI) {
  91719. angDiff += Math.PI * 2;
  91720. }
  91721. return angDiff;
  91722. };
  91723. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  91724. ang1 %= (2 * Math.PI);
  91725. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  91726. ang2 %= (2 * Math.PI);
  91727. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  91728. var ab = 0;
  91729. if (ang1 < ang2) {
  91730. ab = ang2 - ang1;
  91731. }
  91732. else {
  91733. ab = ang1 - ang2;
  91734. }
  91735. if (ab > Math.PI) {
  91736. ab = Math.PI * 2 - ab;
  91737. }
  91738. return ab;
  91739. };
  91740. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  91741. ang %= (2 * Math.PI);
  91742. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  91743. ang1 %= (2 * Math.PI);
  91744. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  91745. ang2 %= (2 * Math.PI);
  91746. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  91747. if (ang1 < ang2) {
  91748. if (ang > ang1 && ang < ang2) {
  91749. return true;
  91750. }
  91751. }
  91752. else {
  91753. if (ang > ang2 && ang < ang1) {
  91754. return true;
  91755. }
  91756. }
  91757. return false;
  91758. };
  91759. 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()];
  91760. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  91761. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  91762. return BoneLookController;
  91763. }());
  91764. BABYLON.BoneLookController = BoneLookController;
  91765. })(BABYLON || (BABYLON = {}));
  91766. //# sourceMappingURL=babylon.boneLookController.js.map
  91767. var BABYLON;
  91768. (function (BABYLON) {
  91769. /**
  91770. * Class used to handle skinning animations
  91771. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  91772. */
  91773. var Skeleton = /** @class */ (function () {
  91774. /**
  91775. * Creates a new skeleton
  91776. * @param name defines the skeleton name
  91777. * @param id defines the skeleton Id
  91778. * @param scene defines the hosting scene
  91779. */
  91780. function Skeleton(
  91781. /** defines the skeleton name */
  91782. name,
  91783. /** defines the skeleton Id */
  91784. id, scene) {
  91785. this.name = name;
  91786. this.id = id;
  91787. /**
  91788. * Gets the list of child bones
  91789. */
  91790. this.bones = new Array();
  91791. /**
  91792. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  91793. */
  91794. this.needInitialSkinMatrix = false;
  91795. this._isDirty = true;
  91796. this._meshesWithPoseMatrix = new Array();
  91797. this._identity = BABYLON.Matrix.Identity();
  91798. this._ranges = {};
  91799. this._lastAbsoluteTransformsUpdateId = -1;
  91800. /**
  91801. * Specifies if the skeleton should be serialized
  91802. */
  91803. this.doNotSerialize = false;
  91804. this._animationPropertiesOverride = null;
  91805. // Events
  91806. /**
  91807. * An observable triggered before computing the skeleton's matrices
  91808. */
  91809. this.onBeforeComputeObservable = new BABYLON.Observable();
  91810. this.bones = [];
  91811. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91812. scene.skeletons.push(this);
  91813. //make sure it will recalculate the matrix next time prepare is called.
  91814. this._isDirty = true;
  91815. }
  91816. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  91817. /**
  91818. * Gets or sets the animation properties override
  91819. */
  91820. get: function () {
  91821. if (!this._animationPropertiesOverride) {
  91822. return this._scene.animationPropertiesOverride;
  91823. }
  91824. return this._animationPropertiesOverride;
  91825. },
  91826. set: function (value) {
  91827. this._animationPropertiesOverride = value;
  91828. },
  91829. enumerable: true,
  91830. configurable: true
  91831. });
  91832. // Members
  91833. /**
  91834. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  91835. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  91836. * @returns a Float32Array containing matrices data
  91837. */
  91838. Skeleton.prototype.getTransformMatrices = function (mesh) {
  91839. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  91840. return mesh._bonesTransformMatrices;
  91841. }
  91842. if (!this._transformMatrices) {
  91843. this.prepare();
  91844. }
  91845. return this._transformMatrices;
  91846. };
  91847. /**
  91848. * Gets the current hosting scene
  91849. * @returns a scene object
  91850. */
  91851. Skeleton.prototype.getScene = function () {
  91852. return this._scene;
  91853. };
  91854. // Methods
  91855. /**
  91856. * Gets a string representing the current skeleton data
  91857. * @param fullDetails defines a boolean indicating if we want a verbose version
  91858. * @returns a string representing the current skeleton data
  91859. */
  91860. Skeleton.prototype.toString = function (fullDetails) {
  91861. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  91862. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  91863. if (fullDetails) {
  91864. ret += ", Ranges: {";
  91865. var first = true;
  91866. for (var name_1 in this._ranges) {
  91867. if (first) {
  91868. ret += ", ";
  91869. first = false;
  91870. }
  91871. ret += name_1;
  91872. }
  91873. ret += "}";
  91874. }
  91875. return ret;
  91876. };
  91877. /**
  91878. * Get bone's index searching by name
  91879. * @param name defines bone's name to search for
  91880. * @return the indice of the bone. Returns -1 if not found
  91881. */
  91882. Skeleton.prototype.getBoneIndexByName = function (name) {
  91883. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  91884. if (this.bones[boneIndex].name === name) {
  91885. return boneIndex;
  91886. }
  91887. }
  91888. return -1;
  91889. };
  91890. /**
  91891. * Creater a new animation range
  91892. * @param name defines the name of the range
  91893. * @param from defines the start key
  91894. * @param to defines the end key
  91895. */
  91896. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  91897. // check name not already in use
  91898. if (!this._ranges[name]) {
  91899. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  91900. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  91901. if (this.bones[i].animations[0]) {
  91902. this.bones[i].animations[0].createRange(name, from, to);
  91903. }
  91904. }
  91905. }
  91906. };
  91907. /**
  91908. * Delete a specific animation range
  91909. * @param name defines the name of the range
  91910. * @param deleteFrames defines if frames must be removed as well
  91911. */
  91912. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  91913. if (deleteFrames === void 0) { deleteFrames = true; }
  91914. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  91915. if (this.bones[i].animations[0]) {
  91916. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  91917. }
  91918. }
  91919. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  91920. };
  91921. /**
  91922. * Gets a specific animation range
  91923. * @param name defines the name of the range to look for
  91924. * @returns the requested animation range or null if not found
  91925. */
  91926. Skeleton.prototype.getAnimationRange = function (name) {
  91927. return this._ranges[name];
  91928. };
  91929. /**
  91930. * Gets the list of all animation ranges defined on this skeleton
  91931. * @returns an array
  91932. */
  91933. Skeleton.prototype.getAnimationRanges = function () {
  91934. var animationRanges = [];
  91935. var name;
  91936. var i = 0;
  91937. for (name in this._ranges) {
  91938. animationRanges[i] = this._ranges[name];
  91939. i++;
  91940. }
  91941. return animationRanges;
  91942. };
  91943. /**
  91944. * Copy animation range from a source skeleton.
  91945. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  91946. * @param source defines the source skeleton
  91947. * @param name defines the name of the range to copy
  91948. * @param rescaleAsRequired defines if rescaling must be applied if required
  91949. * @returns true if operation was successful
  91950. */
  91951. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  91952. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  91953. if (this._ranges[name] || !source.getAnimationRange(name)) {
  91954. return false;
  91955. }
  91956. var ret = true;
  91957. var frameOffset = this._getHighestAnimationFrame() + 1;
  91958. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  91959. var boneDict = {};
  91960. var sourceBones = source.bones;
  91961. var nBones;
  91962. var i;
  91963. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  91964. boneDict[sourceBones[i].name] = sourceBones[i];
  91965. }
  91966. if (this.bones.length !== sourceBones.length) {
  91967. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  91968. ret = false;
  91969. }
  91970. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  91971. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  91972. var boneName = this.bones[i].name;
  91973. var sourceBone = boneDict[boneName];
  91974. if (sourceBone) {
  91975. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  91976. }
  91977. else {
  91978. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  91979. ret = false;
  91980. }
  91981. }
  91982. // do not call createAnimationRange(), since it also is done to bones, which was already done
  91983. var range = source.getAnimationRange(name);
  91984. if (range) {
  91985. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  91986. }
  91987. return ret;
  91988. };
  91989. /**
  91990. * Forces the skeleton to go to rest pose
  91991. */
  91992. Skeleton.prototype.returnToRest = function () {
  91993. for (var index = 0; index < this.bones.length; index++) {
  91994. this.bones[index].returnToRest();
  91995. }
  91996. };
  91997. Skeleton.prototype._getHighestAnimationFrame = function () {
  91998. var ret = 0;
  91999. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  92000. if (this.bones[i].animations[0]) {
  92001. var highest = this.bones[i].animations[0].getHighestFrame();
  92002. if (ret < highest) {
  92003. ret = highest;
  92004. }
  92005. }
  92006. }
  92007. return ret;
  92008. };
  92009. /**
  92010. * Begin a specific animation range
  92011. * @param name defines the name of the range to start
  92012. * @param loop defines if looping must be turned on (false by default)
  92013. * @param speedRatio defines the speed ratio to apply (1 by default)
  92014. * @param onAnimationEnd defines a callback which will be called when animation will end
  92015. * @returns a new animatable
  92016. */
  92017. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  92018. var range = this.getAnimationRange(name);
  92019. if (!range) {
  92020. return null;
  92021. }
  92022. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  92023. };
  92024. /** @hidden */
  92025. Skeleton.prototype._markAsDirty = function () {
  92026. this._isDirty = true;
  92027. };
  92028. /** @hidden */
  92029. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  92030. this._meshesWithPoseMatrix.push(mesh);
  92031. };
  92032. /** @hidden */
  92033. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  92034. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  92035. if (index > -1) {
  92036. this._meshesWithPoseMatrix.splice(index, 1);
  92037. }
  92038. };
  92039. /** @hidden */
  92040. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  92041. this.onBeforeComputeObservable.notifyObservers(this);
  92042. for (var index = 0; index < this.bones.length; index++) {
  92043. var bone = this.bones[index];
  92044. var parentBone = bone.getParent();
  92045. if (parentBone) {
  92046. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  92047. }
  92048. else {
  92049. if (initialSkinMatrix) {
  92050. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  92051. }
  92052. else {
  92053. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  92054. }
  92055. }
  92056. if (bone._index !== -1) {
  92057. var mappedIndex = bone._index === null ? index : bone._index;
  92058. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  92059. }
  92060. }
  92061. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  92062. };
  92063. /**
  92064. * Build all resources required to render a skeleton
  92065. */
  92066. Skeleton.prototype.prepare = function () {
  92067. if (!this._isDirty) {
  92068. return;
  92069. }
  92070. if (this.needInitialSkinMatrix) {
  92071. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  92072. var mesh = this._meshesWithPoseMatrix[index];
  92073. var poseMatrix = mesh.getPoseMatrix();
  92074. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  92075. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  92076. }
  92077. if (this._synchronizedWithMesh !== mesh) {
  92078. this._synchronizedWithMesh = mesh;
  92079. // Prepare bones
  92080. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  92081. var bone = this.bones[boneIndex];
  92082. if (!bone.getParent()) {
  92083. var matrix = bone.getBaseMatrix();
  92084. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  92085. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  92086. }
  92087. }
  92088. }
  92089. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  92090. }
  92091. }
  92092. else {
  92093. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  92094. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  92095. }
  92096. this._computeTransformMatrices(this._transformMatrices, null);
  92097. }
  92098. this._isDirty = false;
  92099. this._scene._activeBones.addCount(this.bones.length, false);
  92100. };
  92101. /**
  92102. * Gets the list of animatables currently running for this skeleton
  92103. * @returns an array of animatables
  92104. */
  92105. Skeleton.prototype.getAnimatables = function () {
  92106. if (!this._animatables || this._animatables.length !== this.bones.length) {
  92107. this._animatables = [];
  92108. for (var index = 0; index < this.bones.length; index++) {
  92109. this._animatables.push(this.bones[index]);
  92110. }
  92111. }
  92112. return this._animatables;
  92113. };
  92114. /**
  92115. * Clone the current skeleton
  92116. * @param name defines the name of the new skeleton
  92117. * @param id defines the id of the enw skeleton
  92118. * @returns the new skeleton
  92119. */
  92120. Skeleton.prototype.clone = function (name, id) {
  92121. var result = new Skeleton(name, id || name, this._scene);
  92122. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  92123. for (var index = 0; index < this.bones.length; index++) {
  92124. var source = this.bones[index];
  92125. var parentBone = null;
  92126. var parent_1 = source.getParent();
  92127. if (parent_1) {
  92128. var parentIndex = this.bones.indexOf(parent_1);
  92129. parentBone = result.bones[parentIndex];
  92130. }
  92131. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  92132. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  92133. }
  92134. if (this._ranges) {
  92135. result._ranges = {};
  92136. for (var rangeName in this._ranges) {
  92137. var range = this._ranges[rangeName];
  92138. if (range) {
  92139. result._ranges[rangeName] = range.clone();
  92140. }
  92141. }
  92142. }
  92143. this._isDirty = true;
  92144. return result;
  92145. };
  92146. /**
  92147. * Enable animation blending for this skeleton
  92148. * @param blendingSpeed defines the blending speed to apply
  92149. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  92150. */
  92151. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  92152. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  92153. this.bones.forEach(function (bone) {
  92154. bone.animations.forEach(function (animation) {
  92155. animation.enableBlending = true;
  92156. animation.blendingSpeed = blendingSpeed;
  92157. });
  92158. });
  92159. };
  92160. /**
  92161. * Releases all resources associated with the current skeleton
  92162. */
  92163. Skeleton.prototype.dispose = function () {
  92164. this._meshesWithPoseMatrix = [];
  92165. // Animations
  92166. this.getScene().stopAnimation(this);
  92167. // Remove from scene
  92168. this.getScene().removeSkeleton(this);
  92169. };
  92170. /**
  92171. * Serialize the skeleton in a JSON object
  92172. * @returns a JSON object
  92173. */
  92174. Skeleton.prototype.serialize = function () {
  92175. var serializationObject = {};
  92176. serializationObject.name = this.name;
  92177. serializationObject.id = this.id;
  92178. if (this.dimensionsAtRest) {
  92179. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  92180. }
  92181. serializationObject.bones = [];
  92182. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  92183. for (var index = 0; index < this.bones.length; index++) {
  92184. var bone = this.bones[index];
  92185. var parent_2 = bone.getParent();
  92186. var serializedBone = {
  92187. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  92188. name: bone.name,
  92189. matrix: bone.getBaseMatrix().toArray(),
  92190. rest: bone.getRestPose().toArray()
  92191. };
  92192. serializationObject.bones.push(serializedBone);
  92193. if (bone.length) {
  92194. serializedBone.length = bone.length;
  92195. }
  92196. if (bone.metadata) {
  92197. serializedBone.metadata = bone.metadata;
  92198. }
  92199. if (bone.animations && bone.animations.length > 0) {
  92200. serializedBone.animation = bone.animations[0].serialize();
  92201. }
  92202. serializationObject.ranges = [];
  92203. for (var name in this._ranges) {
  92204. var source = this._ranges[name];
  92205. if (!source) {
  92206. continue;
  92207. }
  92208. var range = {};
  92209. range.name = name;
  92210. range.from = source.from;
  92211. range.to = source.to;
  92212. serializationObject.ranges.push(range);
  92213. }
  92214. }
  92215. return serializationObject;
  92216. };
  92217. /**
  92218. * Creates a new skeleton from serialized data
  92219. * @param parsedSkeleton defines the serialized data
  92220. * @param scene defines the hosting scene
  92221. * @returns a new skeleton
  92222. */
  92223. Skeleton.Parse = function (parsedSkeleton, scene) {
  92224. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  92225. if (parsedSkeleton.dimensionsAtRest) {
  92226. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  92227. }
  92228. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  92229. var index;
  92230. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  92231. var parsedBone = parsedSkeleton.bones[index];
  92232. var parentBone = null;
  92233. if (parsedBone.parentBoneIndex > -1) {
  92234. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  92235. }
  92236. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  92237. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  92238. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  92239. bone.id = parsedBone.id;
  92240. }
  92241. if (parsedBone.length) {
  92242. bone.length = parsedBone.length;
  92243. }
  92244. if (parsedBone.metadata) {
  92245. bone.metadata = parsedBone.metadata;
  92246. }
  92247. if (parsedBone.animation) {
  92248. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  92249. }
  92250. }
  92251. // placed after bones, so createAnimationRange can cascade down
  92252. if (parsedSkeleton.ranges) {
  92253. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  92254. var data = parsedSkeleton.ranges[index];
  92255. skeleton.createAnimationRange(data.name, data.from, data.to);
  92256. }
  92257. }
  92258. return skeleton;
  92259. };
  92260. /**
  92261. * Compute all node absolute transforms
  92262. * @param forceUpdate defines if computation must be done even if cache is up to date
  92263. */
  92264. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  92265. if (forceUpdate === void 0) { forceUpdate = false; }
  92266. var renderId = this._scene.getRenderId();
  92267. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  92268. this.bones[0].computeAbsoluteTransforms();
  92269. this._lastAbsoluteTransformsUpdateId = renderId;
  92270. }
  92271. };
  92272. /**
  92273. * Gets the root pose matrix
  92274. * @returns a matrix
  92275. */
  92276. Skeleton.prototype.getPoseMatrix = function () {
  92277. var poseMatrix = null;
  92278. if (this._meshesWithPoseMatrix.length > 0) {
  92279. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  92280. }
  92281. return poseMatrix;
  92282. };
  92283. /**
  92284. * Sorts bones per internal index
  92285. */
  92286. Skeleton.prototype.sortBones = function () {
  92287. var bones = new Array();
  92288. var visited = new Array(this.bones.length);
  92289. for (var index = 0; index < this.bones.length; index++) {
  92290. this._sortBones(index, bones, visited);
  92291. }
  92292. this.bones = bones;
  92293. };
  92294. Skeleton.prototype._sortBones = function (index, bones, visited) {
  92295. if (visited[index]) {
  92296. return;
  92297. }
  92298. visited[index] = true;
  92299. var bone = this.bones[index];
  92300. if (bone._index === undefined) {
  92301. bone._index = index;
  92302. }
  92303. var parentBone = bone.getParent();
  92304. if (parentBone) {
  92305. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  92306. }
  92307. bones.push(bone);
  92308. };
  92309. return Skeleton;
  92310. }());
  92311. BABYLON.Skeleton = Skeleton;
  92312. })(BABYLON || (BABYLON = {}));
  92313. //# sourceMappingURL=babylon.skeleton.js.map
  92314. var BABYLON;
  92315. (function (BABYLON) {
  92316. /**
  92317. * This groups tools to convert HDR texture to native colors array.
  92318. */
  92319. var HDRTools = /** @class */ (function () {
  92320. function HDRTools() {
  92321. }
  92322. HDRTools.Ldexp = function (mantissa, exponent) {
  92323. if (exponent > 1023) {
  92324. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  92325. }
  92326. if (exponent < -1074) {
  92327. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  92328. }
  92329. return mantissa * Math.pow(2, exponent);
  92330. };
  92331. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  92332. if (exponent > 0) { /*nonzero pixel*/
  92333. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  92334. float32array[index + 0] = red * exponent;
  92335. float32array[index + 1] = green * exponent;
  92336. float32array[index + 2] = blue * exponent;
  92337. }
  92338. else {
  92339. float32array[index + 0] = 0;
  92340. float32array[index + 1] = 0;
  92341. float32array[index + 2] = 0;
  92342. }
  92343. };
  92344. HDRTools.readStringLine = function (uint8array, startIndex) {
  92345. var line = "";
  92346. var character = "";
  92347. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  92348. character = String.fromCharCode(uint8array[i]);
  92349. if (character == "\n") {
  92350. break;
  92351. }
  92352. line += character;
  92353. }
  92354. return line;
  92355. };
  92356. /**
  92357. * Reads header information from an RGBE texture stored in a native array.
  92358. * More information on this format are available here:
  92359. * https://en.wikipedia.org/wiki/RGBE_image_format
  92360. *
  92361. * @param uint8array The binary file stored in native array.
  92362. * @return The header information.
  92363. */
  92364. HDRTools.RGBE_ReadHeader = function (uint8array) {
  92365. var height = 0;
  92366. var width = 0;
  92367. var line = this.readStringLine(uint8array, 0);
  92368. if (line[0] != '#' || line[1] != '?') {
  92369. throw "Bad HDR Format.";
  92370. }
  92371. var endOfHeader = false;
  92372. var findFormat = false;
  92373. var lineIndex = 0;
  92374. do {
  92375. lineIndex += (line.length + 1);
  92376. line = this.readStringLine(uint8array, lineIndex);
  92377. if (line == "FORMAT=32-bit_rle_rgbe") {
  92378. findFormat = true;
  92379. }
  92380. else if (line.length == 0) {
  92381. endOfHeader = true;
  92382. }
  92383. } while (!endOfHeader);
  92384. if (!findFormat) {
  92385. throw "HDR Bad header format, unsupported FORMAT";
  92386. }
  92387. lineIndex += (line.length + 1);
  92388. line = this.readStringLine(uint8array, lineIndex);
  92389. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  92390. var match = sizeRegexp.exec(line);
  92391. // TODO. Support +Y and -X if needed.
  92392. if (!match || match.length < 3) {
  92393. throw "HDR Bad header format, no size";
  92394. }
  92395. width = parseInt(match[2]);
  92396. height = parseInt(match[1]);
  92397. if (width < 8 || width > 0x7fff) {
  92398. throw "HDR Bad header format, unsupported size";
  92399. }
  92400. lineIndex += (line.length + 1);
  92401. return {
  92402. height: height,
  92403. width: width,
  92404. dataPosition: lineIndex
  92405. };
  92406. };
  92407. /**
  92408. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  92409. * This RGBE texture needs to store the information as a panorama.
  92410. *
  92411. * More information on this format are available here:
  92412. * https://en.wikipedia.org/wiki/RGBE_image_format
  92413. *
  92414. * @param buffer The binary file stored in an array buffer.
  92415. * @param size The expected size of the extracted cubemap.
  92416. * @return The Cube Map information.
  92417. */
  92418. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  92419. var uint8array = new Uint8Array(buffer);
  92420. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  92421. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  92422. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  92423. return cubeMapData;
  92424. };
  92425. /**
  92426. * Returns the pixels data extracted from an RGBE texture.
  92427. * This pixels will be stored left to right up to down in the R G B order in one array.
  92428. *
  92429. * More information on this format are available here:
  92430. * https://en.wikipedia.org/wiki/RGBE_image_format
  92431. *
  92432. * @param uint8array The binary file stored in an array buffer.
  92433. * @param hdrInfo The header information of the file.
  92434. * @return The pixels data in RGB right to left up to down order.
  92435. */
  92436. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  92437. // Keep for multi format supports.
  92438. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  92439. };
  92440. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  92441. var num_scanlines = hdrInfo.height;
  92442. var scanline_width = hdrInfo.width;
  92443. var a, b, c, d, count;
  92444. var dataIndex = hdrInfo.dataPosition;
  92445. var index = 0, endIndex = 0, i = 0;
  92446. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  92447. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  92448. // 3 channels of 4 bytes per pixel in float.
  92449. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  92450. var resultArray = new Float32Array(resultBuffer);
  92451. // read in each successive scanline
  92452. while (num_scanlines > 0) {
  92453. a = uint8array[dataIndex++];
  92454. b = uint8array[dataIndex++];
  92455. c = uint8array[dataIndex++];
  92456. d = uint8array[dataIndex++];
  92457. if (a != 2 || b != 2 || (c & 0x80)) {
  92458. // this file is not run length encoded
  92459. throw "HDR Bad header format, not RLE";
  92460. }
  92461. if (((c << 8) | d) != scanline_width) {
  92462. throw "HDR Bad header format, wrong scan line width";
  92463. }
  92464. index = 0;
  92465. // read each of the four channels for the scanline into the buffer
  92466. for (i = 0; i < 4; i++) {
  92467. endIndex = (i + 1) * scanline_width;
  92468. while (index < endIndex) {
  92469. a = uint8array[dataIndex++];
  92470. b = uint8array[dataIndex++];
  92471. if (a > 128) {
  92472. // a run of the same value
  92473. count = a - 128;
  92474. if ((count == 0) || (count > endIndex - index)) {
  92475. throw "HDR Bad Format, bad scanline data (run)";
  92476. }
  92477. while (count-- > 0) {
  92478. scanLineArray[index++] = b;
  92479. }
  92480. }
  92481. else {
  92482. // a non-run
  92483. count = a;
  92484. if ((count == 0) || (count > endIndex - index)) {
  92485. throw "HDR Bad Format, bad scanline data (non-run)";
  92486. }
  92487. scanLineArray[index++] = b;
  92488. if (--count > 0) {
  92489. for (var j = 0; j < count; j++) {
  92490. scanLineArray[index++] = uint8array[dataIndex++];
  92491. }
  92492. }
  92493. }
  92494. }
  92495. }
  92496. // now convert data from buffer into floats
  92497. for (i = 0; i < scanline_width; i++) {
  92498. a = scanLineArray[i];
  92499. b = scanLineArray[i + scanline_width];
  92500. c = scanLineArray[i + 2 * scanline_width];
  92501. d = scanLineArray[i + 3 * scanline_width];
  92502. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  92503. }
  92504. num_scanlines--;
  92505. }
  92506. return resultArray;
  92507. };
  92508. return HDRTools;
  92509. }());
  92510. BABYLON.HDRTools = HDRTools;
  92511. })(BABYLON || (BABYLON = {}));
  92512. //# sourceMappingURL=babylon.hdr.js.map
  92513. var BABYLON;
  92514. (function (BABYLON) {
  92515. /**
  92516. * This represents a texture coming from an HDR input.
  92517. *
  92518. * The only supported format is currently panorama picture stored in RGBE format.
  92519. * Example of such files can be found on HDRLib: http://hdrlib.com/
  92520. */
  92521. var HDRCubeTexture = /** @class */ (function (_super) {
  92522. __extends(HDRCubeTexture, _super);
  92523. /**
  92524. * Instantiates an HDRTexture from the following parameters.
  92525. *
  92526. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  92527. * @param scene The scene the texture will be used in
  92528. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  92529. * @param noMipmap Forces to not generate the mipmap if true
  92530. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  92531. * @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)
  92532. * @param reserved Reserved flag for internal use.
  92533. */
  92534. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  92535. if (noMipmap === void 0) { noMipmap = false; }
  92536. if (generateHarmonics === void 0) { generateHarmonics = true; }
  92537. if (gammaSpace === void 0) { gammaSpace = false; }
  92538. if (reserved === void 0) { reserved = false; }
  92539. if (onLoad === void 0) { onLoad = null; }
  92540. if (onError === void 0) { onError = null; }
  92541. var _this = _super.call(this, scene) || this;
  92542. _this._generateHarmonics = true;
  92543. _this._onLoad = null;
  92544. _this._onError = null;
  92545. /**
  92546. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  92547. */
  92548. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  92549. _this._isBlocking = true;
  92550. _this._rotationY = 0;
  92551. /**
  92552. * Gets or sets the center of the bounding box associated with the cube texture
  92553. * It must define where the camera used to render the texture was set
  92554. */
  92555. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  92556. if (!url) {
  92557. return _this;
  92558. }
  92559. _this.name = url;
  92560. _this.url = url;
  92561. _this.hasAlpha = false;
  92562. _this.isCube = true;
  92563. _this._textureMatrix = BABYLON.Matrix.Identity();
  92564. _this._onLoad = onLoad;
  92565. _this._onError = onError;
  92566. _this.gammaSpace = gammaSpace;
  92567. _this._noMipmap = noMipmap;
  92568. _this._size = size;
  92569. _this._texture = _this._getFromCache(url, _this._noMipmap);
  92570. if (!_this._texture) {
  92571. if (!scene.useDelayedTextureLoading) {
  92572. _this.loadTexture();
  92573. }
  92574. else {
  92575. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  92576. }
  92577. }
  92578. return _this;
  92579. }
  92580. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  92581. /**
  92582. * Gets wether or not the texture is blocking during loading.
  92583. */
  92584. get: function () {
  92585. return this._isBlocking;
  92586. },
  92587. /**
  92588. * Sets wether or not the texture is blocking during loading.
  92589. */
  92590. set: function (value) {
  92591. this._isBlocking = value;
  92592. },
  92593. enumerable: true,
  92594. configurable: true
  92595. });
  92596. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  92597. /**
  92598. * Gets texture matrix rotation angle around Y axis radians.
  92599. */
  92600. get: function () {
  92601. return this._rotationY;
  92602. },
  92603. /**
  92604. * Sets texture matrix rotation angle around Y axis in radians.
  92605. */
  92606. set: function (value) {
  92607. this._rotationY = value;
  92608. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  92609. },
  92610. enumerable: true,
  92611. configurable: true
  92612. });
  92613. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  92614. get: function () {
  92615. return this._boundingBoxSize;
  92616. },
  92617. /**
  92618. * Gets or sets the size of the bounding box associated with the cube texture
  92619. * When defined, the cubemap will switch to local mode
  92620. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  92621. * @example https://www.babylonjs-playground.com/#RNASML
  92622. */
  92623. set: function (value) {
  92624. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  92625. return;
  92626. }
  92627. this._boundingBoxSize = value;
  92628. var scene = this.getScene();
  92629. if (scene) {
  92630. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  92631. }
  92632. },
  92633. enumerable: true,
  92634. configurable: true
  92635. });
  92636. /**
  92637. * Occurs when the file is raw .hdr file.
  92638. */
  92639. HDRCubeTexture.prototype.loadTexture = function () {
  92640. var _this = this;
  92641. var callback = function (buffer) {
  92642. _this.lodGenerationOffset = 0.0;
  92643. _this.lodGenerationScale = 0.8;
  92644. var scene = _this.getScene();
  92645. if (!scene) {
  92646. return null;
  92647. }
  92648. // Extract the raw linear data.
  92649. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  92650. // Generate harmonics if needed.
  92651. if (_this._generateHarmonics) {
  92652. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  92653. _this.sphericalPolynomial = sphericalPolynomial;
  92654. }
  92655. var results = [];
  92656. var byteArray = null;
  92657. // Push each faces.
  92658. for (var j = 0; j < 6; j++) {
  92659. // Create uintarray fallback.
  92660. if (!scene.getEngine().getCaps().textureFloat) {
  92661. // 3 channels of 1 bytes per pixel in bytes.
  92662. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  92663. byteArray = new Uint8Array(byteBuffer);
  92664. }
  92665. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  92666. // If special cases.
  92667. if (_this.gammaSpace || byteArray) {
  92668. for (var i = 0; i < _this._size * _this._size; i++) {
  92669. // Put in gamma space if requested.
  92670. if (_this.gammaSpace) {
  92671. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  92672. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  92673. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  92674. }
  92675. // Convert to int texture for fallback.
  92676. if (byteArray) {
  92677. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  92678. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  92679. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  92680. // May use luminance instead if the result is not accurate.
  92681. var max = Math.max(Math.max(r, g), b);
  92682. if (max > 255) {
  92683. var scale = 255 / max;
  92684. r *= scale;
  92685. g *= scale;
  92686. b *= scale;
  92687. }
  92688. byteArray[(i * 3) + 0] = r;
  92689. byteArray[(i * 3) + 1] = g;
  92690. byteArray[(i * 3) + 2] = b;
  92691. }
  92692. }
  92693. }
  92694. if (byteArray) {
  92695. results.push(byteArray);
  92696. }
  92697. else {
  92698. results.push(dataFace);
  92699. }
  92700. }
  92701. return results;
  92702. };
  92703. var scene = this.getScene();
  92704. if (scene) {
  92705. 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);
  92706. }
  92707. };
  92708. HDRCubeTexture.prototype.clone = function () {
  92709. var scene = this.getScene();
  92710. if (!scene) {
  92711. return this;
  92712. }
  92713. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  92714. // Base texture
  92715. newTexture.level = this.level;
  92716. newTexture.wrapU = this.wrapU;
  92717. newTexture.wrapV = this.wrapV;
  92718. newTexture.coordinatesIndex = this.coordinatesIndex;
  92719. newTexture.coordinatesMode = this.coordinatesMode;
  92720. return newTexture;
  92721. };
  92722. // Methods
  92723. HDRCubeTexture.prototype.delayLoad = function () {
  92724. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  92725. return;
  92726. }
  92727. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  92728. this._texture = this._getFromCache(this.url, this._noMipmap);
  92729. if (!this._texture) {
  92730. this.loadTexture();
  92731. }
  92732. };
  92733. /**
  92734. * Get the texture reflection matrix used to rotate/transform the reflection.
  92735. * @returns the reflection matrix
  92736. */
  92737. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  92738. return this._textureMatrix;
  92739. };
  92740. /**
  92741. * Set the texture reflection matrix used to rotate/transform the reflection.
  92742. * @param value Define the reflection matrix to set
  92743. */
  92744. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  92745. this._textureMatrix = value;
  92746. };
  92747. /**
  92748. * Parses a JSON representation of an HDR Texture in order to create the texture
  92749. * @param parsedTexture Define the JSON representation
  92750. * @param scene Define the scene the texture should be created in
  92751. * @param rootUrl Define the root url in case we need to load relative dependencies
  92752. * @returns the newly created texture after parsing
  92753. */
  92754. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  92755. var texture = null;
  92756. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  92757. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  92758. texture.name = parsedTexture.name;
  92759. texture.hasAlpha = parsedTexture.hasAlpha;
  92760. texture.level = parsedTexture.level;
  92761. texture.coordinatesMode = parsedTexture.coordinatesMode;
  92762. texture.isBlocking = parsedTexture.isBlocking;
  92763. }
  92764. if (texture) {
  92765. if (parsedTexture.boundingBoxPosition) {
  92766. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  92767. }
  92768. if (parsedTexture.boundingBoxSize) {
  92769. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  92770. }
  92771. if (parsedTexture.rotationY) {
  92772. texture.rotationY = parsedTexture.rotationY;
  92773. }
  92774. }
  92775. return texture;
  92776. };
  92777. HDRCubeTexture.prototype.serialize = function () {
  92778. if (!this.name) {
  92779. return null;
  92780. }
  92781. var serializationObject = {};
  92782. serializationObject.name = this.name;
  92783. serializationObject.hasAlpha = this.hasAlpha;
  92784. serializationObject.isCube = true;
  92785. serializationObject.level = this.level;
  92786. serializationObject.size = this._size;
  92787. serializationObject.coordinatesMode = this.coordinatesMode;
  92788. serializationObject.useInGammaSpace = this.gammaSpace;
  92789. serializationObject.generateHarmonics = this._generateHarmonics;
  92790. serializationObject.customType = "BABYLON.HDRCubeTexture";
  92791. serializationObject.noMipmap = this._noMipmap;
  92792. serializationObject.isBlocking = this._isBlocking;
  92793. serializationObject.rotationY = this._rotationY;
  92794. return serializationObject;
  92795. };
  92796. HDRCubeTexture._facesMapping = [
  92797. "right",
  92798. "left",
  92799. "up",
  92800. "down",
  92801. "front",
  92802. "back"
  92803. ];
  92804. return HDRCubeTexture;
  92805. }(BABYLON.BaseTexture));
  92806. BABYLON.HDRCubeTexture = HDRCubeTexture;
  92807. })(BABYLON || (BABYLON = {}));
  92808. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  92809. var BABYLON;
  92810. (function (BABYLON) {
  92811. /**
  92812. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  92813. */
  92814. var PanoramaToCubeMapTools = /** @class */ (function () {
  92815. function PanoramaToCubeMapTools() {
  92816. }
  92817. /**
  92818. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  92819. *
  92820. * @param float32Array The source data.
  92821. * @param inputWidth The width of the input panorama.
  92822. * @param inputHeight The height of the input panorama.
  92823. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  92824. * @return The cubemap data
  92825. */
  92826. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  92827. if (!float32Array) {
  92828. throw "ConvertPanoramaToCubemap: input cannot be null";
  92829. }
  92830. if (float32Array.length != inputWidth * inputHeight * 3) {
  92831. throw "ConvertPanoramaToCubemap: input size is wrong";
  92832. }
  92833. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  92834. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  92835. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  92836. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  92837. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  92838. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  92839. return {
  92840. front: textureFront,
  92841. back: textureBack,
  92842. left: textureLeft,
  92843. right: textureRight,
  92844. up: textureUp,
  92845. down: textureDown,
  92846. size: size,
  92847. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  92848. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  92849. gammaSpace: false,
  92850. };
  92851. };
  92852. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  92853. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  92854. var textureArray = new Float32Array(buffer);
  92855. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  92856. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  92857. var dy = 1 / texSize;
  92858. var fy = 0;
  92859. for (var y = 0; y < texSize; y++) {
  92860. var xv1 = faceData[0];
  92861. var xv2 = faceData[2];
  92862. for (var x = 0; x < texSize; x++) {
  92863. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  92864. v.normalize();
  92865. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  92866. // 3 channels per pixels
  92867. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  92868. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  92869. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  92870. xv1 = xv1.add(rotDX1);
  92871. xv2 = xv2.add(rotDX2);
  92872. }
  92873. fy += dy;
  92874. }
  92875. return textureArray;
  92876. };
  92877. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  92878. var theta = Math.atan2(vDir.z, vDir.x);
  92879. var phi = Math.acos(vDir.y);
  92880. while (theta < -Math.PI) {
  92881. theta += 2 * Math.PI;
  92882. }
  92883. while (theta > Math.PI) {
  92884. theta -= 2 * Math.PI;
  92885. }
  92886. var dx = theta / Math.PI;
  92887. var dy = phi / Math.PI;
  92888. // recenter.
  92889. dx = dx * 0.5 + 0.5;
  92890. var px = Math.round(dx * inputWidth);
  92891. if (px < 0) {
  92892. px = 0;
  92893. }
  92894. else if (px >= inputWidth) {
  92895. px = inputWidth - 1;
  92896. }
  92897. var py = Math.round(dy * inputHeight);
  92898. if (py < 0) {
  92899. py = 0;
  92900. }
  92901. else if (py >= inputHeight) {
  92902. py = inputHeight - 1;
  92903. }
  92904. var inputY = (inputHeight - py - 1);
  92905. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  92906. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  92907. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  92908. return {
  92909. r: r,
  92910. g: g,
  92911. b: b
  92912. };
  92913. };
  92914. PanoramaToCubeMapTools.FACE_FRONT = [
  92915. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  92916. new BABYLON.Vector3(1.0, -1.0, -1.0),
  92917. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  92918. new BABYLON.Vector3(1.0, 1.0, -1.0)
  92919. ];
  92920. PanoramaToCubeMapTools.FACE_BACK = [
  92921. new BABYLON.Vector3(1.0, -1.0, 1.0),
  92922. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  92923. new BABYLON.Vector3(1.0, 1.0, 1.0),
  92924. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  92925. ];
  92926. PanoramaToCubeMapTools.FACE_RIGHT = [
  92927. new BABYLON.Vector3(1.0, -1.0, -1.0),
  92928. new BABYLON.Vector3(1.0, -1.0, 1.0),
  92929. new BABYLON.Vector3(1.0, 1.0, -1.0),
  92930. new BABYLON.Vector3(1.0, 1.0, 1.0)
  92931. ];
  92932. PanoramaToCubeMapTools.FACE_LEFT = [
  92933. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  92934. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  92935. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  92936. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  92937. ];
  92938. PanoramaToCubeMapTools.FACE_DOWN = [
  92939. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  92940. new BABYLON.Vector3(1.0, 1.0, -1.0),
  92941. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  92942. new BABYLON.Vector3(1.0, 1.0, 1.0)
  92943. ];
  92944. PanoramaToCubeMapTools.FACE_UP = [
  92945. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  92946. new BABYLON.Vector3(1.0, -1.0, 1.0),
  92947. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  92948. new BABYLON.Vector3(1.0, -1.0, -1.0)
  92949. ];
  92950. return PanoramaToCubeMapTools;
  92951. }());
  92952. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  92953. })(BABYLON || (BABYLON = {}));
  92954. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  92955. var BABYLON;
  92956. (function (BABYLON) {
  92957. /**
  92958. * Vector2 wth index property
  92959. */
  92960. var IndexedVector2 = /** @class */ (function (_super) {
  92961. __extends(IndexedVector2, _super);
  92962. function IndexedVector2(original,
  92963. /** Index of the vector2 */
  92964. index) {
  92965. var _this = _super.call(this, original.x, original.y) || this;
  92966. _this.index = index;
  92967. return _this;
  92968. }
  92969. return IndexedVector2;
  92970. }(BABYLON.Vector2));
  92971. /**
  92972. * Defines points to create a polygon
  92973. */
  92974. var PolygonPoints = /** @class */ (function () {
  92975. function PolygonPoints() {
  92976. this.elements = new Array();
  92977. }
  92978. PolygonPoints.prototype.add = function (originalPoints) {
  92979. var _this = this;
  92980. var result = new Array();
  92981. originalPoints.forEach(function (point) {
  92982. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  92983. var newPoint = new IndexedVector2(point, _this.elements.length);
  92984. result.push(newPoint);
  92985. _this.elements.push(newPoint);
  92986. }
  92987. });
  92988. return result;
  92989. };
  92990. PolygonPoints.prototype.computeBounds = function () {
  92991. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  92992. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  92993. this.elements.forEach(function (point) {
  92994. // x
  92995. if (point.x < lmin.x) {
  92996. lmin.x = point.x;
  92997. }
  92998. else if (point.x > lmax.x) {
  92999. lmax.x = point.x;
  93000. }
  93001. // y
  93002. if (point.y < lmin.y) {
  93003. lmin.y = point.y;
  93004. }
  93005. else if (point.y > lmax.y) {
  93006. lmax.y = point.y;
  93007. }
  93008. });
  93009. return {
  93010. min: lmin,
  93011. max: lmax,
  93012. width: lmax.x - lmin.x,
  93013. height: lmax.y - lmin.y
  93014. };
  93015. };
  93016. return PolygonPoints;
  93017. }());
  93018. /**
  93019. * Polygon
  93020. * @see https://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  93021. */
  93022. var Polygon = /** @class */ (function () {
  93023. function Polygon() {
  93024. }
  93025. /**
  93026. * Creates a rectangle
  93027. * @param xmin bottom X coord
  93028. * @param ymin bottom Y coord
  93029. * @param xmax top X coord
  93030. * @param ymax top Y coord
  93031. * @returns points that make the resulting rectation
  93032. */
  93033. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  93034. return [
  93035. new BABYLON.Vector2(xmin, ymin),
  93036. new BABYLON.Vector2(xmax, ymin),
  93037. new BABYLON.Vector2(xmax, ymax),
  93038. new BABYLON.Vector2(xmin, ymax)
  93039. ];
  93040. };
  93041. /**
  93042. * Creates a circle
  93043. * @param radius radius of circle
  93044. * @param cx scale in x
  93045. * @param cy scale in y
  93046. * @param numberOfSides number of sides that make up the circle
  93047. * @returns points that make the resulting circle
  93048. */
  93049. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  93050. if (cx === void 0) { cx = 0; }
  93051. if (cy === void 0) { cy = 0; }
  93052. if (numberOfSides === void 0) { numberOfSides = 32; }
  93053. var result = new Array();
  93054. var angle = 0;
  93055. var increment = (Math.PI * 2) / numberOfSides;
  93056. for (var i = 0; i < numberOfSides; i++) {
  93057. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  93058. angle -= increment;
  93059. }
  93060. return result;
  93061. };
  93062. /**
  93063. * Creates a polygon from input string
  93064. * @param input Input polygon data
  93065. * @returns the parsed points
  93066. */
  93067. Polygon.Parse = function (input) {
  93068. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  93069. var i, result = [];
  93070. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  93071. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  93072. }
  93073. return result;
  93074. };
  93075. /**
  93076. * Starts building a polygon from x and y coordinates
  93077. * @param x x coordinate
  93078. * @param y y coordinate
  93079. * @returns the started path2
  93080. */
  93081. Polygon.StartingAt = function (x, y) {
  93082. return BABYLON.Path2.StartingAt(x, y);
  93083. };
  93084. return Polygon;
  93085. }());
  93086. BABYLON.Polygon = Polygon;
  93087. /**
  93088. * Builds a polygon
  93089. * @see https://doc.babylonjs.com/how_to/polygonmeshbuilder
  93090. */
  93091. var PolygonMeshBuilder = /** @class */ (function () {
  93092. /**
  93093. * Creates a PolygonMeshBuilder
  93094. * @param name name of the builder
  93095. * @param contours Path of the polygon
  93096. * @param scene scene to add to
  93097. */
  93098. function PolygonMeshBuilder(name, contours, scene) {
  93099. this._points = new PolygonPoints();
  93100. this._outlinepoints = new PolygonPoints();
  93101. this._holes = new Array();
  93102. this._epoints = new Array();
  93103. this._eholes = new Array();
  93104. this._name = name;
  93105. this._scene = scene;
  93106. var points;
  93107. if (contours instanceof BABYLON.Path2) {
  93108. points = contours.getPoints();
  93109. }
  93110. else {
  93111. points = contours;
  93112. }
  93113. this._addToepoint(points);
  93114. this._points.add(points);
  93115. this._outlinepoints.add(points);
  93116. if (typeof earcut === 'undefined') {
  93117. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  93118. }
  93119. }
  93120. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  93121. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  93122. var p = points_1[_i];
  93123. this._epoints.push(p.x, p.y);
  93124. }
  93125. };
  93126. /**
  93127. * Adds a whole within the polygon
  93128. * @param hole Array of points defining the hole
  93129. * @returns this
  93130. */
  93131. PolygonMeshBuilder.prototype.addHole = function (hole) {
  93132. this._points.add(hole);
  93133. var holepoints = new PolygonPoints();
  93134. holepoints.add(hole);
  93135. this._holes.push(holepoints);
  93136. this._eholes.push(this._epoints.length / 2);
  93137. this._addToepoint(hole);
  93138. return this;
  93139. };
  93140. /**
  93141. * Creates the polygon
  93142. * @param updatable If the mesh should be updatable
  93143. * @param depth The depth of the mesh created
  93144. * @returns the created mesh
  93145. */
  93146. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  93147. var _this = this;
  93148. if (updatable === void 0) { updatable = false; }
  93149. if (depth === void 0) { depth = 0; }
  93150. var result = new BABYLON.Mesh(this._name, this._scene);
  93151. var normals = new Array();
  93152. var positions = new Array();
  93153. var uvs = new Array();
  93154. var bounds = this._points.computeBounds();
  93155. this._points.elements.forEach(function (p) {
  93156. normals.push(0, 1.0, 0);
  93157. positions.push(p.x, 0, p.y);
  93158. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  93159. });
  93160. var indices = new Array();
  93161. var res = earcut(this._epoints, this._eholes, 2);
  93162. for (var i = 0; i < res.length; i++) {
  93163. indices.push(res[i]);
  93164. }
  93165. if (depth > 0) {
  93166. var positionscount = (positions.length / 3); //get the current pointcount
  93167. this._points.elements.forEach(function (p) {
  93168. normals.push(0, -1.0, 0);
  93169. positions.push(p.x, -depth, p.y);
  93170. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  93171. });
  93172. var totalCount = indices.length;
  93173. for (var i = 0; i < totalCount; i += 3) {
  93174. var i0 = indices[i + 0];
  93175. var i1 = indices[i + 1];
  93176. var i2 = indices[i + 2];
  93177. indices.push(i2 + positionscount);
  93178. indices.push(i1 + positionscount);
  93179. indices.push(i0 + positionscount);
  93180. }
  93181. //Add the sides
  93182. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  93183. this._holes.forEach(function (hole) {
  93184. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  93185. });
  93186. }
  93187. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  93188. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  93189. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  93190. result.setIndices(indices);
  93191. return result;
  93192. };
  93193. /**
  93194. * Adds a side to the polygon
  93195. * @param positions points that make the polygon
  93196. * @param normals normals of the polygon
  93197. * @param uvs uvs of the polygon
  93198. * @param indices indices of the polygon
  93199. * @param bounds bounds of the polygon
  93200. * @param points points of the polygon
  93201. * @param depth depth of the polygon
  93202. * @param flip flip of the polygon
  93203. */
  93204. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  93205. var StartIndex = positions.length / 3;
  93206. var ulength = 0;
  93207. for (var i = 0; i < points.elements.length; i++) {
  93208. var p = points.elements[i];
  93209. var p1;
  93210. if ((i + 1) > points.elements.length - 1) {
  93211. p1 = points.elements[0];
  93212. }
  93213. else {
  93214. p1 = points.elements[i + 1];
  93215. }
  93216. positions.push(p.x, 0, p.y);
  93217. positions.push(p.x, -depth, p.y);
  93218. positions.push(p1.x, 0, p1.y);
  93219. positions.push(p1.x, -depth, p1.y);
  93220. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  93221. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  93222. var v3 = v2.subtract(v1);
  93223. var v4 = new BABYLON.Vector3(0, 1, 0);
  93224. var vn = BABYLON.Vector3.Cross(v3, v4);
  93225. vn = vn.normalize();
  93226. uvs.push(ulength / bounds.width, 0);
  93227. uvs.push(ulength / bounds.width, 1);
  93228. ulength += v3.length();
  93229. uvs.push((ulength / bounds.width), 0);
  93230. uvs.push((ulength / bounds.width), 1);
  93231. if (!flip) {
  93232. normals.push(-vn.x, -vn.y, -vn.z);
  93233. normals.push(-vn.x, -vn.y, -vn.z);
  93234. normals.push(-vn.x, -vn.y, -vn.z);
  93235. normals.push(-vn.x, -vn.y, -vn.z);
  93236. indices.push(StartIndex);
  93237. indices.push(StartIndex + 1);
  93238. indices.push(StartIndex + 2);
  93239. indices.push(StartIndex + 1);
  93240. indices.push(StartIndex + 3);
  93241. indices.push(StartIndex + 2);
  93242. }
  93243. else {
  93244. normals.push(vn.x, vn.y, vn.z);
  93245. normals.push(vn.x, vn.y, vn.z);
  93246. normals.push(vn.x, vn.y, vn.z);
  93247. normals.push(vn.x, vn.y, vn.z);
  93248. indices.push(StartIndex);
  93249. indices.push(StartIndex + 2);
  93250. indices.push(StartIndex + 1);
  93251. indices.push(StartIndex + 1);
  93252. indices.push(StartIndex + 2);
  93253. indices.push(StartIndex + 3);
  93254. }
  93255. StartIndex += 4;
  93256. }
  93257. };
  93258. return PolygonMeshBuilder;
  93259. }());
  93260. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  93261. })(BABYLON || (BABYLON = {}));
  93262. //# sourceMappingURL=babylon.polygonMesh.js.map
  93263. var BABYLON;
  93264. (function (BABYLON) {
  93265. /**
  93266. * Unique ID when we import meshes from Babylon to CSG
  93267. */
  93268. var currentCSGMeshId = 0;
  93269. /**
  93270. * Represents a vertex of a polygon. Use your own vertex class instead of this
  93271. * one to provide additional features like texture coordinates and vertex
  93272. * colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  93273. * `flip()`, and `interpolate()` methods that behave analogous to the ones
  93274. * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  93275. * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  93276. * is not used anywhere else.
  93277. * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  93278. */
  93279. var Vertex = /** @class */ (function () {
  93280. /**
  93281. * Initializes the vertex
  93282. * @param pos The position of the vertex
  93283. * @param normal The normal of the vertex
  93284. * @param uv The texture coordinate of the vertex
  93285. */
  93286. function Vertex(
  93287. /**
  93288. * The position of the vertex
  93289. */
  93290. pos,
  93291. /**
  93292. * The normal of the vertex
  93293. */
  93294. normal,
  93295. /**
  93296. * The texture coordinate of the vertex
  93297. */
  93298. uv) {
  93299. this.pos = pos;
  93300. this.normal = normal;
  93301. this.uv = uv;
  93302. }
  93303. /**
  93304. * Make a clone, or deep copy, of the vertex
  93305. * @returns A new Vertex
  93306. */
  93307. Vertex.prototype.clone = function () {
  93308. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  93309. };
  93310. /**
  93311. * Invert all orientation-specific data (e.g. vertex normal). Called when the
  93312. * orientation of a polygon is flipped.
  93313. */
  93314. Vertex.prototype.flip = function () {
  93315. this.normal = this.normal.scale(-1);
  93316. };
  93317. /**
  93318. * Create a new vertex between this vertex and `other` by linearly
  93319. * interpolating all properties using a parameter of `t`. Subclasses should
  93320. * override this to interpolate additional properties.
  93321. * @param other the vertex to interpolate against
  93322. * @param t The factor used to linearly interpolate between the vertices
  93323. */
  93324. Vertex.prototype.interpolate = function (other, t) {
  93325. 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));
  93326. };
  93327. return Vertex;
  93328. }());
  93329. /**
  93330. * Represents a plane in 3D space.
  93331. */
  93332. var Plane = /** @class */ (function () {
  93333. /**
  93334. * Initializes the plane
  93335. * @param normal The normal for the plane
  93336. * @param w
  93337. */
  93338. function Plane(normal, w) {
  93339. this.normal = normal;
  93340. this.w = w;
  93341. }
  93342. /**
  93343. * Construct a plane from three points
  93344. * @param a Point a
  93345. * @param b Point b
  93346. * @param c Point c
  93347. */
  93348. Plane.FromPoints = function (a, b, c) {
  93349. var v0 = c.subtract(a);
  93350. var v1 = b.subtract(a);
  93351. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  93352. return null;
  93353. }
  93354. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  93355. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  93356. };
  93357. /**
  93358. * Clone, or make a deep copy of the plane
  93359. * @returns a new Plane
  93360. */
  93361. Plane.prototype.clone = function () {
  93362. return new Plane(this.normal.clone(), this.w);
  93363. };
  93364. /**
  93365. * Flip the face of the plane
  93366. */
  93367. Plane.prototype.flip = function () {
  93368. this.normal.scaleInPlace(-1);
  93369. this.w = -this.w;
  93370. };
  93371. /**
  93372. * Split `polygon` by this plane if needed, then put the polygon or polygon
  93373. * fragments in the appropriate lists. Coplanar polygons go into either
  93374. `* coplanarFront` or `coplanarBack` depending on their orientation with
  93375. * respect to this plane. Polygons in front or in back of this plane go into
  93376. * either `front` or `back`
  93377. * @param polygon The polygon to be split
  93378. * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane
  93379. * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane
  93380. * @param front Will contain the polygons in front of the plane
  93381. * @param back Will contain the polygons begind the plane
  93382. */
  93383. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  93384. var COPLANAR = 0;
  93385. var FRONT = 1;
  93386. var BACK = 2;
  93387. var SPANNING = 3;
  93388. // Classify each point as well as the entire polygon into one of the above
  93389. // four classes.
  93390. var polygonType = 0;
  93391. var types = [];
  93392. var i;
  93393. var t;
  93394. for (i = 0; i < polygon.vertices.length; i++) {
  93395. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  93396. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  93397. polygonType |= type;
  93398. types.push(type);
  93399. }
  93400. // Put the polygon in the correct list, splitting it when necessary
  93401. switch (polygonType) {
  93402. case COPLANAR:
  93403. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  93404. break;
  93405. case FRONT:
  93406. front.push(polygon);
  93407. break;
  93408. case BACK:
  93409. back.push(polygon);
  93410. break;
  93411. case SPANNING:
  93412. var f = [], b = [];
  93413. for (i = 0; i < polygon.vertices.length; i++) {
  93414. var j = (i + 1) % polygon.vertices.length;
  93415. var ti = types[i], tj = types[j];
  93416. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  93417. if (ti !== BACK) {
  93418. f.push(vi);
  93419. }
  93420. if (ti !== FRONT) {
  93421. b.push(ti !== BACK ? vi.clone() : vi);
  93422. }
  93423. if ((ti | tj) === SPANNING) {
  93424. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  93425. var v = vi.interpolate(vj, t);
  93426. f.push(v);
  93427. b.push(v.clone());
  93428. }
  93429. }
  93430. var poly;
  93431. if (f.length >= 3) {
  93432. poly = new Polygon(f, polygon.shared);
  93433. if (poly.plane) {
  93434. front.push(poly);
  93435. }
  93436. }
  93437. if (b.length >= 3) {
  93438. poly = new Polygon(b, polygon.shared);
  93439. if (poly.plane) {
  93440. back.push(poly);
  93441. }
  93442. }
  93443. break;
  93444. }
  93445. };
  93446. /**
  93447. * `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  93448. * point is on the plane
  93449. */
  93450. Plane.EPSILON = 1e-5;
  93451. return Plane;
  93452. }());
  93453. /**
  93454. * Represents a convex polygon. The vertices used to initialize a polygon must
  93455. * be coplanar and form a convex loop.
  93456. *
  93457. * Each convex polygon has a `shared` property, which is shared between all
  93458. * polygons that are clones of each other or were split from the same polygon.
  93459. * This can be used to define per-polygon properties (such as surface color)
  93460. */
  93461. var Polygon = /** @class */ (function () {
  93462. /**
  93463. * Initializes the polygon
  93464. * @param vertices The vertices of the polygon
  93465. * @param shared The properties shared across all polygons
  93466. */
  93467. function Polygon(vertices, shared) {
  93468. this.vertices = vertices;
  93469. this.shared = shared;
  93470. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  93471. }
  93472. /**
  93473. * Clones, or makes a deep copy, or the polygon
  93474. */
  93475. Polygon.prototype.clone = function () {
  93476. var vertices = this.vertices.map(function (v) { return v.clone(); });
  93477. return new Polygon(vertices, this.shared);
  93478. };
  93479. /**
  93480. * Flips the faces of the polygon
  93481. */
  93482. Polygon.prototype.flip = function () {
  93483. this.vertices.reverse().map(function (v) { v.flip(); });
  93484. this.plane.flip();
  93485. };
  93486. return Polygon;
  93487. }());
  93488. /**
  93489. * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  93490. * by picking a polygon to split along. That polygon (and all other coplanar
  93491. * polygons) are added directly to that node and the other polygons are added to
  93492. * the front and/or back subtrees. This is not a leafy BSP tree since there is
  93493. * no distinction between internal and leaf nodes
  93494. */
  93495. var Node = /** @class */ (function () {
  93496. /**
  93497. * Initializes the node
  93498. * @param polygons A collection of polygons held in the node
  93499. */
  93500. function Node(polygons) {
  93501. this.plane = null;
  93502. this.front = null;
  93503. this.back = null;
  93504. this.polygons = new Array();
  93505. if (polygons) {
  93506. this.build(polygons);
  93507. }
  93508. }
  93509. /**
  93510. * Clones, or makes a deep copy, of the node
  93511. * @returns The cloned node
  93512. */
  93513. Node.prototype.clone = function () {
  93514. var node = new Node();
  93515. node.plane = this.plane && this.plane.clone();
  93516. node.front = this.front && this.front.clone();
  93517. node.back = this.back && this.back.clone();
  93518. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  93519. return node;
  93520. };
  93521. /**
  93522. * Convert solid space to empty space and empty space to solid space
  93523. */
  93524. Node.prototype.invert = function () {
  93525. for (var i = 0; i < this.polygons.length; i++) {
  93526. this.polygons[i].flip();
  93527. }
  93528. if (this.plane) {
  93529. this.plane.flip();
  93530. }
  93531. if (this.front) {
  93532. this.front.invert();
  93533. }
  93534. if (this.back) {
  93535. this.back.invert();
  93536. }
  93537. var temp = this.front;
  93538. this.front = this.back;
  93539. this.back = temp;
  93540. };
  93541. /**
  93542. * Recursively remove all polygons in `polygons` that are inside this BSP
  93543. * tree.
  93544. * @param polygons Polygons to remove from the BSP
  93545. * @returns Polygons clipped from the BSP
  93546. */
  93547. Node.prototype.clipPolygons = function (polygons) {
  93548. if (!this.plane) {
  93549. return polygons.slice();
  93550. }
  93551. var front = new Array(), back = new Array();
  93552. for (var i = 0; i < polygons.length; i++) {
  93553. this.plane.splitPolygon(polygons[i], front, back, front, back);
  93554. }
  93555. if (this.front) {
  93556. front = this.front.clipPolygons(front);
  93557. }
  93558. if (this.back) {
  93559. back = this.back.clipPolygons(back);
  93560. }
  93561. else {
  93562. back = [];
  93563. }
  93564. return front.concat(back);
  93565. };
  93566. /**
  93567. * Remove all polygons in this BSP tree that are inside the other BSP tree
  93568. * `bsp`.
  93569. * @param bsp BSP containing polygons to remove from this BSP
  93570. */
  93571. Node.prototype.clipTo = function (bsp) {
  93572. this.polygons = bsp.clipPolygons(this.polygons);
  93573. if (this.front) {
  93574. this.front.clipTo(bsp);
  93575. }
  93576. if (this.back) {
  93577. this.back.clipTo(bsp);
  93578. }
  93579. };
  93580. /**
  93581. * Return a list of all polygons in this BSP tree
  93582. * @returns List of all polygons in this BSP tree
  93583. */
  93584. Node.prototype.allPolygons = function () {
  93585. var polygons = this.polygons.slice();
  93586. if (this.front) {
  93587. polygons = polygons.concat(this.front.allPolygons());
  93588. }
  93589. if (this.back) {
  93590. polygons = polygons.concat(this.back.allPolygons());
  93591. }
  93592. return polygons;
  93593. };
  93594. /**
  93595. * Build a BSP tree out of `polygons`. When called on an existing tree, the
  93596. * new polygons are filtered down to the bottom of the tree and become new
  93597. * nodes there. Each set of polygons is partitioned using the first polygon
  93598. * (no heuristic is used to pick a good split)
  93599. * @param polygons Polygons used to construct the BSP tree
  93600. */
  93601. Node.prototype.build = function (polygons) {
  93602. if (!polygons.length) {
  93603. return;
  93604. }
  93605. if (!this.plane) {
  93606. this.plane = polygons[0].plane.clone();
  93607. }
  93608. var front = new Array(), back = new Array();
  93609. for (var i = 0; i < polygons.length; i++) {
  93610. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  93611. }
  93612. if (front.length) {
  93613. if (!this.front) {
  93614. this.front = new Node();
  93615. }
  93616. this.front.build(front);
  93617. }
  93618. if (back.length) {
  93619. if (!this.back) {
  93620. this.back = new Node();
  93621. }
  93622. this.back.build(back);
  93623. }
  93624. };
  93625. return Node;
  93626. }());
  93627. /**
  93628. * Class for building Constructive Solid Geometry
  93629. */
  93630. var CSG = /** @class */ (function () {
  93631. function CSG() {
  93632. this.polygons = new Array();
  93633. }
  93634. /**
  93635. * Convert the BABYLON.Mesh to BABYLON.CSG
  93636. * @param mesh The BABYLON.Mesh to convert to BABYLON.CSG
  93637. * @returns A new BABYLON.CSG from the BABYLON.Mesh
  93638. */
  93639. CSG.FromMesh = function (mesh) {
  93640. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  93641. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  93642. if (mesh instanceof BABYLON.Mesh) {
  93643. mesh.computeWorldMatrix(true);
  93644. matrix = mesh.getWorldMatrix();
  93645. meshPosition = mesh.position.clone();
  93646. meshRotation = mesh.rotation.clone();
  93647. if (mesh.rotationQuaternion) {
  93648. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  93649. }
  93650. meshScaling = mesh.scaling.clone();
  93651. }
  93652. else {
  93653. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  93654. }
  93655. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  93656. var subMeshes = mesh.subMeshes;
  93657. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  93658. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  93659. vertices = [];
  93660. for (var j = 0; j < 3; j++) {
  93661. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  93662. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  93663. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  93664. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  93665. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  93666. vertex = new Vertex(position, normal, uv);
  93667. vertices.push(vertex);
  93668. }
  93669. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  93670. // To handle the case of degenerated triangle
  93671. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  93672. if (polygon.plane) {
  93673. polygons.push(polygon);
  93674. }
  93675. }
  93676. }
  93677. var csg = CSG.FromPolygons(polygons);
  93678. csg.matrix = matrix;
  93679. csg.position = meshPosition;
  93680. csg.rotation = meshRotation;
  93681. csg.scaling = meshScaling;
  93682. csg.rotationQuaternion = meshRotationQuaternion;
  93683. currentCSGMeshId++;
  93684. return csg;
  93685. };
  93686. /**
  93687. * Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  93688. * @param polygons Polygons used to construct a BABYLON.CSG solid
  93689. */
  93690. CSG.FromPolygons = function (polygons) {
  93691. var csg = new CSG();
  93692. csg.polygons = polygons;
  93693. return csg;
  93694. };
  93695. /**
  93696. * Clones, or makes a deep copy, of the BABYLON.CSG
  93697. * @returns A new BABYLON.CSG
  93698. */
  93699. CSG.prototype.clone = function () {
  93700. var csg = new CSG();
  93701. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  93702. csg.copyTransformAttributes(this);
  93703. return csg;
  93704. };
  93705. /**
  93706. * Unions this CSG with another CSG
  93707. * @param csg The CSG to union against this CSG
  93708. * @returns The unioned CSG
  93709. */
  93710. CSG.prototype.union = function (csg) {
  93711. var a = new Node(this.clone().polygons);
  93712. var b = new Node(csg.clone().polygons);
  93713. a.clipTo(b);
  93714. b.clipTo(a);
  93715. b.invert();
  93716. b.clipTo(a);
  93717. b.invert();
  93718. a.build(b.allPolygons());
  93719. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  93720. };
  93721. /**
  93722. * Unions this CSG with another CSG in place
  93723. * @param csg The CSG to union against this CSG
  93724. */
  93725. CSG.prototype.unionInPlace = function (csg) {
  93726. var a = new Node(this.polygons);
  93727. var b = new Node(csg.polygons);
  93728. a.clipTo(b);
  93729. b.clipTo(a);
  93730. b.invert();
  93731. b.clipTo(a);
  93732. b.invert();
  93733. a.build(b.allPolygons());
  93734. this.polygons = a.allPolygons();
  93735. };
  93736. /**
  93737. * Subtracts this CSG with another CSG
  93738. * @param csg The CSG to subtract against this CSG
  93739. * @returns A new BABYLON.CSG
  93740. */
  93741. CSG.prototype.subtract = function (csg) {
  93742. var a = new Node(this.clone().polygons);
  93743. var b = new Node(csg.clone().polygons);
  93744. a.invert();
  93745. a.clipTo(b);
  93746. b.clipTo(a);
  93747. b.invert();
  93748. b.clipTo(a);
  93749. b.invert();
  93750. a.build(b.allPolygons());
  93751. a.invert();
  93752. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  93753. };
  93754. /**
  93755. * Subtracts this CSG with another CSG in place
  93756. * @param csg The CSG to subtact against this CSG
  93757. */
  93758. CSG.prototype.subtractInPlace = function (csg) {
  93759. var a = new Node(this.polygons);
  93760. var b = new Node(csg.polygons);
  93761. a.invert();
  93762. a.clipTo(b);
  93763. b.clipTo(a);
  93764. b.invert();
  93765. b.clipTo(a);
  93766. b.invert();
  93767. a.build(b.allPolygons());
  93768. a.invert();
  93769. this.polygons = a.allPolygons();
  93770. };
  93771. /**
  93772. * Intersect this CSG with another CSG
  93773. * @param csg The CSG to intersect against this CSG
  93774. * @returns A new BABYLON.CSG
  93775. */
  93776. CSG.prototype.intersect = function (csg) {
  93777. var a = new Node(this.clone().polygons);
  93778. var b = new Node(csg.clone().polygons);
  93779. a.invert();
  93780. b.clipTo(a);
  93781. b.invert();
  93782. a.clipTo(b);
  93783. b.clipTo(a);
  93784. a.build(b.allPolygons());
  93785. a.invert();
  93786. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  93787. };
  93788. /**
  93789. * Intersects this CSG with another CSG in place
  93790. * @param csg The CSG to intersect against this CSG
  93791. */
  93792. CSG.prototype.intersectInPlace = function (csg) {
  93793. var a = new Node(this.polygons);
  93794. var b = new Node(csg.polygons);
  93795. a.invert();
  93796. b.clipTo(a);
  93797. b.invert();
  93798. a.clipTo(b);
  93799. b.clipTo(a);
  93800. a.build(b.allPolygons());
  93801. a.invert();
  93802. this.polygons = a.allPolygons();
  93803. };
  93804. /**
  93805. * Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  93806. * not modified.
  93807. * @returns A new BABYLON.CSG solid with solid and empty space switched
  93808. */
  93809. CSG.prototype.inverse = function () {
  93810. var csg = this.clone();
  93811. csg.inverseInPlace();
  93812. return csg;
  93813. };
  93814. /**
  93815. * Inverses the BABYLON.CSG in place
  93816. */
  93817. CSG.prototype.inverseInPlace = function () {
  93818. this.polygons.map(function (p) { p.flip(); });
  93819. };
  93820. /**
  93821. * This is used to keep meshes transformations so they can be restored
  93822. * when we build back a Babylon Mesh
  93823. * NB : All CSG operations are performed in world coordinates
  93824. * @param csg The BABYLON.CSG to copy the transform attributes from
  93825. * @returns This BABYLON.CSG
  93826. */
  93827. CSG.prototype.copyTransformAttributes = function (csg) {
  93828. this.matrix = csg.matrix;
  93829. this.position = csg.position;
  93830. this.rotation = csg.rotation;
  93831. this.scaling = csg.scaling;
  93832. this.rotationQuaternion = csg.rotationQuaternion;
  93833. return this;
  93834. };
  93835. /**
  93836. * Build Raw mesh from CSG
  93837. * Coordinates here are in world space
  93838. * @param name The name of the mesh geometry
  93839. * @param scene The BABYLON.Scene
  93840. * @param keepSubMeshes Specifies if the submeshes should be kept
  93841. * @returns A new BABYLON.Mesh
  93842. */
  93843. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  93844. var matrix = this.matrix.clone();
  93845. matrix.invert();
  93846. 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;
  93847. if (keepSubMeshes) {
  93848. // Sort Polygons, since subMeshes are indices range
  93849. polygons.sort(function (a, b) {
  93850. if (a.shared.meshId === b.shared.meshId) {
  93851. return a.shared.subMeshId - b.shared.subMeshId;
  93852. }
  93853. else {
  93854. return a.shared.meshId - b.shared.meshId;
  93855. }
  93856. });
  93857. }
  93858. for (var i = 0, il = polygons.length; i < il; i++) {
  93859. polygon = polygons[i];
  93860. // Building SubMeshes
  93861. if (!subMesh_dict[polygon.shared.meshId]) {
  93862. subMesh_dict[polygon.shared.meshId] = {};
  93863. }
  93864. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  93865. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  93866. indexStart: +Infinity,
  93867. indexEnd: -Infinity,
  93868. materialIndex: polygon.shared.materialIndex
  93869. };
  93870. }
  93871. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  93872. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  93873. polygonIndices[0] = 0;
  93874. polygonIndices[1] = j - 1;
  93875. polygonIndices[2] = j;
  93876. for (var k = 0; k < 3; k++) {
  93877. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  93878. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  93879. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  93880. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  93881. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  93882. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  93883. // Check if 2 points can be merged
  93884. if (!(typeof vertex_idx !== 'undefined' &&
  93885. normals[vertex_idx * 3] === localNormal.x &&
  93886. normals[vertex_idx * 3 + 1] === localNormal.y &&
  93887. normals[vertex_idx * 3 + 2] === localNormal.z &&
  93888. uvs[vertex_idx * 2] === uv.x &&
  93889. uvs[vertex_idx * 2 + 1] === uv.y)) {
  93890. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  93891. uvs.push(uv.x, uv.y);
  93892. normals.push(normal.x, normal.y, normal.z);
  93893. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  93894. }
  93895. indices.push(vertex_idx);
  93896. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  93897. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  93898. currentIndex++;
  93899. }
  93900. }
  93901. }
  93902. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  93903. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  93904. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  93905. mesh.setIndices(indices, null);
  93906. if (keepSubMeshes) {
  93907. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  93908. var materialIndexOffset = 0, materialMaxIndex;
  93909. mesh.subMeshes = new Array();
  93910. for (var m in subMesh_dict) {
  93911. materialMaxIndex = -1;
  93912. for (var sm in subMesh_dict[m]) {
  93913. subMesh_obj = subMesh_dict[m][sm];
  93914. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  93915. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  93916. }
  93917. materialIndexOffset += ++materialMaxIndex;
  93918. }
  93919. }
  93920. return mesh;
  93921. };
  93922. /**
  93923. * Build Mesh from CSG taking material and transforms into account
  93924. * @param name The name of the BABYLON.Mesh
  93925. * @param material The material of the BABYLON.Mesh
  93926. * @param scene The BABYLON.Scene
  93927. * @param keepSubMeshes Specifies if submeshes should be kept
  93928. * @returns The new BABYLON.Mesh
  93929. */
  93930. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  93931. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  93932. mesh.material = material;
  93933. mesh.position.copyFrom(this.position);
  93934. mesh.rotation.copyFrom(this.rotation);
  93935. if (this.rotationQuaternion) {
  93936. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  93937. }
  93938. mesh.scaling.copyFrom(this.scaling);
  93939. mesh.computeWorldMatrix(true);
  93940. return mesh;
  93941. };
  93942. return CSG;
  93943. }());
  93944. BABYLON.CSG = CSG;
  93945. })(BABYLON || (BABYLON = {}));
  93946. //# sourceMappingURL=babylon.csg.js.map
  93947. var BABYLON;
  93948. (function (BABYLON) {
  93949. /**
  93950. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  93951. * It controls one of the indiviual texture used in the effect.
  93952. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  93953. */
  93954. var LensFlare = /** @class */ (function () {
  93955. /**
  93956. * Instantiates a new Lens Flare.
  93957. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  93958. * It controls one of the indiviual texture used in the effect.
  93959. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  93960. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  93961. * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  93962. * @param color Define the lens color
  93963. * @param imgUrl Define the lens texture url
  93964. * @param system Define the `lensFlareSystem` this flare is part of
  93965. */
  93966. function LensFlare(
  93967. /**
  93968. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  93969. */
  93970. size,
  93971. /**
  93972. * Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  93973. */
  93974. position, color, imgUrl, system) {
  93975. this.size = size;
  93976. this.position = position;
  93977. /**
  93978. * Define the alpha mode to render this particular lens.
  93979. */
  93980. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  93981. this.color = color || new BABYLON.Color3(1, 1, 1);
  93982. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  93983. this._system = system;
  93984. system.lensFlares.push(this);
  93985. }
  93986. /**
  93987. * Creates a new Lens Flare.
  93988. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  93989. * It controls one of the indiviual texture used in the effect.
  93990. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  93991. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  93992. * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  93993. * @param color Define the lens color
  93994. * @param imgUrl Define the lens texture url
  93995. * @param system Define the `lensFlareSystem` this flare is part of
  93996. * @returns The newly created Lens Flare
  93997. */
  93998. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  93999. return new LensFlare(size, position, color, imgUrl, system);
  94000. };
  94001. /**
  94002. * Dispose and release the lens flare with its associated resources.
  94003. */
  94004. LensFlare.prototype.dispose = function () {
  94005. if (this.texture) {
  94006. this.texture.dispose();
  94007. }
  94008. // Remove from scene
  94009. var index = this._system.lensFlares.indexOf(this);
  94010. this._system.lensFlares.splice(index, 1);
  94011. };
  94012. return LensFlare;
  94013. }());
  94014. BABYLON.LensFlare = LensFlare;
  94015. })(BABYLON || (BABYLON = {}));
  94016. //# sourceMappingURL=babylon.lensFlare.js.map
  94017. var BABYLON;
  94018. (function (BABYLON) {
  94019. // Adds the parser to the scene parsers.
  94020. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  94021. // Lens flares
  94022. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  94023. if (!container.lensFlareSystems) {
  94024. container.lensFlareSystems = new Array();
  94025. }
  94026. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  94027. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  94028. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  94029. container.lensFlareSystems.push(lf);
  94030. }
  94031. }
  94032. });
  94033. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  94034. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  94035. if (this.lensFlareSystems[index].name === name) {
  94036. return this.lensFlareSystems[index];
  94037. }
  94038. }
  94039. return null;
  94040. };
  94041. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  94042. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  94043. if (this.lensFlareSystems[index].id === id) {
  94044. return this.lensFlareSystems[index];
  94045. }
  94046. }
  94047. return null;
  94048. };
  94049. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  94050. var index = this.lensFlareSystems.indexOf(toRemove);
  94051. if (index !== -1) {
  94052. this.lensFlareSystems.splice(index, 1);
  94053. }
  94054. return index;
  94055. };
  94056. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  94057. this.lensFlareSystems.push(newLensFlareSystem);
  94058. };
  94059. /**
  94060. * Defines the lens flare scene component responsible to manage any lens flares
  94061. * in a given scene.
  94062. */
  94063. var LensFlareSystemSceneComponent = /** @class */ (function () {
  94064. /**
  94065. * Creates a new instance of the component for the given scene
  94066. * @param scene Defines the scene to register the component in
  94067. */
  94068. function LensFlareSystemSceneComponent(scene) {
  94069. /**
  94070. * The component name helpfull to identify the component in the list of scene components.
  94071. */
  94072. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  94073. this.scene = scene;
  94074. scene.lensFlareSystems = new Array();
  94075. }
  94076. /**
  94077. * Registers the component in a given scene
  94078. */
  94079. LensFlareSystemSceneComponent.prototype.register = function () {
  94080. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  94081. };
  94082. /**
  94083. * Rebuilds the elements related to this component in case of
  94084. * context lost for instance.
  94085. */
  94086. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  94087. // Nothing to do for lens flare
  94088. };
  94089. /**
  94090. * Adds all the element from the container to the scene
  94091. * @param container the container holding the elements
  94092. */
  94093. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  94094. var _this = this;
  94095. if (!container.lensFlareSystems) {
  94096. return;
  94097. }
  94098. container.lensFlareSystems.forEach(function (o) {
  94099. _this.scene.addLensFlareSystem(o);
  94100. });
  94101. };
  94102. /**
  94103. * Removes all the elements in the container from the scene
  94104. * @param container contains the elements to remove
  94105. */
  94106. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  94107. var _this = this;
  94108. if (!container.lensFlareSystems) {
  94109. return;
  94110. }
  94111. container.lensFlareSystems.forEach(function (o) {
  94112. _this.scene.removeLensFlareSystem(o);
  94113. });
  94114. };
  94115. /**
  94116. * Serializes the component data to the specified json object
  94117. * @param serializationObject The object to serialize to
  94118. */
  94119. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  94120. // Lens flares
  94121. serializationObject.lensFlareSystems = [];
  94122. var lensFlareSystems = this.scene.lensFlareSystems;
  94123. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  94124. var lensFlareSystem = lensFlareSystems_1[_i];
  94125. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  94126. }
  94127. };
  94128. /**
  94129. * Disposes the component and the associated ressources.
  94130. */
  94131. LensFlareSystemSceneComponent.prototype.dispose = function () {
  94132. var lensFlareSystems = this.scene.lensFlareSystems;
  94133. while (lensFlareSystems.length) {
  94134. lensFlareSystems[0].dispose();
  94135. }
  94136. };
  94137. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  94138. // Lens flares
  94139. if (this.scene.lensFlaresEnabled) {
  94140. var lensFlareSystems = this.scene.lensFlareSystems;
  94141. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  94142. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  94143. var lensFlareSystem = lensFlareSystems_2[_i];
  94144. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  94145. lensFlareSystem.render();
  94146. }
  94147. }
  94148. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  94149. }
  94150. };
  94151. return LensFlareSystemSceneComponent;
  94152. }());
  94153. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  94154. })(BABYLON || (BABYLON = {}));
  94155. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  94156. var BABYLON;
  94157. (function (BABYLON) {
  94158. /**
  94159. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  94160. * It is usually composed of several `BABYLON.lensFlare`.
  94161. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  94162. */
  94163. var LensFlareSystem = /** @class */ (function () {
  94164. /**
  94165. * Instantiates a lens flare system.
  94166. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  94167. * It is usually composed of several `BABYLON.lensFlare`.
  94168. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  94169. * @param name Define the name of the lens flare system in the scene
  94170. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  94171. * @param scene Define the scene the lens flare system belongs to
  94172. */
  94173. function LensFlareSystem(
  94174. /**
  94175. * Define the name of the lens flare system
  94176. */
  94177. name, emitter, scene) {
  94178. this.name = name;
  94179. /**
  94180. * List of lens flares used in this system.
  94181. */
  94182. this.lensFlares = new Array();
  94183. /**
  94184. * Define a limit from the border the lens flare can be visible.
  94185. */
  94186. this.borderLimit = 300;
  94187. /**
  94188. * Define a viewport border we do not want to see the lens flare in.
  94189. */
  94190. this.viewportBorder = 0;
  94191. /**
  94192. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  94193. */
  94194. this.layerMask = 0x0FFFFFFF;
  94195. this._vertexBuffers = {};
  94196. this._isEnabled = true;
  94197. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  94198. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  94199. if (!component) {
  94200. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  94201. scene._addComponent(component);
  94202. }
  94203. this._emitter = emitter;
  94204. this.id = name;
  94205. scene.lensFlareSystems.push(this);
  94206. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  94207. var engine = scene.getEngine();
  94208. // VBO
  94209. var vertices = [];
  94210. vertices.push(1, 1);
  94211. vertices.push(-1, 1);
  94212. vertices.push(-1, -1);
  94213. vertices.push(1, -1);
  94214. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  94215. // Indices
  94216. var indices = [];
  94217. indices.push(0);
  94218. indices.push(1);
  94219. indices.push(2);
  94220. indices.push(0);
  94221. indices.push(2);
  94222. indices.push(3);
  94223. this._indexBuffer = engine.createIndexBuffer(indices);
  94224. // Effects
  94225. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  94226. }
  94227. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  94228. /**
  94229. * Define if the lens flare system is enabled.
  94230. */
  94231. get: function () {
  94232. return this._isEnabled;
  94233. },
  94234. set: function (value) {
  94235. this._isEnabled = value;
  94236. },
  94237. enumerable: true,
  94238. configurable: true
  94239. });
  94240. /**
  94241. * Get the scene the effects belongs to.
  94242. * @returns the scene holding the lens flare system
  94243. */
  94244. LensFlareSystem.prototype.getScene = function () {
  94245. return this._scene;
  94246. };
  94247. /**
  94248. * Get the emitter of the lens flare system.
  94249. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  94250. * @returns the emitter of the lens flare system
  94251. */
  94252. LensFlareSystem.prototype.getEmitter = function () {
  94253. return this._emitter;
  94254. };
  94255. /**
  94256. * Set the emitter of the lens flare system.
  94257. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  94258. * @param newEmitter Define the new emitter of the system
  94259. */
  94260. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  94261. this._emitter = newEmitter;
  94262. };
  94263. /**
  94264. * Get the lens flare system emitter position.
  94265. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  94266. * @returns the position
  94267. */
  94268. LensFlareSystem.prototype.getEmitterPosition = function () {
  94269. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  94270. };
  94271. /**
  94272. * @hidden
  94273. */
  94274. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  94275. var position = this.getEmitterPosition();
  94276. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  94277. this._positionX = position.x;
  94278. this._positionY = position.y;
  94279. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  94280. if (this.viewportBorder > 0) {
  94281. globalViewport.x -= this.viewportBorder;
  94282. globalViewport.y -= this.viewportBorder;
  94283. globalViewport.width += this.viewportBorder * 2;
  94284. globalViewport.height += this.viewportBorder * 2;
  94285. position.x += this.viewportBorder;
  94286. position.y += this.viewportBorder;
  94287. this._positionX += this.viewportBorder;
  94288. this._positionY += this.viewportBorder;
  94289. }
  94290. if (position.z > 0) {
  94291. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  94292. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height)) {
  94293. return true;
  94294. }
  94295. }
  94296. return true;
  94297. }
  94298. return false;
  94299. };
  94300. /** @hidden */
  94301. LensFlareSystem.prototype._isVisible = function () {
  94302. if (!this._isEnabled || !this._scene.activeCamera) {
  94303. return false;
  94304. }
  94305. var emitterPosition = this.getEmitterPosition();
  94306. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  94307. var distance = direction.length();
  94308. direction.normalize();
  94309. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  94310. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  94311. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  94312. };
  94313. /**
  94314. * @hidden
  94315. */
  94316. LensFlareSystem.prototype.render = function () {
  94317. if (!this._effect.isReady() || !this._scene.activeCamera) {
  94318. return false;
  94319. }
  94320. var engine = this._scene.getEngine();
  94321. var viewport = this._scene.activeCamera.viewport;
  94322. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  94323. // Position
  94324. if (!this.computeEffectivePosition(globalViewport)) {
  94325. return false;
  94326. }
  94327. // Visibility
  94328. if (!this._isVisible()) {
  94329. return false;
  94330. }
  94331. // Intensity
  94332. var awayX;
  94333. var awayY;
  94334. if (this._positionX < this.borderLimit + globalViewport.x) {
  94335. awayX = this.borderLimit + globalViewport.x - this._positionX;
  94336. }
  94337. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  94338. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  94339. }
  94340. else {
  94341. awayX = 0;
  94342. }
  94343. if (this._positionY < this.borderLimit + globalViewport.y) {
  94344. awayY = this.borderLimit + globalViewport.y - this._positionY;
  94345. }
  94346. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  94347. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  94348. }
  94349. else {
  94350. awayY = 0;
  94351. }
  94352. var away = (awayX > awayY) ? awayX : awayY;
  94353. away -= this.viewportBorder;
  94354. if (away > this.borderLimit) {
  94355. away = this.borderLimit;
  94356. }
  94357. var intensity = 1.0 - BABYLON.Scalar.Clamp(away / this.borderLimit, 0, 1);
  94358. if (intensity < 0) {
  94359. return false;
  94360. }
  94361. if (intensity > 1.0) {
  94362. intensity = 1.0;
  94363. }
  94364. if (this.viewportBorder > 0) {
  94365. globalViewport.x += this.viewportBorder;
  94366. globalViewport.y += this.viewportBorder;
  94367. globalViewport.width -= this.viewportBorder * 2;
  94368. globalViewport.height -= this.viewportBorder * 2;
  94369. this._positionX -= this.viewportBorder;
  94370. this._positionY -= this.viewportBorder;
  94371. }
  94372. // Position
  94373. var centerX = globalViewport.x + globalViewport.width / 2;
  94374. var centerY = globalViewport.y + globalViewport.height / 2;
  94375. var distX = centerX - this._positionX;
  94376. var distY = centerY - this._positionY;
  94377. // Effects
  94378. engine.enableEffect(this._effect);
  94379. engine.setState(false);
  94380. engine.setDepthBuffer(false);
  94381. // VBOs
  94382. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  94383. // Flares
  94384. for (var index = 0; index < this.lensFlares.length; index++) {
  94385. var flare = this.lensFlares[index];
  94386. engine.setAlphaMode(flare.alphaMode);
  94387. var x = centerX - (distX * flare.position);
  94388. var y = centerY - (distY * flare.position);
  94389. var cw = flare.size;
  94390. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  94391. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  94392. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  94393. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  94394. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  94395. // Texture
  94396. this._effect.setTexture("textureSampler", flare.texture);
  94397. // Color
  94398. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  94399. // Draw order
  94400. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94401. }
  94402. engine.setDepthBuffer(true);
  94403. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  94404. return true;
  94405. };
  94406. /**
  94407. * Dispose and release the lens flare with its associated resources.
  94408. */
  94409. LensFlareSystem.prototype.dispose = function () {
  94410. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94411. if (vertexBuffer) {
  94412. vertexBuffer.dispose();
  94413. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94414. }
  94415. if (this._indexBuffer) {
  94416. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94417. this._indexBuffer = null;
  94418. }
  94419. while (this.lensFlares.length) {
  94420. this.lensFlares[0].dispose();
  94421. }
  94422. // Remove from scene
  94423. var index = this._scene.lensFlareSystems.indexOf(this);
  94424. this._scene.lensFlareSystems.splice(index, 1);
  94425. };
  94426. /**
  94427. * Parse a lens flare system from a JSON repressentation
  94428. * @param parsedLensFlareSystem Define the JSON to parse
  94429. * @param scene Define the scene the parsed system should be instantiated in
  94430. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  94431. * @returns the parsed system
  94432. */
  94433. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  94434. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  94435. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  94436. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  94437. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  94438. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  94439. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  94440. var parsedFlare = parsedLensFlareSystem.flares[index];
  94441. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  94442. }
  94443. return lensFlareSystem;
  94444. };
  94445. /**
  94446. * Serialize the current Lens Flare System into a JSON representation.
  94447. * @returns the serialized JSON
  94448. */
  94449. LensFlareSystem.prototype.serialize = function () {
  94450. var serializationObject = {};
  94451. serializationObject.id = this.id;
  94452. serializationObject.name = this.name;
  94453. serializationObject.emitterId = this.getEmitter().id;
  94454. serializationObject.borderLimit = this.borderLimit;
  94455. serializationObject.flares = [];
  94456. for (var index = 0; index < this.lensFlares.length; index++) {
  94457. var flare = this.lensFlares[index];
  94458. serializationObject.flares.push({
  94459. size: flare.size,
  94460. position: flare.position,
  94461. color: flare.color.asArray(),
  94462. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  94463. });
  94464. }
  94465. return serializationObject;
  94466. };
  94467. return LensFlareSystem;
  94468. }());
  94469. BABYLON.LensFlareSystem = LensFlareSystem;
  94470. })(BABYLON || (BABYLON = {}));
  94471. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  94472. var BABYLON;
  94473. (function (BABYLON) {
  94474. /**
  94475. * This is a holder class for the physics joint created by the physics plugin
  94476. * It holds a set of functions to control the underlying joint
  94477. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94478. */
  94479. var PhysicsJoint = /** @class */ (function () {
  94480. /**
  94481. * Initializes the physics joint
  94482. * @param type The type of the physics joint
  94483. * @param jointData The data for the physics joint
  94484. */
  94485. function PhysicsJoint(
  94486. /**
  94487. * The type of the physics joint
  94488. */
  94489. type,
  94490. /**
  94491. * The data for the physics joint
  94492. */
  94493. jointData) {
  94494. this.type = type;
  94495. this.jointData = jointData;
  94496. jointData.nativeParams = jointData.nativeParams || {};
  94497. }
  94498. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  94499. /**
  94500. * Gets the physics joint
  94501. */
  94502. get: function () {
  94503. return this._physicsJoint;
  94504. },
  94505. /**
  94506. * Sets the physics joint
  94507. */
  94508. set: function (newJoint) {
  94509. if (this._physicsJoint) {
  94510. //remove from the wolrd
  94511. }
  94512. this._physicsJoint = newJoint;
  94513. },
  94514. enumerable: true,
  94515. configurable: true
  94516. });
  94517. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  94518. /**
  94519. * Sets the physics plugin
  94520. */
  94521. set: function (physicsPlugin) {
  94522. this._physicsPlugin = physicsPlugin;
  94523. },
  94524. enumerable: true,
  94525. configurable: true
  94526. });
  94527. /**
  94528. * Execute a function that is physics-plugin specific.
  94529. * @param {Function} func the function that will be executed.
  94530. * It accepts two parameters: the physics world and the physics joint
  94531. */
  94532. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  94533. func(this._physicsPlugin.world, this._physicsJoint);
  94534. };
  94535. //TODO check if the native joints are the same
  94536. //Joint Types
  94537. /**
  94538. * Distance-Joint type
  94539. */
  94540. PhysicsJoint.DistanceJoint = 0;
  94541. /**
  94542. * Hinge-Joint type
  94543. */
  94544. PhysicsJoint.HingeJoint = 1;
  94545. /**
  94546. * Ball-and-Socket joint type
  94547. */
  94548. PhysicsJoint.BallAndSocketJoint = 2;
  94549. /**
  94550. * Wheel-Joint type
  94551. */
  94552. PhysicsJoint.WheelJoint = 3;
  94553. /**
  94554. * Slider-Joint type
  94555. */
  94556. PhysicsJoint.SliderJoint = 4;
  94557. //OIMO
  94558. /**
  94559. * Prismatic-Joint type
  94560. */
  94561. PhysicsJoint.PrismaticJoint = 5;
  94562. //
  94563. /**
  94564. * Universal-Joint type
  94565. * ENERGY FTW! (compare with this - @see http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  94566. */
  94567. PhysicsJoint.UniversalJoint = 6;
  94568. /**
  94569. * Hinge-Joint 2 type
  94570. */
  94571. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  94572. //Cannon
  94573. /**
  94574. * Point to Point Joint type. Similar to a Ball-Joint. Different in parameters
  94575. */
  94576. PhysicsJoint.PointToPointJoint = 8;
  94577. //Cannon only at the moment
  94578. /**
  94579. * Spring-Joint type
  94580. */
  94581. PhysicsJoint.SpringJoint = 9;
  94582. /**
  94583. * Lock-Joint type
  94584. */
  94585. PhysicsJoint.LockJoint = 10;
  94586. return PhysicsJoint;
  94587. }());
  94588. BABYLON.PhysicsJoint = PhysicsJoint;
  94589. /**
  94590. * A class representing a physics distance joint
  94591. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94592. */
  94593. var DistanceJoint = /** @class */ (function (_super) {
  94594. __extends(DistanceJoint, _super);
  94595. /**
  94596. *
  94597. * @param jointData The data for the Distance-Joint
  94598. */
  94599. function DistanceJoint(jointData) {
  94600. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  94601. }
  94602. /**
  94603. * Update the predefined distance.
  94604. * @param maxDistance The maximum preferred distance
  94605. * @param minDistance The minimum preferred distance
  94606. */
  94607. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  94608. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  94609. };
  94610. return DistanceJoint;
  94611. }(PhysicsJoint));
  94612. BABYLON.DistanceJoint = DistanceJoint;
  94613. /**
  94614. * Represents a Motor-Enabled Joint
  94615. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94616. */
  94617. var MotorEnabledJoint = /** @class */ (function (_super) {
  94618. __extends(MotorEnabledJoint, _super);
  94619. /**
  94620. * Initializes the Motor-Enabled Joint
  94621. * @param type The type of the joint
  94622. * @param jointData The physica joint data for the joint
  94623. */
  94624. function MotorEnabledJoint(type, jointData) {
  94625. return _super.call(this, type, jointData) || this;
  94626. }
  94627. /**
  94628. * Set the motor values.
  94629. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94630. * @param force the force to apply
  94631. * @param maxForce max force for this motor.
  94632. */
  94633. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  94634. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  94635. };
  94636. /**
  94637. * Set the motor's limits.
  94638. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94639. * @param upperLimit The upper limit of the motor
  94640. * @param lowerLimit The lower limit of the motor
  94641. */
  94642. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  94643. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  94644. };
  94645. return MotorEnabledJoint;
  94646. }(PhysicsJoint));
  94647. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  94648. /**
  94649. * This class represents a single physics Hinge-Joint
  94650. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94651. */
  94652. var HingeJoint = /** @class */ (function (_super) {
  94653. __extends(HingeJoint, _super);
  94654. /**
  94655. * Initializes the Hinge-Joint
  94656. * @param jointData The joint data for the Hinge-Joint
  94657. */
  94658. function HingeJoint(jointData) {
  94659. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  94660. }
  94661. /**
  94662. * Set the motor values.
  94663. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94664. * @param {number} force the force to apply
  94665. * @param {number} maxForce max force for this motor.
  94666. */
  94667. HingeJoint.prototype.setMotor = function (force, maxForce) {
  94668. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  94669. };
  94670. /**
  94671. * Set the motor's limits.
  94672. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94673. * @param upperLimit The upper limit of the motor
  94674. * @param lowerLimit The lower limit of the motor
  94675. */
  94676. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  94677. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  94678. };
  94679. return HingeJoint;
  94680. }(MotorEnabledJoint));
  94681. BABYLON.HingeJoint = HingeJoint;
  94682. /**
  94683. * This class represents a dual hinge physics joint (same as wheel joint)
  94684. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94685. */
  94686. var Hinge2Joint = /** @class */ (function (_super) {
  94687. __extends(Hinge2Joint, _super);
  94688. /**
  94689. * Initializes the Hinge2-Joint
  94690. * @param jointData The joint data for the Hinge2-Joint
  94691. */
  94692. function Hinge2Joint(jointData) {
  94693. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  94694. }
  94695. /**
  94696. * Set the motor values.
  94697. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94698. * @param {number} force the force to apply
  94699. * @param {number} maxForce max force for this motor.
  94700. * @param {motorIndex} the motor's index, 0 or 1.
  94701. */
  94702. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  94703. if (motorIndex === void 0) { motorIndex = 0; }
  94704. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  94705. };
  94706. /**
  94707. * Set the motor limits.
  94708. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94709. * @param {number} upperLimit the upper limit
  94710. * @param {number} lowerLimit lower limit
  94711. * @param {motorIndex} the motor's index, 0 or 1.
  94712. */
  94713. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  94714. if (motorIndex === void 0) { motorIndex = 0; }
  94715. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  94716. };
  94717. return Hinge2Joint;
  94718. }(MotorEnabledJoint));
  94719. BABYLON.Hinge2Joint = Hinge2Joint;
  94720. })(BABYLON || (BABYLON = {}));
  94721. //# sourceMappingURL=babylon.physicsJoint.js.map
  94722. var BABYLON;
  94723. (function (BABYLON) {
  94724. /**
  94725. * Represents a physics imposter
  94726. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94727. */
  94728. var PhysicsImpostor = /** @class */ (function () {
  94729. /**
  94730. * Initializes the physics imposter
  94731. * @param object The physics-enabled object used as the physics imposter
  94732. * @param type The type of the physics imposter
  94733. * @param _options The options for the physics imposter
  94734. * @param _scene The Babylon scene
  94735. */
  94736. function PhysicsImpostor(
  94737. /**
  94738. * The physics-enabled object used as the physics imposter
  94739. */
  94740. object,
  94741. /**
  94742. * The type of the physics imposter
  94743. */
  94744. type, _options, _scene) {
  94745. if (_options === void 0) { _options = { mass: 0 }; }
  94746. var _this = this;
  94747. this.object = object;
  94748. this.type = type;
  94749. this._options = _options;
  94750. this._scene = _scene;
  94751. this._bodyUpdateRequired = false;
  94752. this._onBeforePhysicsStepCallbacks = new Array();
  94753. this._onAfterPhysicsStepCallbacks = new Array();
  94754. this._onPhysicsCollideCallbacks = [];
  94755. this._deltaPosition = BABYLON.Vector3.Zero();
  94756. this._isDisposed = false;
  94757. //temp variables for parent rotation calculations
  94758. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  94759. this._tmpQuat = new BABYLON.Quaternion();
  94760. this._tmpQuat2 = new BABYLON.Quaternion();
  94761. /**
  94762. * this function is executed by the physics engine.
  94763. */
  94764. this.beforeStep = function () {
  94765. if (!_this._physicsEngine) {
  94766. return;
  94767. }
  94768. _this.object.translate(_this._deltaPosition, -1);
  94769. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  94770. _this.object.computeWorldMatrix(false);
  94771. if (_this.object.parent && _this.object.rotationQuaternion) {
  94772. _this.getParentsRotation();
  94773. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  94774. }
  94775. else {
  94776. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  94777. }
  94778. if (!_this._options.disableBidirectionalTransformation) {
  94779. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  94780. }
  94781. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  94782. func(_this);
  94783. });
  94784. };
  94785. /**
  94786. * this function is executed by the physics engine
  94787. */
  94788. this.afterStep = function () {
  94789. if (!_this._physicsEngine) {
  94790. return;
  94791. }
  94792. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  94793. func(_this);
  94794. });
  94795. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  94796. // object has now its world rotation. needs to be converted to local.
  94797. if (_this.object.parent && _this.object.rotationQuaternion) {
  94798. _this.getParentsRotation();
  94799. _this._tmpQuat.conjugateInPlace();
  94800. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  94801. }
  94802. // take the position set and make it the absolute position of this object.
  94803. _this.object.setAbsolutePosition(_this.object.position);
  94804. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  94805. _this.object.translate(_this._deltaPosition, 1);
  94806. };
  94807. /**
  94808. * Legacy collision detection event support
  94809. */
  94810. this.onCollideEvent = null;
  94811. /**
  94812. * event and body object due to cannon's event-based architecture.
  94813. */
  94814. this.onCollide = function (e) {
  94815. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  94816. return;
  94817. }
  94818. if (!_this._physicsEngine) {
  94819. return;
  94820. }
  94821. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  94822. if (otherImpostor) {
  94823. // Legacy collision detection event support
  94824. if (_this.onCollideEvent) {
  94825. _this.onCollideEvent(_this, otherImpostor);
  94826. }
  94827. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  94828. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  94829. }).forEach(function (obj) {
  94830. obj.callback(_this, otherImpostor);
  94831. });
  94832. }
  94833. };
  94834. //sanity check!
  94835. if (!this.object) {
  94836. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  94837. return;
  94838. }
  94839. //legacy support for old syntax.
  94840. if (!this._scene && object.getScene) {
  94841. this._scene = object.getScene();
  94842. }
  94843. if (!this._scene) {
  94844. return;
  94845. }
  94846. this._physicsEngine = this._scene.getPhysicsEngine();
  94847. if (!this._physicsEngine) {
  94848. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  94849. }
  94850. else {
  94851. //set the object's quaternion, if not set
  94852. if (!this.object.rotationQuaternion) {
  94853. if (this.object.rotation) {
  94854. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  94855. }
  94856. else {
  94857. this.object.rotationQuaternion = new BABYLON.Quaternion();
  94858. }
  94859. }
  94860. //default options params
  94861. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  94862. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  94863. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  94864. this._joints = [];
  94865. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  94866. if (!this.object.parent || this._options.ignoreParent) {
  94867. this._init();
  94868. }
  94869. else if (this.object.parent.physicsImpostor) {
  94870. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  94871. }
  94872. }
  94873. }
  94874. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  94875. /**
  94876. * Specifies if the physics imposter is disposed
  94877. */
  94878. get: function () {
  94879. return this._isDisposed;
  94880. },
  94881. enumerable: true,
  94882. configurable: true
  94883. });
  94884. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  94885. /**
  94886. * Gets the mass of the physics imposter
  94887. */
  94888. get: function () {
  94889. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  94890. },
  94891. set: function (value) {
  94892. this.setMass(value);
  94893. },
  94894. enumerable: true,
  94895. configurable: true
  94896. });
  94897. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  94898. /**
  94899. * Gets the coefficient of friction
  94900. */
  94901. get: function () {
  94902. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  94903. },
  94904. /**
  94905. * Sets the coefficient of friction
  94906. */
  94907. set: function (value) {
  94908. if (!this._physicsEngine) {
  94909. return;
  94910. }
  94911. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  94912. },
  94913. enumerable: true,
  94914. configurable: true
  94915. });
  94916. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  94917. /**
  94918. * Gets the coefficient of restitution
  94919. */
  94920. get: function () {
  94921. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  94922. },
  94923. /**
  94924. * Sets the coefficient of restitution
  94925. */
  94926. set: function (value) {
  94927. if (!this._physicsEngine) {
  94928. return;
  94929. }
  94930. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  94931. },
  94932. enumerable: true,
  94933. configurable: true
  94934. });
  94935. /**
  94936. * This function will completly initialize this impostor.
  94937. * It will create a new body - but only if this mesh has no parent.
  94938. * If it has, this impostor will not be used other than to define the impostor
  94939. * of the child mesh.
  94940. * @hidden
  94941. */
  94942. PhysicsImpostor.prototype._init = function () {
  94943. if (!this._physicsEngine) {
  94944. return;
  94945. }
  94946. this._physicsEngine.removeImpostor(this);
  94947. this.physicsBody = null;
  94948. this._parent = this._parent || this._getPhysicsParent();
  94949. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  94950. this._physicsEngine.addImpostor(this);
  94951. }
  94952. };
  94953. PhysicsImpostor.prototype._getPhysicsParent = function () {
  94954. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  94955. var parentMesh = this.object.parent;
  94956. return parentMesh.physicsImpostor;
  94957. }
  94958. return null;
  94959. };
  94960. /**
  94961. * Should a new body be generated.
  94962. * @returns boolean specifying if body initialization is required
  94963. */
  94964. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  94965. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  94966. };
  94967. /**
  94968. * Sets the updated scaling
  94969. * @param updated Specifies if the scaling is updated
  94970. */
  94971. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  94972. this.forceUpdate();
  94973. };
  94974. /**
  94975. * Force a regeneration of this or the parent's impostor's body.
  94976. * Use under cautious - This will remove all joints already implemented.
  94977. */
  94978. PhysicsImpostor.prototype.forceUpdate = function () {
  94979. this._init();
  94980. if (this.parent && !this._options.ignoreParent) {
  94981. this.parent.forceUpdate();
  94982. }
  94983. };
  94984. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  94985. /*public get mesh(): AbstractMesh {
  94986. return this._mesh;
  94987. }*/
  94988. /**
  94989. * Gets the body that holds this impostor. Either its own, or its parent.
  94990. */
  94991. get: function () {
  94992. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  94993. },
  94994. /**
  94995. * Set the physics body. Used mainly by the physics engine/plugin
  94996. */
  94997. set: function (physicsBody) {
  94998. if (this._physicsBody && this._physicsEngine) {
  94999. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  95000. }
  95001. this._physicsBody = physicsBody;
  95002. this.resetUpdateFlags();
  95003. },
  95004. enumerable: true,
  95005. configurable: true
  95006. });
  95007. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  95008. /**
  95009. * Get the parent of the physics imposter
  95010. * @returns Physics imposter or null
  95011. */
  95012. get: function () {
  95013. return !this._options.ignoreParent && this._parent ? this._parent : null;
  95014. },
  95015. /**
  95016. * Sets the parent of the physics imposter
  95017. */
  95018. set: function (value) {
  95019. this._parent = value;
  95020. },
  95021. enumerable: true,
  95022. configurable: true
  95023. });
  95024. /**
  95025. * Resets the update flags
  95026. */
  95027. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  95028. this._bodyUpdateRequired = false;
  95029. };
  95030. /**
  95031. * Gets the object extend size
  95032. * @returns the object extend size
  95033. */
  95034. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  95035. if (this.object.getBoundingInfo) {
  95036. var q = this.object.rotationQuaternion;
  95037. //reset rotation
  95038. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  95039. //calculate the world matrix with no rotation
  95040. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  95041. var boundingInfo = this.object.getBoundingInfo();
  95042. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  95043. //bring back the rotation
  95044. this.object.rotationQuaternion = q;
  95045. //calculate the world matrix with the new rotation
  95046. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  95047. return size;
  95048. }
  95049. else {
  95050. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  95051. }
  95052. };
  95053. /**
  95054. * Gets the object center
  95055. * @returns The object center
  95056. */
  95057. PhysicsImpostor.prototype.getObjectCenter = function () {
  95058. if (this.object.getBoundingInfo) {
  95059. var boundingInfo = this.object.getBoundingInfo();
  95060. return boundingInfo.boundingBox.centerWorld;
  95061. }
  95062. else {
  95063. return this.object.position;
  95064. }
  95065. };
  95066. /**
  95067. * Get a specific parametes from the options parameter
  95068. * @param paramName The object parameter name
  95069. * @returns The object parameter
  95070. */
  95071. PhysicsImpostor.prototype.getParam = function (paramName) {
  95072. return this._options[paramName];
  95073. };
  95074. /**
  95075. * Sets a specific parameter in the options given to the physics plugin
  95076. * @param paramName The parameter name
  95077. * @param value The value of the parameter
  95078. */
  95079. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  95080. this._options[paramName] = value;
  95081. this._bodyUpdateRequired = true;
  95082. };
  95083. /**
  95084. * Specifically change the body's mass option. Won't recreate the physics body object
  95085. * @param mass The mass of the physics imposter
  95086. */
  95087. PhysicsImpostor.prototype.setMass = function (mass) {
  95088. if (this.getParam("mass") !== mass) {
  95089. this.setParam("mass", mass);
  95090. }
  95091. if (this._physicsEngine) {
  95092. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  95093. }
  95094. };
  95095. /**
  95096. * Gets the linear velocity
  95097. * @returns linear velocity or null
  95098. */
  95099. PhysicsImpostor.prototype.getLinearVelocity = function () {
  95100. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  95101. };
  95102. /**
  95103. * Sets the linear velocity
  95104. * @param velocity linear velocity or null
  95105. */
  95106. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  95107. if (this._physicsEngine) {
  95108. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  95109. }
  95110. };
  95111. /**
  95112. * Gets the angular velocity
  95113. * @returns angular velocity or null
  95114. */
  95115. PhysicsImpostor.prototype.getAngularVelocity = function () {
  95116. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  95117. };
  95118. /**
  95119. * Sets the angular velocity
  95120. * @param velocity The velocity or null
  95121. */
  95122. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  95123. if (this._physicsEngine) {
  95124. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  95125. }
  95126. };
  95127. /**
  95128. * Execute a function with the physics plugin native code
  95129. * Provide a function the will have two variables - the world object and the physics body object
  95130. * @param func The function to execute with the physics plugin native code
  95131. */
  95132. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  95133. if (this._physicsEngine) {
  95134. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  95135. }
  95136. };
  95137. /**
  95138. * Register a function that will be executed before the physics world is stepping forward
  95139. * @param func The function to execute before the physics world is stepped forward
  95140. */
  95141. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  95142. this._onBeforePhysicsStepCallbacks.push(func);
  95143. };
  95144. /**
  95145. * Unregister a function that will be executed before the physics world is stepping forward
  95146. * @param func The function to execute before the physics world is stepped forward
  95147. */
  95148. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  95149. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  95150. if (index > -1) {
  95151. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  95152. }
  95153. else {
  95154. BABYLON.Tools.Warn("Function to remove was not found");
  95155. }
  95156. };
  95157. /**
  95158. * Register a function that will be executed after the physics step
  95159. * @param func The function to execute after physics step
  95160. */
  95161. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  95162. this._onAfterPhysicsStepCallbacks.push(func);
  95163. };
  95164. /**
  95165. * Unregisters a function that will be executed after the physics step
  95166. * @param func The function to execute after physics step
  95167. */
  95168. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  95169. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  95170. if (index > -1) {
  95171. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  95172. }
  95173. else {
  95174. BABYLON.Tools.Warn("Function to remove was not found");
  95175. }
  95176. };
  95177. /**
  95178. * register a function that will be executed when this impostor collides against a different body
  95179. * @param collideAgainst Physics imposter, or array of physics imposters to collide against
  95180. * @param func Callback that is executed on collision
  95181. */
  95182. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  95183. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  95184. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  95185. };
  95186. /**
  95187. * Unregisters the physics imposter on contact
  95188. * @param collideAgainst The physics object to collide against
  95189. * @param func Callback to execute on collision
  95190. */
  95191. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  95192. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  95193. var index = -1;
  95194. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  95195. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  95196. // chcek the arrays match
  95197. var sameList = cbDef.otherImpostors.every(function (impostor) {
  95198. return collidedAgainstList.indexOf(impostor) > -1;
  95199. });
  95200. if (sameList) {
  95201. index = idx;
  95202. }
  95203. return sameList;
  95204. }
  95205. return false;
  95206. });
  95207. if (found) {
  95208. this._onPhysicsCollideCallbacks.splice(index, 1);
  95209. }
  95210. else {
  95211. BABYLON.Tools.Warn("Function to remove was not found");
  95212. }
  95213. };
  95214. /**
  95215. * Get the parent rotation
  95216. * @returns The parent rotation
  95217. */
  95218. PhysicsImpostor.prototype.getParentsRotation = function () {
  95219. var parent = this.object.parent;
  95220. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  95221. while (parent) {
  95222. if (parent.rotationQuaternion) {
  95223. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  95224. }
  95225. else {
  95226. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  95227. }
  95228. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  95229. parent = parent.parent;
  95230. }
  95231. return this._tmpQuat;
  95232. };
  95233. /**
  95234. * Apply a force
  95235. * @param force The force to apply
  95236. * @param contactPoint The contact point for the force
  95237. * @returns The physics imposter
  95238. */
  95239. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  95240. if (this._physicsEngine) {
  95241. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  95242. }
  95243. return this;
  95244. };
  95245. /**
  95246. * Apply an impulse
  95247. * @param force The impulse force
  95248. * @param contactPoint The contact point for the impulse force
  95249. * @returns The physics imposter
  95250. */
  95251. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  95252. if (this._physicsEngine) {
  95253. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  95254. }
  95255. return this;
  95256. };
  95257. /**
  95258. * A help function to create a joint
  95259. * @param otherImpostor A physics imposter used to create a joint
  95260. * @param jointType The type of joint
  95261. * @param jointData The data for the joint
  95262. * @returns The physics imposter
  95263. */
  95264. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  95265. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  95266. this.addJoint(otherImpostor, joint);
  95267. return this;
  95268. };
  95269. /**
  95270. * Add a joint to this impostor with a different impostor
  95271. * @param otherImpostor A physics imposter used to add a joint
  95272. * @param joint The joint to add
  95273. * @returns The physics imposter
  95274. */
  95275. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  95276. this._joints.push({
  95277. otherImpostor: otherImpostor,
  95278. joint: joint
  95279. });
  95280. if (this._physicsEngine) {
  95281. this._physicsEngine.addJoint(this, otherImpostor, joint);
  95282. }
  95283. return this;
  95284. };
  95285. /**
  95286. * Will keep this body still, in a sleep mode.
  95287. * @returns the physics imposter
  95288. */
  95289. PhysicsImpostor.prototype.sleep = function () {
  95290. if (this._physicsEngine) {
  95291. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  95292. }
  95293. return this;
  95294. };
  95295. /**
  95296. * Wake the body up.
  95297. * @returns The physics imposter
  95298. */
  95299. PhysicsImpostor.prototype.wakeUp = function () {
  95300. if (this._physicsEngine) {
  95301. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  95302. }
  95303. return this;
  95304. };
  95305. /**
  95306. * Clones the physics imposter
  95307. * @param newObject The physics imposter clones to this physics-enabled object
  95308. * @returns A nullable physics imposter
  95309. */
  95310. PhysicsImpostor.prototype.clone = function (newObject) {
  95311. if (!newObject) {
  95312. return null;
  95313. }
  95314. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  95315. };
  95316. /**
  95317. * Disposes the physics imposter
  95318. */
  95319. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  95320. var _this = this;
  95321. //no dispose if no physics engine is available.
  95322. if (!this._physicsEngine) {
  95323. return;
  95324. }
  95325. this._joints.forEach(function (j) {
  95326. if (_this._physicsEngine) {
  95327. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  95328. }
  95329. });
  95330. //dispose the physics body
  95331. this._physicsEngine.removeImpostor(this);
  95332. if (this.parent) {
  95333. this.parent.forceUpdate();
  95334. }
  95335. else {
  95336. /*this._object.getChildMeshes().forEach(function(mesh) {
  95337. if (mesh.physicsImpostor) {
  95338. if (disposeChildren) {
  95339. mesh.physicsImpostor.dispose();
  95340. mesh.physicsImpostor = null;
  95341. }
  95342. }
  95343. })*/
  95344. }
  95345. this._isDisposed = true;
  95346. };
  95347. /**
  95348. * Sets the delta position
  95349. * @param position The delta position amount
  95350. */
  95351. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  95352. this._deltaPosition.copyFrom(position);
  95353. };
  95354. /**
  95355. * Sets the delta rotation
  95356. * @param rotation The delta rotation amount
  95357. */
  95358. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  95359. if (!this._deltaRotation) {
  95360. this._deltaRotation = new BABYLON.Quaternion();
  95361. }
  95362. this._deltaRotation.copyFrom(rotation);
  95363. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  95364. };
  95365. /**
  95366. * Gets the box size of the physics imposter and stores the result in the input parameter
  95367. * @param result Stores the box size
  95368. * @returns The physics imposter
  95369. */
  95370. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  95371. if (this._physicsEngine) {
  95372. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  95373. }
  95374. return this;
  95375. };
  95376. /**
  95377. * Gets the radius of the physics imposter
  95378. * @returns Radius of the physics imposter
  95379. */
  95380. PhysicsImpostor.prototype.getRadius = function () {
  95381. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  95382. };
  95383. /**
  95384. * Sync a bone with this impostor
  95385. * @param bone The bone to sync to the impostor.
  95386. * @param boneMesh The mesh that the bone is influencing.
  95387. * @param jointPivot The pivot of the joint / bone in local space.
  95388. * @param distToJoint Optional distance from the impostor to the joint.
  95389. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  95390. */
  95391. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  95392. var tempVec = PhysicsImpostor._tmpVecs[0];
  95393. var mesh = this.object;
  95394. if (mesh.rotationQuaternion) {
  95395. if (adjustRotation) {
  95396. var tempQuat = PhysicsImpostor._tmpQuat;
  95397. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  95398. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  95399. }
  95400. else {
  95401. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  95402. }
  95403. }
  95404. tempVec.x = 0;
  95405. tempVec.y = 0;
  95406. tempVec.z = 0;
  95407. if (jointPivot) {
  95408. tempVec.x = jointPivot.x;
  95409. tempVec.y = jointPivot.y;
  95410. tempVec.z = jointPivot.z;
  95411. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  95412. if (distToJoint === undefined || distToJoint === null) {
  95413. distToJoint = jointPivot.length();
  95414. }
  95415. tempVec.x *= distToJoint;
  95416. tempVec.y *= distToJoint;
  95417. tempVec.z *= distToJoint;
  95418. }
  95419. if (bone.getParent()) {
  95420. tempVec.addInPlace(mesh.getAbsolutePosition());
  95421. bone.setAbsolutePosition(tempVec, boneMesh);
  95422. }
  95423. else {
  95424. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  95425. boneMesh.position.x -= tempVec.x;
  95426. boneMesh.position.y -= tempVec.y;
  95427. boneMesh.position.z -= tempVec.z;
  95428. }
  95429. };
  95430. /**
  95431. * Sync impostor to a bone
  95432. * @param bone The bone that the impostor will be synced to.
  95433. * @param boneMesh The mesh that the bone is influencing.
  95434. * @param jointPivot The pivot of the joint / bone in local space.
  95435. * @param distToJoint Optional distance from the impostor to the joint.
  95436. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  95437. * @param boneAxis Optional vector3 axis the bone is aligned with
  95438. */
  95439. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  95440. var mesh = this.object;
  95441. if (mesh.rotationQuaternion) {
  95442. if (adjustRotation) {
  95443. var tempQuat = PhysicsImpostor._tmpQuat;
  95444. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  95445. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  95446. }
  95447. else {
  95448. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  95449. }
  95450. }
  95451. var pos = PhysicsImpostor._tmpVecs[0];
  95452. var boneDir = PhysicsImpostor._tmpVecs[1];
  95453. if (!boneAxis) {
  95454. boneAxis = PhysicsImpostor._tmpVecs[2];
  95455. boneAxis.x = 0;
  95456. boneAxis.y = 1;
  95457. boneAxis.z = 0;
  95458. }
  95459. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  95460. bone.getAbsolutePositionToRef(boneMesh, pos);
  95461. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  95462. distToJoint = jointPivot.length();
  95463. }
  95464. if (distToJoint !== undefined && distToJoint !== null) {
  95465. pos.x += boneDir.x * distToJoint;
  95466. pos.y += boneDir.y * distToJoint;
  95467. pos.z += boneDir.z * distToJoint;
  95468. }
  95469. mesh.setAbsolutePosition(pos);
  95470. };
  95471. /**
  95472. * The default object size of the imposter
  95473. */
  95474. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  95475. /**
  95476. * The identity quaternion of the imposter
  95477. */
  95478. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  95479. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  95480. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  95481. //Impostor types
  95482. /**
  95483. * No-Imposter type
  95484. */
  95485. PhysicsImpostor.NoImpostor = 0;
  95486. /**
  95487. * Sphere-Imposter type
  95488. */
  95489. PhysicsImpostor.SphereImpostor = 1;
  95490. /**
  95491. * Box-Imposter type
  95492. */
  95493. PhysicsImpostor.BoxImpostor = 2;
  95494. /**
  95495. * Plane-Imposter type
  95496. */
  95497. PhysicsImpostor.PlaneImpostor = 3;
  95498. /**
  95499. * Mesh-imposter type
  95500. */
  95501. PhysicsImpostor.MeshImpostor = 4;
  95502. /**
  95503. * Cylinder-Imposter type
  95504. */
  95505. PhysicsImpostor.CylinderImpostor = 7;
  95506. /**
  95507. * Particle-Imposter type
  95508. */
  95509. PhysicsImpostor.ParticleImpostor = 8;
  95510. /**
  95511. * Heightmap-Imposter type
  95512. */
  95513. PhysicsImpostor.HeightmapImpostor = 9;
  95514. return PhysicsImpostor;
  95515. }());
  95516. BABYLON.PhysicsImpostor = PhysicsImpostor;
  95517. })(BABYLON || (BABYLON = {}));
  95518. //# sourceMappingURL=babylon.physicsImpostor.js.map
  95519. var BABYLON;
  95520. (function (BABYLON) {
  95521. /**
  95522. * Class used to control physics engine
  95523. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  95524. */
  95525. var PhysicsEngine = /** @class */ (function () {
  95526. /**
  95527. * Creates a new Physics Engine
  95528. * @param gravity defines the gravity vector used by the simulation
  95529. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  95530. */
  95531. function PhysicsEngine(gravity, _physicsPlugin) {
  95532. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  95533. this._physicsPlugin = _physicsPlugin;
  95534. this._impostors = [];
  95535. this._joints = [];
  95536. if (!this._physicsPlugin.isSupported()) {
  95537. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  95538. + "Please make sure it is included.");
  95539. }
  95540. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  95541. this.setGravity(gravity);
  95542. this.setTimeStep();
  95543. }
  95544. /**
  95545. * Sets the gravity vector used by the simulation
  95546. * @param gravity defines the gravity vector to use
  95547. */
  95548. PhysicsEngine.prototype.setGravity = function (gravity) {
  95549. this.gravity = gravity;
  95550. this._physicsPlugin.setGravity(this.gravity);
  95551. };
  95552. /**
  95553. * Set the time step of the physics engine.
  95554. * Default is 1/60.
  95555. * To slow it down, enter 1/600 for example.
  95556. * To speed it up, 1/30
  95557. * @param newTimeStep defines the new timestep to apply to this world.
  95558. */
  95559. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  95560. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  95561. this._physicsPlugin.setTimeStep(newTimeStep);
  95562. };
  95563. /**
  95564. * Get the time step of the physics engine.
  95565. * @returns the current time step
  95566. */
  95567. PhysicsEngine.prototype.getTimeStep = function () {
  95568. return this._physicsPlugin.getTimeStep();
  95569. };
  95570. /**
  95571. * Release all resources
  95572. */
  95573. PhysicsEngine.prototype.dispose = function () {
  95574. this._impostors.forEach(function (impostor) {
  95575. impostor.dispose();
  95576. });
  95577. this._physicsPlugin.dispose();
  95578. };
  95579. /**
  95580. * Gets the name of the current physics plugin
  95581. * @returns the name of the plugin
  95582. */
  95583. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  95584. return this._physicsPlugin.name;
  95585. };
  95586. /**
  95587. * Adding a new impostor for the impostor tracking.
  95588. * This will be done by the impostor itself.
  95589. * @param impostor the impostor to add
  95590. */
  95591. PhysicsEngine.prototype.addImpostor = function (impostor) {
  95592. impostor.uniqueId = this._impostors.push(impostor);
  95593. //if no parent, generate the body
  95594. if (!impostor.parent) {
  95595. this._physicsPlugin.generatePhysicsBody(impostor);
  95596. }
  95597. };
  95598. /**
  95599. * Remove an impostor from the engine.
  95600. * This impostor and its mesh will not longer be updated by the physics engine.
  95601. * @param impostor the impostor to remove
  95602. */
  95603. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  95604. var index = this._impostors.indexOf(impostor);
  95605. if (index > -1) {
  95606. var removed = this._impostors.splice(index, 1);
  95607. //Is it needed?
  95608. if (removed.length) {
  95609. //this will also remove it from the world.
  95610. removed[0].physicsBody = null;
  95611. }
  95612. }
  95613. };
  95614. /**
  95615. * Add a joint to the physics engine
  95616. * @param mainImpostor defines the main impostor to which the joint is added.
  95617. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  95618. * @param joint defines the joint that will connect both impostors.
  95619. */
  95620. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  95621. var impostorJoint = {
  95622. mainImpostor: mainImpostor,
  95623. connectedImpostor: connectedImpostor,
  95624. joint: joint
  95625. };
  95626. joint.physicsPlugin = this._physicsPlugin;
  95627. this._joints.push(impostorJoint);
  95628. this._physicsPlugin.generateJoint(impostorJoint);
  95629. };
  95630. /**
  95631. * Removes a joint from the simulation
  95632. * @param mainImpostor defines the impostor used with the joint
  95633. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  95634. * @param joint defines the joint to remove
  95635. */
  95636. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  95637. var matchingJoints = this._joints.filter(function (impostorJoint) {
  95638. return (impostorJoint.connectedImpostor === connectedImpostor
  95639. && impostorJoint.joint === joint
  95640. && impostorJoint.mainImpostor === mainImpostor);
  95641. });
  95642. if (matchingJoints.length) {
  95643. this._physicsPlugin.removeJoint(matchingJoints[0]);
  95644. //TODO remove it from the list as well
  95645. }
  95646. };
  95647. /**
  95648. * Called by the scene. No need to call it.
  95649. * @param delta defines the timespam between frames
  95650. */
  95651. PhysicsEngine.prototype._step = function (delta) {
  95652. var _this = this;
  95653. //check if any mesh has no body / requires an update
  95654. this._impostors.forEach(function (impostor) {
  95655. if (impostor.isBodyInitRequired()) {
  95656. _this._physicsPlugin.generatePhysicsBody(impostor);
  95657. }
  95658. });
  95659. if (delta > 0.1) {
  95660. delta = 0.1;
  95661. }
  95662. else if (delta <= 0) {
  95663. delta = 1.0 / 60.0;
  95664. }
  95665. this._physicsPlugin.executeStep(delta, this._impostors);
  95666. };
  95667. /**
  95668. * Gets the current plugin used to run the simulation
  95669. * @returns current plugin
  95670. */
  95671. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  95672. return this._physicsPlugin;
  95673. };
  95674. /**
  95675. * Gets the list of physic impostors
  95676. * @returns an array of PhysicsImpostor
  95677. */
  95678. PhysicsEngine.prototype.getImpostors = function () {
  95679. return this._impostors;
  95680. };
  95681. /**
  95682. * Gets the impostor for a physics enabled object
  95683. * @param object defines the object impersonated by the impostor
  95684. * @returns the PhysicsImpostor or null if not found
  95685. */
  95686. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  95687. for (var i = 0; i < this._impostors.length; ++i) {
  95688. if (this._impostors[i].object === object) {
  95689. return this._impostors[i];
  95690. }
  95691. }
  95692. return null;
  95693. };
  95694. /**
  95695. * Gets the impostor for a physics body object
  95696. * @param body defines physics body used by the impostor
  95697. * @returns the PhysicsImpostor or null if not found
  95698. */
  95699. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  95700. for (var i = 0; i < this._impostors.length; ++i) {
  95701. if (this._impostors[i].physicsBody === body) {
  95702. return this._impostors[i];
  95703. }
  95704. }
  95705. return null;
  95706. };
  95707. /**
  95708. * Global value used to control the smallest number supported by the simulation
  95709. */
  95710. PhysicsEngine.Epsilon = 0.001;
  95711. return PhysicsEngine;
  95712. }());
  95713. BABYLON.PhysicsEngine = PhysicsEngine;
  95714. })(BABYLON || (BABYLON = {}));
  95715. //# sourceMappingURL=babylon.physicsEngine.js.map
  95716. var BABYLON;
  95717. (function (BABYLON) {
  95718. /**
  95719. * A helper for physics simulations
  95720. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95721. */
  95722. var PhysicsHelper = /** @class */ (function () {
  95723. /**
  95724. * Initializes the Physics helper
  95725. * @param scene Babylon.js scene
  95726. */
  95727. function PhysicsHelper(scene) {
  95728. this._scene = scene;
  95729. this._physicsEngine = this._scene.getPhysicsEngine();
  95730. if (!this._physicsEngine) {
  95731. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  95732. }
  95733. }
  95734. /**
  95735. * Applies a radial explosion impulse
  95736. * @param origin the origin of the explosion
  95737. * @param radius the explosion radius
  95738. * @param strength the explosion strength
  95739. * @param falloff possible options: Constant & Linear. Defaults to Constant
  95740. * @returns A physics radial explosion event, or null
  95741. */
  95742. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  95743. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95744. if (!this._physicsEngine) {
  95745. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  95746. return null;
  95747. }
  95748. var impostors = this._physicsEngine.getImpostors();
  95749. if (impostors.length === 0) {
  95750. return null;
  95751. }
  95752. var event = new PhysicsRadialExplosionEvent(this._scene);
  95753. impostors.forEach(function (impostor) {
  95754. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  95755. if (!impostorForceAndContactPoint) {
  95756. return;
  95757. }
  95758. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  95759. });
  95760. event.dispose(false);
  95761. return event;
  95762. };
  95763. /**
  95764. * Applies a radial explosion force
  95765. * @param origin the origin of the explosion
  95766. * @param radius the explosion radius
  95767. * @param strength the explosion strength
  95768. * @param falloff possible options: Constant & Linear. Defaults to Constant
  95769. * @returns A physics radial explosion event, or null
  95770. */
  95771. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  95772. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95773. if (!this._physicsEngine) {
  95774. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95775. return null;
  95776. }
  95777. var impostors = this._physicsEngine.getImpostors();
  95778. if (impostors.length === 0) {
  95779. return null;
  95780. }
  95781. var event = new PhysicsRadialExplosionEvent(this._scene);
  95782. impostors.forEach(function (impostor) {
  95783. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  95784. if (!impostorForceAndContactPoint) {
  95785. return;
  95786. }
  95787. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  95788. });
  95789. event.dispose(false);
  95790. return event;
  95791. };
  95792. /**
  95793. * Creates a gravitational field
  95794. * @param origin the origin of the explosion
  95795. * @param radius the explosion radius
  95796. * @param strength the explosion strength
  95797. * @param falloff possible options: Constant & Linear. Defaults to Constant
  95798. * @returns A physics gravitational field event, or null
  95799. */
  95800. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  95801. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95802. if (!this._physicsEngine) {
  95803. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95804. return null;
  95805. }
  95806. var impostors = this._physicsEngine.getImpostors();
  95807. if (impostors.length === 0) {
  95808. return null;
  95809. }
  95810. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  95811. event.dispose(false);
  95812. return event;
  95813. };
  95814. /**
  95815. * Creates a physics updraft event
  95816. * @param origin the origin of the updraft
  95817. * @param radius the radius of the updraft
  95818. * @param strength the strength of the updraft
  95819. * @param height the height of the updraft
  95820. * @param updraftMode possible options: Center & Perpendicular. Defaults to Center
  95821. * @returns A physics updraft event, or null
  95822. */
  95823. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  95824. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  95825. if (!this._physicsEngine) {
  95826. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95827. return null;
  95828. }
  95829. if (this._physicsEngine.getImpostors().length === 0) {
  95830. return null;
  95831. }
  95832. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  95833. event.dispose(false);
  95834. return event;
  95835. };
  95836. /**
  95837. * Creates a physics vortex event
  95838. * @param origin the of the vortex
  95839. * @param radius the radius of the vortex
  95840. * @param strength the strength of the vortex
  95841. * @param height the height of the vortex
  95842. * @returns a Physics vortex event, or null
  95843. * A physics vortex event or null
  95844. */
  95845. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  95846. if (!this._physicsEngine) {
  95847. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95848. return null;
  95849. }
  95850. if (this._physicsEngine.getImpostors().length === 0) {
  95851. return null;
  95852. }
  95853. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  95854. event.dispose(false);
  95855. return event;
  95856. };
  95857. return PhysicsHelper;
  95858. }());
  95859. BABYLON.PhysicsHelper = PhysicsHelper;
  95860. /**
  95861. * Represents a physics radial explosion event
  95862. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95863. */
  95864. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  95865. /**
  95866. * Initializes a radial explosioin event
  95867. * @param scene BabylonJS scene
  95868. */
  95869. function PhysicsRadialExplosionEvent(scene) {
  95870. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  95871. this._rays = [];
  95872. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  95873. this._scene = scene;
  95874. }
  95875. /**
  95876. * Returns the data related to the radial explosion event (sphere & rays).
  95877. * @returns The radial explosion event data
  95878. */
  95879. PhysicsRadialExplosionEvent.prototype.getData = function () {
  95880. this._dataFetched = true;
  95881. return {
  95882. sphere: this._sphere,
  95883. rays: this._rays,
  95884. };
  95885. };
  95886. /**
  95887. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  95888. * @param impostor A physics imposter
  95889. * @param origin the origin of the explosion
  95890. * @param radius the explosion radius
  95891. * @param strength the explosion strength
  95892. * @param falloff possible options: Constant & Linear
  95893. * @returns {Nullable<PhysicsForceAndContactPoint>} A physics force and contact point, or null
  95894. */
  95895. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  95896. if (impostor.mass === 0) {
  95897. return null;
  95898. }
  95899. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  95900. return null;
  95901. }
  95902. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  95903. return null;
  95904. }
  95905. var impostorObjectCenter = impostor.getObjectCenter();
  95906. var direction = impostorObjectCenter.subtract(origin);
  95907. var ray = new BABYLON.Ray(origin, direction, radius);
  95908. this._rays.push(ray);
  95909. var hit = ray.intersectsMesh(impostor.object);
  95910. var contactPoint = hit.pickedPoint;
  95911. if (!contactPoint) {
  95912. return null;
  95913. }
  95914. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  95915. if (distanceFromOrigin > radius) {
  95916. return null;
  95917. }
  95918. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  95919. ? strength
  95920. : strength * (1 - (distanceFromOrigin / radius));
  95921. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  95922. return { force: force, contactPoint: contactPoint };
  95923. };
  95924. /**
  95925. * Disposes the sphere.
  95926. * @param force Specifies if the sphere should be disposed by force
  95927. */
  95928. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  95929. var _this = this;
  95930. if (force === void 0) { force = true; }
  95931. if (force) {
  95932. this._sphere.dispose();
  95933. }
  95934. else {
  95935. setTimeout(function () {
  95936. if (!_this._dataFetched) {
  95937. _this._sphere.dispose();
  95938. }
  95939. }, 0);
  95940. }
  95941. };
  95942. /*** Helpers ***/
  95943. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  95944. if (!this._sphere) {
  95945. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  95946. this._sphere.isVisible = false;
  95947. }
  95948. };
  95949. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  95950. var impostorObject = impostor.object;
  95951. this._prepareSphere();
  95952. this._sphere.position = origin;
  95953. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  95954. this._sphere._updateBoundingInfo();
  95955. this._sphere.computeWorldMatrix(true);
  95956. return this._sphere.intersectsMesh(impostorObject, true);
  95957. };
  95958. return PhysicsRadialExplosionEvent;
  95959. }());
  95960. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  95961. /**
  95962. * Represents a gravitational field event
  95963. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95964. */
  95965. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  95966. /**
  95967. * Initializes the physics gravitational field event
  95968. * @param physicsHelper A physics helper
  95969. * @param scene BabylonJS scene
  95970. * @param origin The origin position of the gravitational field event
  95971. * @param radius The radius of the gravitational field event
  95972. * @param strength The strength of the gravitational field event
  95973. * @param falloff The falloff for the gravitational field event
  95974. */
  95975. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  95976. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95977. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  95978. this._physicsHelper = physicsHelper;
  95979. this._scene = scene;
  95980. this._origin = origin;
  95981. this._radius = radius;
  95982. this._strength = strength;
  95983. this._falloff = falloff;
  95984. this._tickCallback = this._tick.bind(this);
  95985. }
  95986. /**
  95987. * Returns the data related to the gravitational field event (sphere).
  95988. * @returns A gravitational field event
  95989. */
  95990. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  95991. this._dataFetched = true;
  95992. return {
  95993. sphere: this._sphere,
  95994. };
  95995. };
  95996. /**
  95997. * Enables the gravitational field.
  95998. */
  95999. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  96000. this._tickCallback.call(this);
  96001. this._scene.registerBeforeRender(this._tickCallback);
  96002. };
  96003. /**
  96004. * Disables the gravitational field.
  96005. */
  96006. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  96007. this._scene.unregisterBeforeRender(this._tickCallback);
  96008. };
  96009. /**
  96010. * Disposes the sphere.
  96011. * @param force The force to dispose from the gravitational field event
  96012. */
  96013. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  96014. var _this = this;
  96015. if (force === void 0) { force = true; }
  96016. if (force) {
  96017. this._sphere.dispose();
  96018. }
  96019. else {
  96020. setTimeout(function () {
  96021. if (!_this._dataFetched) {
  96022. _this._sphere.dispose();
  96023. }
  96024. }, 0);
  96025. }
  96026. };
  96027. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  96028. // Since the params won't change, we fetch the event only once
  96029. if (this._sphere) {
  96030. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  96031. }
  96032. else {
  96033. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  96034. if (radialExplosionEvent) {
  96035. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  96036. }
  96037. }
  96038. };
  96039. return PhysicsGravitationalFieldEvent;
  96040. }());
  96041. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  96042. /**
  96043. * Represents a physics updraft event
  96044. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96045. */
  96046. var PhysicsUpdraftEvent = /** @class */ (function () {
  96047. /**
  96048. * Initializes the physics updraft event
  96049. * @param _scene BabylonJS scene
  96050. * @param _origin The origin position of the updraft
  96051. * @param _radius The radius of the updraft
  96052. * @param _strength The strength of the updraft
  96053. * @param _height The height of the updraft
  96054. * @param _updraftMode The mode of the updraft
  96055. */
  96056. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  96057. this._scene = _scene;
  96058. this._origin = _origin;
  96059. this._radius = _radius;
  96060. this._strength = _strength;
  96061. this._height = _height;
  96062. this._updraftMode = _updraftMode;
  96063. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  96064. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  96065. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  96066. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  96067. this._physicsEngine = this._scene.getPhysicsEngine();
  96068. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  96069. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  96070. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  96071. this._originDirection = this._origin.subtract(this._originTop).normalize();
  96072. }
  96073. this._tickCallback = this._tick.bind(this);
  96074. }
  96075. /**
  96076. * Returns the data related to the updraft event (cylinder).
  96077. * @returns A physics updraft event
  96078. */
  96079. PhysicsUpdraftEvent.prototype.getData = function () {
  96080. this._dataFetched = true;
  96081. return {
  96082. cylinder: this._cylinder,
  96083. };
  96084. };
  96085. /**
  96086. * Enables the updraft.
  96087. */
  96088. PhysicsUpdraftEvent.prototype.enable = function () {
  96089. this._tickCallback.call(this);
  96090. this._scene.registerBeforeRender(this._tickCallback);
  96091. };
  96092. /**
  96093. * Disables the cortex.
  96094. */
  96095. PhysicsUpdraftEvent.prototype.disable = function () {
  96096. this._scene.unregisterBeforeRender(this._tickCallback);
  96097. };
  96098. /**
  96099. * Disposes the sphere.
  96100. * @param force Specifies if the updraft should be disposed by force
  96101. */
  96102. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  96103. var _this = this;
  96104. if (force === void 0) { force = true; }
  96105. if (force) {
  96106. this._cylinder.dispose();
  96107. }
  96108. else {
  96109. setTimeout(function () {
  96110. if (!_this._dataFetched) {
  96111. _this._cylinder.dispose();
  96112. }
  96113. }, 0);
  96114. }
  96115. };
  96116. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  96117. if (impostor.mass === 0) {
  96118. return null;
  96119. }
  96120. if (!this._intersectsWithCylinder(impostor)) {
  96121. return null;
  96122. }
  96123. var impostorObjectCenter = impostor.getObjectCenter();
  96124. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  96125. var direction = this._originDirection;
  96126. }
  96127. else {
  96128. var direction = impostorObjectCenter.subtract(this._originTop);
  96129. }
  96130. var multiplier = this._strength * -1;
  96131. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  96132. return { force: force, contactPoint: impostorObjectCenter };
  96133. };
  96134. PhysicsUpdraftEvent.prototype._tick = function () {
  96135. var _this = this;
  96136. this._physicsEngine.getImpostors().forEach(function (impostor) {
  96137. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  96138. if (!impostorForceAndContactPoint) {
  96139. return;
  96140. }
  96141. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  96142. });
  96143. };
  96144. /*** Helpers ***/
  96145. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  96146. if (!this._cylinder) {
  96147. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  96148. height: this._height,
  96149. diameter: this._radius * 2,
  96150. }, this._scene);
  96151. this._cylinder.isVisible = false;
  96152. }
  96153. };
  96154. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  96155. var impostorObject = impostor.object;
  96156. this._prepareCylinder();
  96157. this._cylinder.position = this._cylinderPosition;
  96158. return this._cylinder.intersectsMesh(impostorObject, true);
  96159. };
  96160. return PhysicsUpdraftEvent;
  96161. }());
  96162. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  96163. /**
  96164. * Represents a physics vortex event
  96165. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96166. */
  96167. var PhysicsVortexEvent = /** @class */ (function () {
  96168. /**
  96169. * Initializes the physics vortex event
  96170. * @param _scene The BabylonJS scene
  96171. * @param _origin The origin position of the vortex
  96172. * @param _radius The radius of the vortex
  96173. * @param _strength The strength of the vortex
  96174. * @param _height The height of the vortex
  96175. */
  96176. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  96177. this._scene = _scene;
  96178. this._origin = _origin;
  96179. this._radius = _radius;
  96180. this._strength = _strength;
  96181. this._height = _height;
  96182. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  96183. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  96184. this._updraftMultiplier = 0.02;
  96185. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  96186. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  96187. this._physicsEngine = this._scene.getPhysicsEngine();
  96188. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  96189. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  96190. this._tickCallback = this._tick.bind(this);
  96191. }
  96192. /**
  96193. * Returns the data related to the vortex event (cylinder).
  96194. * @returns The physics vortex event data
  96195. */
  96196. PhysicsVortexEvent.prototype.getData = function () {
  96197. this._dataFetched = true;
  96198. return {
  96199. cylinder: this._cylinder,
  96200. };
  96201. };
  96202. /**
  96203. * Enables the vortex.
  96204. */
  96205. PhysicsVortexEvent.prototype.enable = function () {
  96206. this._tickCallback.call(this);
  96207. this._scene.registerBeforeRender(this._tickCallback);
  96208. };
  96209. /**
  96210. * Disables the cortex.
  96211. */
  96212. PhysicsVortexEvent.prototype.disable = function () {
  96213. this._scene.unregisterBeforeRender(this._tickCallback);
  96214. };
  96215. /**
  96216. * Disposes the sphere.
  96217. * @param force
  96218. */
  96219. PhysicsVortexEvent.prototype.dispose = function (force) {
  96220. var _this = this;
  96221. if (force === void 0) { force = true; }
  96222. if (force) {
  96223. this._cylinder.dispose();
  96224. }
  96225. else {
  96226. setTimeout(function () {
  96227. if (!_this._dataFetched) {
  96228. _this._cylinder.dispose();
  96229. }
  96230. }, 0);
  96231. }
  96232. };
  96233. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  96234. if (impostor.mass === 0) {
  96235. return null;
  96236. }
  96237. if (!this._intersectsWithCylinder(impostor)) {
  96238. return null;
  96239. }
  96240. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  96241. return null;
  96242. }
  96243. var impostorObjectCenter = impostor.getObjectCenter();
  96244. 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)
  96245. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  96246. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  96247. var hit = ray.intersectsMesh(impostor.object);
  96248. var contactPoint = hit.pickedPoint;
  96249. if (!contactPoint) {
  96250. return null;
  96251. }
  96252. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  96253. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  96254. var directionToOrigin = contactPoint.normalize();
  96255. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  96256. directionToOrigin = directionToOrigin.negate();
  96257. }
  96258. // TODO: find a more physically based solution
  96259. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  96260. var forceX = directionToOrigin.x * this._strength / 8;
  96261. var forceY = directionToOrigin.y * this._updraftMultiplier;
  96262. var forceZ = directionToOrigin.z * this._strength / 8;
  96263. }
  96264. else {
  96265. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  96266. var forceY = this._originTop.y * this._updraftMultiplier;
  96267. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  96268. }
  96269. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  96270. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  96271. return { force: force, contactPoint: impostorObjectCenter };
  96272. };
  96273. PhysicsVortexEvent.prototype._tick = function () {
  96274. var _this = this;
  96275. this._physicsEngine.getImpostors().forEach(function (impostor) {
  96276. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  96277. if (!impostorForceAndContactPoint) {
  96278. return;
  96279. }
  96280. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  96281. });
  96282. };
  96283. /*** Helpers ***/
  96284. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  96285. if (!this._cylinder) {
  96286. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  96287. height: this._height,
  96288. diameter: this._radius * 2,
  96289. }, this._scene);
  96290. this._cylinder.isVisible = false;
  96291. }
  96292. };
  96293. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  96294. var impostorObject = impostor.object;
  96295. this._prepareCylinder();
  96296. this._cylinder.position = this._cylinderPosition;
  96297. return this._cylinder.intersectsMesh(impostorObject, true);
  96298. };
  96299. return PhysicsVortexEvent;
  96300. }());
  96301. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  96302. /**
  96303. * The strenght of the force in correspondence to the distance of the affected object
  96304. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96305. */
  96306. var PhysicsRadialImpulseFalloff;
  96307. (function (PhysicsRadialImpulseFalloff) {
  96308. /** Defines that impulse is constant in strength across it's whole radius */
  96309. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  96310. /** DEfines that impulse gets weaker if it's further from the origin */
  96311. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  96312. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  96313. /**
  96314. * The strength of the force in correspondence to the distance of the affected object
  96315. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96316. */
  96317. var PhysicsUpdraftMode;
  96318. (function (PhysicsUpdraftMode) {
  96319. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  96320. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  96321. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  96322. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  96323. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  96324. })(BABYLON || (BABYLON = {}));
  96325. //# sourceMappingURL=babylon.physicsHelper.js.map
  96326. var BABYLON;
  96327. (function (BABYLON) {
  96328. /** @hidden */
  96329. var CannonJSPlugin = /** @class */ (function () {
  96330. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  96331. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  96332. if (iterations === void 0) { iterations = 10; }
  96333. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  96334. this.name = "CannonJSPlugin";
  96335. this._physicsMaterials = new Array();
  96336. this._fixedTimeStep = 1 / 60;
  96337. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  96338. this.BJSCANNON = CANNON;
  96339. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  96340. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  96341. this._tmpPosition = BABYLON.Vector3.Zero();
  96342. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  96343. this._tmpUnityRotation = new BABYLON.Quaternion();
  96344. if (!this.isSupported()) {
  96345. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  96346. return;
  96347. }
  96348. this._extendNamespace();
  96349. this.world = new this.BJSCANNON.World();
  96350. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  96351. this.world.solver.iterations = iterations;
  96352. }
  96353. CannonJSPlugin.prototype.setGravity = function (gravity) {
  96354. this.world.gravity.copy(gravity);
  96355. };
  96356. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  96357. this._fixedTimeStep = timeStep;
  96358. };
  96359. CannonJSPlugin.prototype.getTimeStep = function () {
  96360. return this._fixedTimeStep;
  96361. };
  96362. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  96363. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  96364. };
  96365. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  96366. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  96367. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  96368. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  96369. };
  96370. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  96371. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  96372. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  96373. impostor.physicsBody.applyForce(impulse, worldPoint);
  96374. };
  96375. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  96376. //parent-child relationship. Does this impostor has a parent impostor?
  96377. if (impostor.parent) {
  96378. if (impostor.physicsBody) {
  96379. this.removePhysicsBody(impostor);
  96380. //TODO is that needed?
  96381. impostor.forceUpdate();
  96382. }
  96383. return;
  96384. }
  96385. //should a new body be created for this impostor?
  96386. if (impostor.isBodyInitRequired()) {
  96387. var shape = this._createShape(impostor);
  96388. //unregister events, if body is being changed
  96389. var oldBody = impostor.physicsBody;
  96390. if (oldBody) {
  96391. this.removePhysicsBody(impostor);
  96392. }
  96393. //create the body and material
  96394. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  96395. var bodyCreationObject = {
  96396. mass: impostor.getParam("mass"),
  96397. material: material
  96398. };
  96399. // A simple extend, in case native options were used.
  96400. var nativeOptions = impostor.getParam("nativeOptions");
  96401. for (var key in nativeOptions) {
  96402. if (nativeOptions.hasOwnProperty(key)) {
  96403. bodyCreationObject[key] = nativeOptions[key];
  96404. }
  96405. }
  96406. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  96407. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  96408. this.world.addEventListener("preStep", impostor.beforeStep);
  96409. this.world.addEventListener("postStep", impostor.afterStep);
  96410. impostor.physicsBody.addShape(shape);
  96411. this.world.add(impostor.physicsBody);
  96412. //try to keep the body moving in the right direction by taking old properties.
  96413. //Should be tested!
  96414. if (oldBody) {
  96415. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  96416. impostor.physicsBody[param].copy(oldBody[param]);
  96417. });
  96418. }
  96419. this._processChildMeshes(impostor);
  96420. }
  96421. //now update the body's transformation
  96422. this._updatePhysicsBodyTransformation(impostor);
  96423. };
  96424. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  96425. var _this = this;
  96426. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  96427. var currentRotation = mainImpostor.object.rotationQuaternion;
  96428. if (meshChildren.length) {
  96429. var processMesh = function (localPosition, mesh) {
  96430. if (!currentRotation || !mesh.rotationQuaternion) {
  96431. return;
  96432. }
  96433. var childImpostor = mesh.getPhysicsImpostor();
  96434. if (childImpostor) {
  96435. var parent = childImpostor.parent;
  96436. if (parent !== mainImpostor) {
  96437. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  96438. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  96439. if (childImpostor.physicsBody) {
  96440. _this.removePhysicsBody(childImpostor);
  96441. childImpostor.physicsBody = null;
  96442. }
  96443. childImpostor.parent = mainImpostor;
  96444. childImpostor.resetUpdateFlags();
  96445. 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));
  96446. //Add the mass of the children.
  96447. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  96448. }
  96449. }
  96450. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  96451. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  96452. };
  96453. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  96454. }
  96455. };
  96456. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  96457. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  96458. this.world.removeEventListener("preStep", impostor.beforeStep);
  96459. this.world.removeEventListener("postStep", impostor.afterStep);
  96460. this.world.remove(impostor.physicsBody);
  96461. };
  96462. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  96463. var mainBody = impostorJoint.mainImpostor.physicsBody;
  96464. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  96465. if (!mainBody || !connectedBody) {
  96466. return;
  96467. }
  96468. var constraint;
  96469. var jointData = impostorJoint.joint.jointData;
  96470. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  96471. var constraintData = {
  96472. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  96473. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  96474. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  96475. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  96476. maxForce: jointData.nativeParams.maxForce,
  96477. collideConnected: !!jointData.collision
  96478. };
  96479. switch (impostorJoint.joint.type) {
  96480. case BABYLON.PhysicsJoint.HingeJoint:
  96481. case BABYLON.PhysicsJoint.Hinge2Joint:
  96482. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  96483. break;
  96484. case BABYLON.PhysicsJoint.DistanceJoint:
  96485. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  96486. break;
  96487. case BABYLON.PhysicsJoint.SpringJoint:
  96488. var springData = jointData;
  96489. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  96490. restLength: springData.length,
  96491. stiffness: springData.stiffness,
  96492. damping: springData.damping,
  96493. localAnchorA: constraintData.pivotA,
  96494. localAnchorB: constraintData.pivotB
  96495. });
  96496. break;
  96497. case BABYLON.PhysicsJoint.LockJoint:
  96498. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  96499. break;
  96500. case BABYLON.PhysicsJoint.PointToPointJoint:
  96501. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  96502. default:
  96503. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  96504. break;
  96505. }
  96506. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  96507. constraint.collideConnected = !!jointData.collision;
  96508. impostorJoint.joint.physicsJoint = constraint;
  96509. //don't add spring as constraint, as it is not one.
  96510. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  96511. this.world.addConstraint(constraint);
  96512. }
  96513. else {
  96514. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  96515. constraint.applyForce();
  96516. };
  96517. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  96518. }
  96519. };
  96520. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  96521. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  96522. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  96523. }
  96524. else {
  96525. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  96526. }
  96527. };
  96528. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  96529. var index;
  96530. var mat;
  96531. for (index = 0; index < this._physicsMaterials.length; index++) {
  96532. mat = this._physicsMaterials[index];
  96533. if (mat.friction === friction && mat.restitution === restitution) {
  96534. return mat;
  96535. }
  96536. }
  96537. var currentMat = new this.BJSCANNON.Material(name);
  96538. currentMat.friction = friction;
  96539. currentMat.restitution = restitution;
  96540. this._physicsMaterials.push(currentMat);
  96541. return currentMat;
  96542. };
  96543. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  96544. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  96545. };
  96546. CannonJSPlugin.prototype._createShape = function (impostor) {
  96547. var object = impostor.object;
  96548. var returnValue;
  96549. var extendSize = impostor.getObjectExtendSize();
  96550. switch (impostor.type) {
  96551. case BABYLON.PhysicsImpostor.SphereImpostor:
  96552. var radiusX = extendSize.x;
  96553. var radiusY = extendSize.y;
  96554. var radiusZ = extendSize.z;
  96555. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  96556. break;
  96557. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  96558. case BABYLON.PhysicsImpostor.CylinderImpostor:
  96559. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  96560. break;
  96561. case BABYLON.PhysicsImpostor.BoxImpostor:
  96562. var box = extendSize.scale(0.5);
  96563. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  96564. break;
  96565. case BABYLON.PhysicsImpostor.PlaneImpostor:
  96566. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  96567. returnValue = new this.BJSCANNON.Plane();
  96568. break;
  96569. case BABYLON.PhysicsImpostor.MeshImpostor:
  96570. // should transform the vertex data to world coordinates!!
  96571. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  96572. var rawFaces = object.getIndices ? object.getIndices() : [];
  96573. if (!rawVerts) {
  96574. return;
  96575. }
  96576. // get only scale! so the object could transform correctly.
  96577. var oldPosition = object.position.clone();
  96578. var oldRotation = object.rotation && object.rotation.clone();
  96579. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  96580. object.position.copyFromFloats(0, 0, 0);
  96581. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  96582. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  96583. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  96584. var transform = object.computeWorldMatrix(true);
  96585. // convert rawVerts to object space
  96586. var temp = new Array();
  96587. var index;
  96588. for (index = 0; index < rawVerts.length; index += 3) {
  96589. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  96590. }
  96591. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  96592. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  96593. //now set back the transformation!
  96594. object.position.copyFrom(oldPosition);
  96595. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  96596. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  96597. break;
  96598. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  96599. var oldPosition2 = object.position.clone();
  96600. var oldRotation2 = object.rotation && object.rotation.clone();
  96601. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  96602. object.position.copyFromFloats(0, 0, 0);
  96603. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  96604. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  96605. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  96606. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  96607. returnValue = this._createHeightmap(object);
  96608. object.position.copyFrom(oldPosition2);
  96609. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  96610. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  96611. object.computeWorldMatrix(true);
  96612. break;
  96613. case BABYLON.PhysicsImpostor.ParticleImpostor:
  96614. returnValue = new this.BJSCANNON.Particle();
  96615. break;
  96616. }
  96617. return returnValue;
  96618. };
  96619. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  96620. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  96621. var transform = object.computeWorldMatrix(true);
  96622. // convert rawVerts to object space
  96623. var temp = new Array();
  96624. var index;
  96625. for (index = 0; index < pos.length; index += 3) {
  96626. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  96627. }
  96628. pos = temp;
  96629. var matrix = new Array();
  96630. //For now pointDepth will not be used and will be automatically calculated.
  96631. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  96632. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  96633. var boundingInfo = object.getBoundingInfo();
  96634. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  96635. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  96636. var elementSize = dim * 2 / arraySize;
  96637. for (var i = 0; i < pos.length; i = i + 3) {
  96638. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  96639. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  96640. var y = -pos[i + 2] + minY;
  96641. if (!matrix[x]) {
  96642. matrix[x] = [];
  96643. }
  96644. if (!matrix[x][z]) {
  96645. matrix[x][z] = y;
  96646. }
  96647. matrix[x][z] = Math.max(y, matrix[x][z]);
  96648. }
  96649. for (var x = 0; x <= arraySize; ++x) {
  96650. if (!matrix[x]) {
  96651. var loc = 1;
  96652. while (!matrix[(x + loc) % arraySize]) {
  96653. loc++;
  96654. }
  96655. matrix[x] = matrix[(x + loc) % arraySize].slice();
  96656. //console.log("missing x", x);
  96657. }
  96658. for (var z = 0; z <= arraySize; ++z) {
  96659. if (!matrix[x][z]) {
  96660. var loc = 1;
  96661. var newValue;
  96662. while (newValue === undefined) {
  96663. newValue = matrix[x][(z + loc++) % arraySize];
  96664. }
  96665. matrix[x][z] = newValue;
  96666. }
  96667. }
  96668. }
  96669. var shape = new this.BJSCANNON.Heightfield(matrix, {
  96670. elementSize: elementSize
  96671. });
  96672. //For future reference, needed for body transformation
  96673. shape.minY = minY;
  96674. return shape;
  96675. };
  96676. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  96677. var object = impostor.object;
  96678. //make sure it is updated...
  96679. object.computeWorldMatrix && object.computeWorldMatrix(true);
  96680. // The delta between the mesh position and the mesh bounding box center
  96681. var bInfo = object.getBoundingInfo();
  96682. if (!bInfo) {
  96683. return;
  96684. }
  96685. var center = impostor.getObjectCenter();
  96686. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  96687. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  96688. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  96689. this._tmpPosition.copyFrom(center);
  96690. var quaternion = object.rotationQuaternion;
  96691. if (!quaternion) {
  96692. return;
  96693. }
  96694. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  96695. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  96696. //-90 DEG in X, precalculated
  96697. quaternion = quaternion.multiply(this._minus90X);
  96698. //Invert! (Precalculated, 90 deg in X)
  96699. //No need to clone. this will never change.
  96700. impostor.setDeltaRotation(this._plus90X);
  96701. }
  96702. //If it is a heightfield, if should be centered.
  96703. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  96704. var mesh = object;
  96705. var boundingInfo = mesh.getBoundingInfo();
  96706. //calculate the correct body position:
  96707. var rotationQuaternion = mesh.rotationQuaternion;
  96708. mesh.rotationQuaternion = this._tmpUnityRotation;
  96709. mesh.computeWorldMatrix(true);
  96710. //get original center with no rotation
  96711. var c = center.clone();
  96712. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  96713. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  96714. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  96715. mesh.setPreTransformMatrix(p);
  96716. mesh.computeWorldMatrix(true);
  96717. //calculate the translation
  96718. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  96719. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  96720. //add it inverted to the delta
  96721. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  96722. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  96723. //rotation is back
  96724. mesh.rotationQuaternion = rotationQuaternion;
  96725. mesh.setPreTransformMatrix(oldPivot);
  96726. mesh.computeWorldMatrix(true);
  96727. }
  96728. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  96729. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  96730. //this._tmpPosition.copyFrom(object.position);
  96731. }
  96732. impostor.setDeltaPosition(this._tmpDeltaPosition);
  96733. //Now update the impostor object
  96734. impostor.physicsBody.position.copy(this._tmpPosition);
  96735. impostor.physicsBody.quaternion.copy(quaternion);
  96736. };
  96737. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  96738. impostor.object.position.copyFrom(impostor.physicsBody.position);
  96739. if (impostor.object.rotationQuaternion) {
  96740. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  96741. }
  96742. };
  96743. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  96744. impostor.physicsBody.position.copy(newPosition);
  96745. impostor.physicsBody.quaternion.copy(newRotation);
  96746. };
  96747. CannonJSPlugin.prototype.isSupported = function () {
  96748. return this.BJSCANNON !== undefined;
  96749. };
  96750. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  96751. impostor.physicsBody.velocity.copy(velocity);
  96752. };
  96753. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  96754. impostor.physicsBody.angularVelocity.copy(velocity);
  96755. };
  96756. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  96757. var v = impostor.physicsBody.velocity;
  96758. if (!v) {
  96759. return null;
  96760. }
  96761. return new BABYLON.Vector3(v.x, v.y, v.z);
  96762. };
  96763. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  96764. var v = impostor.physicsBody.angularVelocity;
  96765. if (!v) {
  96766. return null;
  96767. }
  96768. return new BABYLON.Vector3(v.x, v.y, v.z);
  96769. };
  96770. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  96771. impostor.physicsBody.mass = mass;
  96772. impostor.physicsBody.updateMassProperties();
  96773. };
  96774. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  96775. return impostor.physicsBody.mass;
  96776. };
  96777. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  96778. return impostor.physicsBody.material.friction;
  96779. };
  96780. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  96781. impostor.physicsBody.material.friction = friction;
  96782. };
  96783. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  96784. return impostor.physicsBody.material.restitution;
  96785. };
  96786. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  96787. impostor.physicsBody.material.restitution = restitution;
  96788. };
  96789. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  96790. impostor.physicsBody.sleep();
  96791. };
  96792. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  96793. impostor.physicsBody.wakeUp();
  96794. };
  96795. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  96796. joint.physicsJoint.distance = maxDistance;
  96797. };
  96798. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  96799. // if (!motorIndex) {
  96800. // joint.physicsJoint.enableMotor();
  96801. // }
  96802. // }
  96803. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  96804. // if (!motorIndex) {
  96805. // joint.physicsJoint.disableMotor();
  96806. // }
  96807. // }
  96808. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  96809. if (!motorIndex) {
  96810. joint.physicsJoint.enableMotor();
  96811. joint.physicsJoint.setMotorSpeed(speed);
  96812. if (maxForce) {
  96813. this.setLimit(joint, maxForce);
  96814. }
  96815. }
  96816. };
  96817. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  96818. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  96819. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  96820. };
  96821. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  96822. var body = impostor.physicsBody;
  96823. mesh.position.x = body.position.x;
  96824. mesh.position.y = body.position.y;
  96825. mesh.position.z = body.position.z;
  96826. if (mesh.rotationQuaternion) {
  96827. mesh.rotationQuaternion.x = body.quaternion.x;
  96828. mesh.rotationQuaternion.y = body.quaternion.y;
  96829. mesh.rotationQuaternion.z = body.quaternion.z;
  96830. mesh.rotationQuaternion.w = body.quaternion.w;
  96831. }
  96832. };
  96833. CannonJSPlugin.prototype.getRadius = function (impostor) {
  96834. var shape = impostor.physicsBody.shapes[0];
  96835. return shape.boundingSphereRadius;
  96836. };
  96837. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  96838. var shape = impostor.physicsBody.shapes[0];
  96839. result.x = shape.halfExtents.x * 2;
  96840. result.y = shape.halfExtents.y * 2;
  96841. result.z = shape.halfExtents.z * 2;
  96842. };
  96843. CannonJSPlugin.prototype.dispose = function () {
  96844. };
  96845. CannonJSPlugin.prototype._extendNamespace = function () {
  96846. //this will force cannon to execute at least one step when using interpolation
  96847. var step_tmp1 = new this.BJSCANNON.Vec3();
  96848. var Engine = this.BJSCANNON;
  96849. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  96850. maxSubSteps = maxSubSteps || 10;
  96851. timeSinceLastCalled = timeSinceLastCalled || 0;
  96852. if (timeSinceLastCalled === 0) {
  96853. this.internalStep(dt);
  96854. this.time += dt;
  96855. }
  96856. else {
  96857. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  96858. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  96859. var t0 = performance.now();
  96860. for (var i = 0; i !== internalSteps; i++) {
  96861. this.internalStep(dt);
  96862. if (performance.now() - t0 > dt * 1000) {
  96863. break;
  96864. }
  96865. }
  96866. this.time += timeSinceLastCalled;
  96867. var h = this.time % dt;
  96868. var h_div_dt = h / dt;
  96869. var interpvelo = step_tmp1;
  96870. var bodies = this.bodies;
  96871. for (var j = 0; j !== bodies.length; j++) {
  96872. var b = bodies[j];
  96873. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  96874. b.position.vsub(b.previousPosition, interpvelo);
  96875. interpvelo.scale(h_div_dt, interpvelo);
  96876. b.position.vadd(interpvelo, b.interpolatedPosition);
  96877. }
  96878. else {
  96879. b.interpolatedPosition.copy(b.position);
  96880. b.interpolatedQuaternion.copy(b.quaternion);
  96881. }
  96882. }
  96883. }
  96884. };
  96885. };
  96886. return CannonJSPlugin;
  96887. }());
  96888. BABYLON.CannonJSPlugin = CannonJSPlugin;
  96889. })(BABYLON || (BABYLON = {}));
  96890. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  96891. var BABYLON;
  96892. (function (BABYLON) {
  96893. /** @hidden */
  96894. var OimoJSPlugin = /** @class */ (function () {
  96895. function OimoJSPlugin(iterations) {
  96896. this.name = "OimoJSPlugin";
  96897. this._tmpImpostorsArray = [];
  96898. this._tmpPositionVector = BABYLON.Vector3.Zero();
  96899. this.BJSOIMO = OIMO;
  96900. this.world = new this.BJSOIMO.World({
  96901. iterations: iterations
  96902. });
  96903. this.world.clear();
  96904. }
  96905. OimoJSPlugin.prototype.setGravity = function (gravity) {
  96906. this.world.gravity.copy(gravity);
  96907. };
  96908. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  96909. this.world.timeStep = timeStep;
  96910. };
  96911. OimoJSPlugin.prototype.getTimeStep = function () {
  96912. return this.world.timeStep;
  96913. };
  96914. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  96915. var _this = this;
  96916. impostors.forEach(function (impostor) {
  96917. impostor.beforeStep();
  96918. });
  96919. this.world.step();
  96920. impostors.forEach(function (impostor) {
  96921. impostor.afterStep();
  96922. //update the ordered impostors array
  96923. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  96924. });
  96925. //check for collisions
  96926. var contact = this.world.contacts;
  96927. while (contact !== null) {
  96928. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  96929. contact = contact.next;
  96930. continue;
  96931. }
  96932. //is this body colliding with any other? get the impostor
  96933. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  96934. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  96935. if (!mainImpostor || !collidingImpostor) {
  96936. contact = contact.next;
  96937. continue;
  96938. }
  96939. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  96940. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  96941. contact = contact.next;
  96942. }
  96943. };
  96944. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  96945. var mass = impostor.physicsBody.mass;
  96946. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  96947. };
  96948. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  96949. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  96950. this.applyImpulse(impostor, force, contactPoint);
  96951. };
  96952. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  96953. var _this = this;
  96954. //parent-child relationship. Does this impostor has a parent impostor?
  96955. if (impostor.parent) {
  96956. if (impostor.physicsBody) {
  96957. this.removePhysicsBody(impostor);
  96958. //TODO is that needed?
  96959. impostor.forceUpdate();
  96960. }
  96961. return;
  96962. }
  96963. if (impostor.isBodyInitRequired()) {
  96964. var bodyConfig = {
  96965. name: impostor.uniqueId,
  96966. //Oimo must have mass, also for static objects.
  96967. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  96968. size: [],
  96969. type: [],
  96970. pos: [],
  96971. posShape: [],
  96972. rot: [],
  96973. rotShape: [],
  96974. move: impostor.getParam("mass") !== 0,
  96975. density: impostor.getParam("mass"),
  96976. friction: impostor.getParam("friction"),
  96977. restitution: impostor.getParam("restitution"),
  96978. //Supporting older versions of Oimo
  96979. world: this.world
  96980. };
  96981. var impostors = [impostor];
  96982. var addToArray = function (parent) {
  96983. if (!parent.getChildMeshes) {
  96984. return;
  96985. }
  96986. parent.getChildMeshes().forEach(function (m) {
  96987. if (m.physicsImpostor) {
  96988. impostors.push(m.physicsImpostor);
  96989. //m.physicsImpostor._init();
  96990. }
  96991. });
  96992. };
  96993. addToArray(impostor.object);
  96994. var checkWithEpsilon_1 = function (value) {
  96995. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  96996. };
  96997. var globalQuaternion_1 = new BABYLON.Quaternion();
  96998. impostors.forEach(function (i) {
  96999. if (!i.object.rotationQuaternion) {
  97000. return;
  97001. }
  97002. //get the correct bounding box
  97003. var oldQuaternion = i.object.rotationQuaternion;
  97004. globalQuaternion_1 = oldQuaternion.clone();
  97005. var rot = oldQuaternion.toEulerAngles();
  97006. var extendSize = i.getObjectExtendSize();
  97007. var radToDeg = 57.295779513082320876;
  97008. if (i === impostor) {
  97009. var center = impostor.getObjectCenter();
  97010. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  97011. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  97012. //Can also use Array.prototype.push.apply
  97013. bodyConfig.pos.push(center.x);
  97014. bodyConfig.pos.push(center.y);
  97015. bodyConfig.pos.push(center.z);
  97016. bodyConfig.posShape.push(0, 0, 0);
  97017. //tmp solution
  97018. bodyConfig.rot.push(0);
  97019. bodyConfig.rot.push(0);
  97020. bodyConfig.rot.push(0);
  97021. bodyConfig.rotShape.push(0, 0, 0);
  97022. }
  97023. else {
  97024. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  97025. bodyConfig.posShape.push(localPosition.x);
  97026. bodyConfig.posShape.push(localPosition.y);
  97027. bodyConfig.posShape.push(localPosition.z);
  97028. bodyConfig.pos.push(0, 0, 0);
  97029. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  97030. bodyConfig.rot.push(0);
  97031. bodyConfig.rot.push(0);
  97032. bodyConfig.rot.push(0);
  97033. bodyConfig.rotShape.push(rot.x * radToDeg);
  97034. bodyConfig.rotShape.push(rot.y * radToDeg);
  97035. bodyConfig.rotShape.push(rot.z * radToDeg);
  97036. }
  97037. // register mesh
  97038. switch (i.type) {
  97039. case BABYLON.PhysicsImpostor.ParticleImpostor:
  97040. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  97041. case BABYLON.PhysicsImpostor.SphereImpostor:
  97042. var radiusX = extendSize.x;
  97043. var radiusY = extendSize.y;
  97044. var radiusZ = extendSize.z;
  97045. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  97046. bodyConfig.type.push('sphere');
  97047. //due to the way oimo works with compounds, add 3 times
  97048. bodyConfig.size.push(size);
  97049. bodyConfig.size.push(size);
  97050. bodyConfig.size.push(size);
  97051. break;
  97052. case BABYLON.PhysicsImpostor.CylinderImpostor:
  97053. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  97054. var sizeY = checkWithEpsilon_1(extendSize.y);
  97055. bodyConfig.type.push('cylinder');
  97056. bodyConfig.size.push(sizeX);
  97057. bodyConfig.size.push(sizeY);
  97058. //due to the way oimo works with compounds, add one more value.
  97059. bodyConfig.size.push(sizeY);
  97060. break;
  97061. case BABYLON.PhysicsImpostor.PlaneImpostor:
  97062. case BABYLON.PhysicsImpostor.BoxImpostor:
  97063. default:
  97064. var sizeX = checkWithEpsilon_1(extendSize.x);
  97065. var sizeY = checkWithEpsilon_1(extendSize.y);
  97066. var sizeZ = checkWithEpsilon_1(extendSize.z);
  97067. bodyConfig.type.push('box');
  97068. //if (i === impostor) {
  97069. bodyConfig.size.push(sizeX);
  97070. bodyConfig.size.push(sizeY);
  97071. bodyConfig.size.push(sizeZ);
  97072. //} else {
  97073. // bodyConfig.size.push(0,0,0);
  97074. //}
  97075. break;
  97076. }
  97077. //actually not needed, but hey...
  97078. i.object.rotationQuaternion = oldQuaternion;
  97079. });
  97080. impostor.physicsBody = this.world.add(bodyConfig);
  97081. // set the quaternion, ignoring the previously defined (euler) rotation
  97082. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  97083. // update with delta 0, so the body will reveive the new rotation.
  97084. impostor.physicsBody.updatePosition(0);
  97085. }
  97086. else {
  97087. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  97088. }
  97089. impostor.setDeltaPosition(this._tmpPositionVector);
  97090. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  97091. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  97092. };
  97093. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  97094. //impostor.physicsBody.dispose();
  97095. //Same as : (older oimo versions)
  97096. this.world.removeRigidBody(impostor.physicsBody);
  97097. };
  97098. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  97099. var mainBody = impostorJoint.mainImpostor.physicsBody;
  97100. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  97101. if (!mainBody || !connectedBody) {
  97102. return;
  97103. }
  97104. var jointData = impostorJoint.joint.jointData;
  97105. var options = jointData.nativeParams || {};
  97106. var type;
  97107. var nativeJointData = {
  97108. body1: mainBody,
  97109. body2: connectedBody,
  97110. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  97111. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  97112. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  97113. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  97114. min: options.min,
  97115. max: options.max,
  97116. collision: options.collision || jointData.collision,
  97117. spring: options.spring,
  97118. //supporting older version of Oimo
  97119. world: this.world
  97120. };
  97121. switch (impostorJoint.joint.type) {
  97122. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  97123. type = "jointBall";
  97124. break;
  97125. case BABYLON.PhysicsJoint.SpringJoint:
  97126. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  97127. var springData = jointData;
  97128. nativeJointData.min = springData.length || nativeJointData.min;
  97129. //Max should also be set, just make sure it is at least min
  97130. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  97131. case BABYLON.PhysicsJoint.DistanceJoint:
  97132. type = "jointDistance";
  97133. nativeJointData.max = jointData.maxDistance;
  97134. break;
  97135. case BABYLON.PhysicsJoint.PrismaticJoint:
  97136. type = "jointPrisme";
  97137. break;
  97138. case BABYLON.PhysicsJoint.SliderJoint:
  97139. type = "jointSlide";
  97140. break;
  97141. case BABYLON.PhysicsJoint.WheelJoint:
  97142. type = "jointWheel";
  97143. break;
  97144. case BABYLON.PhysicsJoint.HingeJoint:
  97145. default:
  97146. type = "jointHinge";
  97147. break;
  97148. }
  97149. nativeJointData.type = type;
  97150. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  97151. };
  97152. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  97153. //Bug in Oimo prevents us from disposing a joint in the playground
  97154. //joint.joint.physicsJoint.dispose();
  97155. //So we will bruteforce it!
  97156. try {
  97157. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  97158. }
  97159. catch (e) {
  97160. BABYLON.Tools.Warn(e);
  97161. }
  97162. };
  97163. OimoJSPlugin.prototype.isSupported = function () {
  97164. return this.BJSOIMO !== undefined;
  97165. };
  97166. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  97167. if (!impostor.physicsBody.sleeping) {
  97168. //TODO check that
  97169. /*if (impostor.physicsBody.shapes.next) {
  97170. var parentShape = this._getLastShape(impostor.physicsBody);
  97171. impostor.object.position.copyFrom(parentShape.position);
  97172. console.log(parentShape.position);
  97173. } else {*/
  97174. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  97175. //}
  97176. if (impostor.object.rotationQuaternion) {
  97177. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  97178. }
  97179. }
  97180. };
  97181. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  97182. var body = impostor.physicsBody;
  97183. body.position.copy(newPosition);
  97184. body.orientation.copy(newRotation);
  97185. body.syncShapes();
  97186. body.awake();
  97187. };
  97188. /*private _getLastShape(body: any): any {
  97189. var lastShape = body.shapes;
  97190. while (lastShape.next) {
  97191. lastShape = lastShape.next;
  97192. }
  97193. return lastShape;
  97194. }*/
  97195. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  97196. impostor.physicsBody.linearVelocity.copy(velocity);
  97197. };
  97198. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  97199. impostor.physicsBody.angularVelocity.copy(velocity);
  97200. };
  97201. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  97202. var v = impostor.physicsBody.linearVelocity;
  97203. if (!v) {
  97204. return null;
  97205. }
  97206. return new BABYLON.Vector3(v.x, v.y, v.z);
  97207. };
  97208. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  97209. var v = impostor.physicsBody.angularVelocity;
  97210. if (!v) {
  97211. return null;
  97212. }
  97213. return new BABYLON.Vector3(v.x, v.y, v.z);
  97214. };
  97215. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  97216. var staticBody = mass === 0;
  97217. //this will actually set the body's density and not its mass.
  97218. //But this is how oimo treats the mass variable.
  97219. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  97220. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  97221. };
  97222. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  97223. return impostor.physicsBody.shapes.density;
  97224. };
  97225. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  97226. return impostor.physicsBody.shapes.friction;
  97227. };
  97228. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  97229. impostor.physicsBody.shapes.friction = friction;
  97230. };
  97231. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  97232. return impostor.physicsBody.shapes.restitution;
  97233. };
  97234. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  97235. impostor.physicsBody.shapes.restitution = restitution;
  97236. };
  97237. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  97238. impostor.physicsBody.sleep();
  97239. };
  97240. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  97241. impostor.physicsBody.awake();
  97242. };
  97243. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  97244. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  97245. if (minDistance !== void 0) {
  97246. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  97247. }
  97248. };
  97249. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  97250. //TODO separate rotational and transational motors.
  97251. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  97252. if (motor) {
  97253. motor.setMotor(speed, maxForce);
  97254. }
  97255. };
  97256. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  97257. //TODO separate rotational and transational motors.
  97258. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  97259. if (motor) {
  97260. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  97261. }
  97262. };
  97263. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  97264. var body = impostor.physicsBody;
  97265. mesh.position.x = body.position.x;
  97266. mesh.position.y = body.position.y;
  97267. mesh.position.z = body.position.z;
  97268. if (mesh.rotationQuaternion) {
  97269. mesh.rotationQuaternion.x = body.orientation.x;
  97270. mesh.rotationQuaternion.y = body.orientation.y;
  97271. mesh.rotationQuaternion.z = body.orientation.z;
  97272. mesh.rotationQuaternion.w = body.orientation.s;
  97273. }
  97274. };
  97275. OimoJSPlugin.prototype.getRadius = function (impostor) {
  97276. return impostor.physicsBody.shapes.radius;
  97277. };
  97278. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  97279. var shape = impostor.physicsBody.shapes;
  97280. result.x = shape.halfWidth * 2;
  97281. result.y = shape.halfHeight * 2;
  97282. result.z = shape.halfDepth * 2;
  97283. };
  97284. OimoJSPlugin.prototype.dispose = function () {
  97285. this.world.clear();
  97286. };
  97287. return OimoJSPlugin;
  97288. }());
  97289. BABYLON.OimoJSPlugin = OimoJSPlugin;
  97290. })(BABYLON || (BABYLON = {}));
  97291. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  97292. var BABYLON;
  97293. (function (BABYLON) {
  97294. /**
  97295. * Gets the current physics engine
  97296. * @returns a IPhysicsEngine or null if none attached
  97297. */
  97298. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  97299. return this._physicsEngine;
  97300. };
  97301. /**
  97302. * Enables physics to the current scene
  97303. * @param gravity defines the scene's gravity for the physics engine
  97304. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  97305. * @return a boolean indicating if the physics engine was initialized
  97306. */
  97307. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  97308. if (gravity === void 0) { gravity = null; }
  97309. if (this._physicsEngine) {
  97310. return true;
  97311. }
  97312. // Register the component to the scene
  97313. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  97314. if (!component) {
  97315. component = new PhysicsEngineSceneComponent(this);
  97316. this._addComponent(component);
  97317. }
  97318. try {
  97319. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  97320. return true;
  97321. }
  97322. catch (e) {
  97323. BABYLON.Tools.Error(e.message);
  97324. return false;
  97325. }
  97326. };
  97327. /**
  97328. * Disables and disposes the physics engine associated with the scene
  97329. */
  97330. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  97331. if (!this._physicsEngine) {
  97332. return;
  97333. }
  97334. this._physicsEngine.dispose();
  97335. this._physicsEngine = null;
  97336. };
  97337. /**
  97338. * Gets a boolean indicating if there is an active physics engine
  97339. * @returns a boolean indicating if there is an active physics engine
  97340. */
  97341. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  97342. return this._physicsEngine !== undefined;
  97343. };
  97344. /**
  97345. * Deletes a physics compound impostor
  97346. * @param compound defines the compound to delete
  97347. */
  97348. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  97349. var mesh = compound.parts[0].mesh;
  97350. if (mesh.physicsImpostor) {
  97351. mesh.physicsImpostor.dispose( /*true*/);
  97352. mesh.physicsImpostor = null;
  97353. }
  97354. };
  97355. /** @hidden */
  97356. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  97357. if (this._physicsEngine) {
  97358. this.onBeforePhysicsObservable.notifyObservers(this);
  97359. this._physicsEngine._step(step / 1000);
  97360. this.onAfterPhysicsObservable.notifyObservers(this);
  97361. }
  97362. };
  97363. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  97364. get: function () {
  97365. return this._physicsImpostor;
  97366. },
  97367. set: function (value) {
  97368. var _this = this;
  97369. if (this._physicsImpostor === value) {
  97370. return;
  97371. }
  97372. if (this._disposePhysicsObserver) {
  97373. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  97374. }
  97375. this._physicsImpostor = value;
  97376. if (value) {
  97377. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  97378. // Physics
  97379. if (_this.physicsImpostor) {
  97380. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  97381. _this.physicsImpostor = null;
  97382. }
  97383. });
  97384. }
  97385. },
  97386. enumerable: true,
  97387. configurable: true
  97388. });
  97389. /**
  97390. * Gets the current physics impostor
  97391. * @see http://doc.babylonjs.com/features/physics_engine
  97392. * @returns a physics impostor or null
  97393. */
  97394. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  97395. return this.physicsImpostor;
  97396. };
  97397. /**
  97398. * Apply a physic impulse to the mesh
  97399. * @param force defines the force to apply
  97400. * @param contactPoint defines where to apply the force
  97401. * @returns the current mesh
  97402. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  97403. */
  97404. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  97405. if (!this.physicsImpostor) {
  97406. return this;
  97407. }
  97408. this.physicsImpostor.applyImpulse(force, contactPoint);
  97409. return this;
  97410. };
  97411. /**
  97412. * Creates a physic joint between two meshes
  97413. * @param otherMesh defines the other mesh to use
  97414. * @param pivot1 defines the pivot to use on this mesh
  97415. * @param pivot2 defines the pivot to use on the other mesh
  97416. * @param options defines additional options (can be plugin dependent)
  97417. * @returns the current mesh
  97418. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  97419. */
  97420. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  97421. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  97422. return this;
  97423. }
  97424. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  97425. mainPivot: pivot1,
  97426. connectedPivot: pivot2,
  97427. nativeParams: options
  97428. });
  97429. return this;
  97430. };
  97431. /**
  97432. * Defines the physics engine scene component responsible to manage a physics engine
  97433. */
  97434. var PhysicsEngineSceneComponent = /** @class */ (function () {
  97435. /**
  97436. * Creates a new instance of the component for the given scene
  97437. * @param scene Defines the scene to register the component in
  97438. */
  97439. function PhysicsEngineSceneComponent(scene) {
  97440. var _this = this;
  97441. /**
  97442. * The component name helpful to identify the component in the list of scene components.
  97443. */
  97444. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  97445. this.scene = scene;
  97446. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  97447. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  97448. // Replace the function used to get the deterministic frame time
  97449. this.scene.getDeterministicFrameTime = function () {
  97450. if (_this.scene._physicsEngine) {
  97451. return _this.scene._physicsEngine.getTimeStep() * 1000;
  97452. }
  97453. return 1000.0 / 60.0;
  97454. };
  97455. }
  97456. /**
  97457. * Registers the component in a given scene
  97458. */
  97459. PhysicsEngineSceneComponent.prototype.register = function () {
  97460. };
  97461. /**
  97462. * Rebuilds the elements related to this component in case of
  97463. * context lost for instance.
  97464. */
  97465. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  97466. // Nothing to do for this component
  97467. };
  97468. /**
  97469. * Disposes the component and the associated ressources
  97470. */
  97471. PhysicsEngineSceneComponent.prototype.dispose = function () {
  97472. this.scene.onBeforePhysicsObservable.clear();
  97473. this.scene.onAfterPhysicsObservable.clear();
  97474. if (this.scene._physicsEngine) {
  97475. this.scene.disablePhysicsEngine();
  97476. }
  97477. };
  97478. return PhysicsEngineSceneComponent;
  97479. }());
  97480. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  97481. })(BABYLON || (BABYLON = {}));
  97482. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  97483. var BABYLON;
  97484. (function (BABYLON) {
  97485. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  97486. // All values and structures referenced from:
  97487. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  97488. var DDS_MAGIC = 0x20534444;
  97489. var
  97490. //DDSD_CAPS = 0x1,
  97491. //DDSD_HEIGHT = 0x2,
  97492. //DDSD_WIDTH = 0x4,
  97493. //DDSD_PITCH = 0x8,
  97494. //DDSD_PIXELFORMAT = 0x1000,
  97495. DDSD_MIPMAPCOUNT = 0x20000;
  97496. //DDSD_LINEARSIZE = 0x80000,
  97497. //DDSD_DEPTH = 0x800000;
  97498. // var DDSCAPS_COMPLEX = 0x8,
  97499. // DDSCAPS_MIPMAP = 0x400000,
  97500. // DDSCAPS_TEXTURE = 0x1000;
  97501. var DDSCAPS2_CUBEMAP = 0x200;
  97502. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  97503. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  97504. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  97505. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  97506. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  97507. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  97508. // DDSCAPS2_VOLUME = 0x200000;
  97509. var
  97510. //DDPF_ALPHAPIXELS = 0x1,
  97511. //DDPF_ALPHA = 0x2,
  97512. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  97513. //DDPF_YUV = 0x200,
  97514. DDPF_LUMINANCE = 0x20000;
  97515. function FourCCToInt32(value) {
  97516. return value.charCodeAt(0) +
  97517. (value.charCodeAt(1) << 8) +
  97518. (value.charCodeAt(2) << 16) +
  97519. (value.charCodeAt(3) << 24);
  97520. }
  97521. function Int32ToFourCC(value) {
  97522. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  97523. }
  97524. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  97525. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  97526. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  97527. var FOURCC_DX10 = FourCCToInt32("DX10");
  97528. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  97529. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  97530. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  97531. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  97532. var headerLengthInt = 31; // The header length in 32 bit ints
  97533. // Offsets into the header array
  97534. var off_magic = 0;
  97535. var off_size = 1;
  97536. var off_flags = 2;
  97537. var off_height = 3;
  97538. var off_width = 4;
  97539. var off_mipmapCount = 7;
  97540. var off_pfFlags = 20;
  97541. var off_pfFourCC = 21;
  97542. var off_RGBbpp = 22;
  97543. var off_RMask = 23;
  97544. var off_GMask = 24;
  97545. var off_BMask = 25;
  97546. var off_AMask = 26;
  97547. // var off_caps1 = 27;
  97548. var off_caps2 = 28;
  97549. // var off_caps3 = 29;
  97550. // var off_caps4 = 30;
  97551. var off_dxgiFormat = 32;
  97552. /**
  97553. * Class used to provide DDS decompression tools
  97554. */
  97555. var DDSTools = /** @class */ (function () {
  97556. function DDSTools() {
  97557. }
  97558. /**
  97559. * Gets DDS information from an array buffer
  97560. * @param arrayBuffer defines the array buffer to read data from
  97561. * @returns the DDS information
  97562. */
  97563. DDSTools.GetDDSInfo = function (arrayBuffer) {
  97564. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  97565. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  97566. var mipmapCount = 1;
  97567. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  97568. mipmapCount = Math.max(1, header[off_mipmapCount]);
  97569. }
  97570. var fourCC = header[off_pfFourCC];
  97571. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  97572. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97573. switch (fourCC) {
  97574. case FOURCC_D3DFMT_R16G16B16A16F:
  97575. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97576. break;
  97577. case FOURCC_D3DFMT_R32G32B32A32F:
  97578. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97579. break;
  97580. case FOURCC_DX10:
  97581. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  97582. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97583. break;
  97584. }
  97585. }
  97586. return {
  97587. width: header[off_width],
  97588. height: header[off_height],
  97589. mipmapCount: mipmapCount,
  97590. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  97591. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  97592. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  97593. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  97594. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  97595. dxgiFormat: dxgiFormat,
  97596. textureType: textureType
  97597. };
  97598. };
  97599. DDSTools._ToHalfFloat = function (value) {
  97600. if (!DDSTools._FloatView) {
  97601. DDSTools._FloatView = new Float32Array(1);
  97602. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  97603. }
  97604. DDSTools._FloatView[0] = value;
  97605. var x = DDSTools._Int32View[0];
  97606. var bits = (x >> 16) & 0x8000; /* Get the sign */
  97607. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  97608. var e = (x >> 23) & 0xff; /* Using int is faster here */
  97609. /* If zero, or denormal, or exponent underflows too much for a denormal
  97610. * half, return signed zero. */
  97611. if (e < 103) {
  97612. return bits;
  97613. }
  97614. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  97615. if (e > 142) {
  97616. bits |= 0x7c00;
  97617. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  97618. * not Inf, so make sure we set one mantissa bit too. */
  97619. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  97620. return bits;
  97621. }
  97622. /* If exponent underflows but not too much, return a denormal */
  97623. if (e < 113) {
  97624. m |= 0x0800;
  97625. /* Extra rounding may overflow and set mantissa to 0 and exponent
  97626. * to 1, which is OK. */
  97627. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  97628. return bits;
  97629. }
  97630. bits |= ((e - 112) << 10) | (m >> 1);
  97631. bits += m & 1;
  97632. return bits;
  97633. };
  97634. DDSTools._FromHalfFloat = function (value) {
  97635. var s = (value & 0x8000) >> 15;
  97636. var e = (value & 0x7C00) >> 10;
  97637. var f = value & 0x03FF;
  97638. if (e === 0) {
  97639. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  97640. }
  97641. else if (e == 0x1F) {
  97642. return f ? NaN : ((s ? -1 : 1) * Infinity);
  97643. }
  97644. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  97645. };
  97646. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97647. var destArray = new Float32Array(dataLength);
  97648. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  97649. var index = 0;
  97650. for (var y = 0; y < height; y++) {
  97651. for (var x = 0; x < width; x++) {
  97652. var srcPos = (x + y * width) * 4;
  97653. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  97654. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  97655. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  97656. if (DDSTools.StoreLODInAlphaChannel) {
  97657. destArray[index + 3] = lod;
  97658. }
  97659. else {
  97660. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  97661. }
  97662. index += 4;
  97663. }
  97664. }
  97665. return destArray;
  97666. };
  97667. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97668. if (DDSTools.StoreLODInAlphaChannel) {
  97669. var destArray = new Uint16Array(dataLength);
  97670. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  97671. var index = 0;
  97672. for (var y = 0; y < height; y++) {
  97673. for (var x = 0; x < width; x++) {
  97674. var srcPos = (x + y * width) * 4;
  97675. destArray[index] = srcData[srcPos];
  97676. destArray[index + 1] = srcData[srcPos + 1];
  97677. destArray[index + 2] = srcData[srcPos + 2];
  97678. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  97679. index += 4;
  97680. }
  97681. }
  97682. return destArray;
  97683. }
  97684. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  97685. };
  97686. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97687. if (DDSTools.StoreLODInAlphaChannel) {
  97688. var destArray = new Float32Array(dataLength);
  97689. var srcData = new Float32Array(arrayBuffer, dataOffset);
  97690. var index = 0;
  97691. for (var y = 0; y < height; y++) {
  97692. for (var x = 0; x < width; x++) {
  97693. var srcPos = (x + y * width) * 4;
  97694. destArray[index] = srcData[srcPos];
  97695. destArray[index + 1] = srcData[srcPos + 1];
  97696. destArray[index + 2] = srcData[srcPos + 2];
  97697. destArray[index + 3] = lod;
  97698. index += 4;
  97699. }
  97700. }
  97701. return destArray;
  97702. }
  97703. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  97704. };
  97705. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97706. var destArray = new Uint8Array(dataLength);
  97707. var srcData = new Float32Array(arrayBuffer, dataOffset);
  97708. var index = 0;
  97709. for (var y = 0; y < height; y++) {
  97710. for (var x = 0; x < width; x++) {
  97711. var srcPos = (x + y * width) * 4;
  97712. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  97713. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  97714. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  97715. if (DDSTools.StoreLODInAlphaChannel) {
  97716. destArray[index + 3] = lod;
  97717. }
  97718. else {
  97719. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  97720. }
  97721. index += 4;
  97722. }
  97723. }
  97724. return destArray;
  97725. };
  97726. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97727. var destArray = new Uint8Array(dataLength);
  97728. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  97729. var index = 0;
  97730. for (var y = 0; y < height; y++) {
  97731. for (var x = 0; x < width; x++) {
  97732. var srcPos = (x + y * width) * 4;
  97733. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  97734. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  97735. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  97736. if (DDSTools.StoreLODInAlphaChannel) {
  97737. destArray[index + 3] = lod;
  97738. }
  97739. else {
  97740. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  97741. }
  97742. index += 4;
  97743. }
  97744. }
  97745. return destArray;
  97746. };
  97747. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  97748. var byteArray = new Uint8Array(dataLength);
  97749. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  97750. var index = 0;
  97751. for (var y = 0; y < height; y++) {
  97752. for (var x = 0; x < width; x++) {
  97753. var srcPos = (x + y * width) * 4;
  97754. byteArray[index] = srcData[srcPos + rOffset];
  97755. byteArray[index + 1] = srcData[srcPos + gOffset];
  97756. byteArray[index + 2] = srcData[srcPos + bOffset];
  97757. byteArray[index + 3] = srcData[srcPos + aOffset];
  97758. index += 4;
  97759. }
  97760. }
  97761. return byteArray;
  97762. };
  97763. DDSTools._ExtractLongWordOrder = function (value) {
  97764. if (value === 0 || value === 255 || value === -16777216) {
  97765. return 0;
  97766. }
  97767. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  97768. };
  97769. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  97770. var byteArray = new Uint8Array(dataLength);
  97771. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  97772. var index = 0;
  97773. for (var y = 0; y < height; y++) {
  97774. for (var x = 0; x < width; x++) {
  97775. var srcPos = (x + y * width) * 3;
  97776. byteArray[index] = srcData[srcPos + rOffset];
  97777. byteArray[index + 1] = srcData[srcPos + gOffset];
  97778. byteArray[index + 2] = srcData[srcPos + bOffset];
  97779. index += 3;
  97780. }
  97781. }
  97782. return byteArray;
  97783. };
  97784. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  97785. var byteArray = new Uint8Array(dataLength);
  97786. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  97787. var index = 0;
  97788. for (var y = 0; y < height; y++) {
  97789. for (var x = 0; x < width; x++) {
  97790. var srcPos = (x + y * width);
  97791. byteArray[index] = srcData[srcPos];
  97792. index++;
  97793. }
  97794. }
  97795. return byteArray;
  97796. };
  97797. /**
  97798. * Uploads DDS Levels to a Babylon Texture
  97799. * @hidden
  97800. */
  97801. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  97802. if (lodIndex === void 0) { lodIndex = -1; }
  97803. var sphericalPolynomialFaces = null;
  97804. if (info.sphericalPolynomial) {
  97805. sphericalPolynomialFaces = new Array();
  97806. }
  97807. var ext = engine.getCaps().s3tc;
  97808. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  97809. var fourCC, width, height, dataLength = 0, dataOffset;
  97810. var byteArray, mipmapCount, mip;
  97811. var internalCompressedFormat = 0;
  97812. var blockBytes = 1;
  97813. if (header[off_magic] !== DDS_MAGIC) {
  97814. BABYLON.Tools.Error("Invalid magic number in DDS header");
  97815. return;
  97816. }
  97817. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  97818. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  97819. return;
  97820. }
  97821. if (info.isCompressed && !ext) {
  97822. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  97823. return;
  97824. }
  97825. var bpp = header[off_RGBbpp];
  97826. dataOffset = header[off_size] + 4;
  97827. var computeFormats = false;
  97828. if (info.isFourCC) {
  97829. fourCC = header[off_pfFourCC];
  97830. switch (fourCC) {
  97831. case FOURCC_DXT1:
  97832. blockBytes = 8;
  97833. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  97834. break;
  97835. case FOURCC_DXT3:
  97836. blockBytes = 16;
  97837. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  97838. break;
  97839. case FOURCC_DXT5:
  97840. blockBytes = 16;
  97841. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  97842. break;
  97843. case FOURCC_D3DFMT_R16G16B16A16F:
  97844. computeFormats = true;
  97845. break;
  97846. case FOURCC_D3DFMT_R32G32B32A32F:
  97847. computeFormats = true;
  97848. break;
  97849. case FOURCC_DX10:
  97850. // There is an additionnal header so dataOffset need to be changed
  97851. dataOffset += 5 * 4; // 5 uints
  97852. var supported = false;
  97853. switch (info.dxgiFormat) {
  97854. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  97855. computeFormats = true;
  97856. supported = true;
  97857. break;
  97858. case DXGI_FORMAT_B8G8R8X8_UNORM:
  97859. info.isRGB = true;
  97860. info.isFourCC = false;
  97861. bpp = 32;
  97862. supported = true;
  97863. break;
  97864. }
  97865. if (supported) {
  97866. break;
  97867. }
  97868. default:
  97869. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  97870. return;
  97871. }
  97872. }
  97873. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  97874. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  97875. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  97876. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  97877. if (computeFormats) {
  97878. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  97879. }
  97880. mipmapCount = 1;
  97881. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  97882. mipmapCount = Math.max(1, header[off_mipmapCount]);
  97883. }
  97884. for (var face = 0; face < faces; face++) {
  97885. width = header[off_width];
  97886. height = header[off_height];
  97887. for (mip = 0; mip < mipmapCount; ++mip) {
  97888. if (lodIndex === -1 || lodIndex === mip) {
  97889. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  97890. var i = (lodIndex === -1) ? mip : 0;
  97891. if (!info.isCompressed && info.isFourCC) {
  97892. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  97893. dataLength = width * height * 4;
  97894. var floatArray = null;
  97895. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  97896. if (bpp === 128) {
  97897. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97898. if (sphericalPolynomialFaces && i == 0) {
  97899. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  97900. }
  97901. }
  97902. else if (bpp === 64) {
  97903. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97904. if (sphericalPolynomialFaces && i == 0) {
  97905. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  97906. }
  97907. }
  97908. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97909. }
  97910. else {
  97911. if (bpp === 128) {
  97912. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97913. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97914. if (sphericalPolynomialFaces && i == 0) {
  97915. sphericalPolynomialFaces.push(floatArray);
  97916. }
  97917. }
  97918. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  97919. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97920. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97921. if (sphericalPolynomialFaces && i == 0) {
  97922. sphericalPolynomialFaces.push(floatArray);
  97923. }
  97924. }
  97925. else { // 64
  97926. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97927. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97928. if (sphericalPolynomialFaces && i == 0) {
  97929. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  97930. }
  97931. }
  97932. }
  97933. if (floatArray) {
  97934. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  97935. }
  97936. }
  97937. else if (info.isRGB) {
  97938. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97939. if (bpp === 24) {
  97940. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  97941. dataLength = width * height * 3;
  97942. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  97943. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  97944. }
  97945. else { // 32
  97946. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  97947. dataLength = width * height * 4;
  97948. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  97949. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  97950. }
  97951. }
  97952. else if (info.isLuminance) {
  97953. var unpackAlignment = engine._getUnpackAlignement();
  97954. var unpaddedRowSize = width;
  97955. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  97956. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  97957. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  97958. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  97959. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97960. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  97961. }
  97962. else {
  97963. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  97964. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  97965. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97966. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  97967. }
  97968. }
  97969. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  97970. width *= 0.5;
  97971. height *= 0.5;
  97972. width = Math.max(1.0, width);
  97973. height = Math.max(1.0, height);
  97974. }
  97975. if (currentFace !== undefined) {
  97976. // Loading a single face
  97977. break;
  97978. }
  97979. }
  97980. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  97981. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  97982. size: header[off_width],
  97983. right: sphericalPolynomialFaces[0],
  97984. left: sphericalPolynomialFaces[1],
  97985. up: sphericalPolynomialFaces[2],
  97986. down: sphericalPolynomialFaces[3],
  97987. front: sphericalPolynomialFaces[4],
  97988. back: sphericalPolynomialFaces[5],
  97989. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  97990. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  97991. gammaSpace: false,
  97992. });
  97993. }
  97994. else {
  97995. info.sphericalPolynomial = undefined;
  97996. }
  97997. };
  97998. /**
  97999. * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)
  98000. */
  98001. DDSTools.StoreLODInAlphaChannel = false;
  98002. return DDSTools;
  98003. }());
  98004. BABYLON.DDSTools = DDSTools;
  98005. })(BABYLON || (BABYLON = {}));
  98006. //# sourceMappingURL=babylon.dds.js.map
  98007. var BABYLON;
  98008. (function (BABYLON) {
  98009. /**
  98010. * Implementation of the DDS Texture Loader.
  98011. */
  98012. var DDSTextureLoader = /** @class */ (function () {
  98013. function DDSTextureLoader() {
  98014. /**
  98015. * Defines wether the loader supports cascade loading the different faces.
  98016. */
  98017. this.supportCascades = true;
  98018. }
  98019. /**
  98020. * This returns if the loader support the current file information.
  98021. * @param extension defines the file extension of the file being loaded
  98022. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98023. * @param fallback defines the fallback internal texture if any
  98024. * @param isBase64 defines whether the texture is encoded as a base64
  98025. * @param isBuffer defines whether the texture data are stored as a buffer
  98026. * @returns true if the loader can load the specified file
  98027. */
  98028. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  98029. return extension.indexOf(".dds") === 0;
  98030. };
  98031. /**
  98032. * Transform the url before loading if required.
  98033. * @param rootUrl the url of the texture
  98034. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98035. * @returns the transformed texture
  98036. */
  98037. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  98038. return rootUrl;
  98039. };
  98040. /**
  98041. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  98042. * @param rootUrl the url of the texture
  98043. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98044. * @returns the fallback texture
  98045. */
  98046. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  98047. return null;
  98048. };
  98049. /**
  98050. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  98051. * @param data contains the texture data
  98052. * @param texture defines the BabylonJS internal texture
  98053. * @param createPolynomials will be true if polynomials have been requested
  98054. * @param onLoad defines the callback to trigger once the texture is ready
  98055. * @param onError defines the callback to trigger in case of error
  98056. */
  98057. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  98058. var engine = texture.getEngine();
  98059. var info;
  98060. var loadMipmap = false;
  98061. if (Array.isArray(imgs)) {
  98062. for (var index = 0; index < imgs.length; index++) {
  98063. var data_1 = imgs[index];
  98064. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  98065. texture.width = info.width;
  98066. texture.height = info.height;
  98067. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  98068. engine._unpackFlipY(info.isCompressed);
  98069. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  98070. if (!info.isFourCC && info.mipmapCount === 1) {
  98071. engine.generateMipMapsForCubemap(texture);
  98072. }
  98073. }
  98074. }
  98075. else {
  98076. var data = imgs;
  98077. info = BABYLON.DDSTools.GetDDSInfo(data);
  98078. texture.width = info.width;
  98079. texture.height = info.height;
  98080. if (createPolynomials) {
  98081. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  98082. }
  98083. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  98084. engine._unpackFlipY(info.isCompressed);
  98085. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  98086. if (!info.isFourCC && info.mipmapCount === 1) {
  98087. engine.generateMipMapsForCubemap(texture);
  98088. }
  98089. }
  98090. engine._setCubeMapTextureParams(loadMipmap);
  98091. texture.isReady = true;
  98092. if (onLoad) {
  98093. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  98094. }
  98095. };
  98096. /**
  98097. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  98098. * @param data contains the texture data
  98099. * @param texture defines the BabylonJS internal texture
  98100. * @param callback defines the method to call once ready to upload
  98101. */
  98102. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  98103. var info = BABYLON.DDSTools.GetDDSInfo(data);
  98104. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  98105. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  98106. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  98107. });
  98108. };
  98109. return DDSTextureLoader;
  98110. }());
  98111. // Register the loader.
  98112. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  98113. })(BABYLON || (BABYLON = {}));
  98114. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  98115. var BABYLON;
  98116. (function (BABYLON) {
  98117. /**
  98118. * Based on jsTGALoader - Javascript loader for TGA file
  98119. * By Vincent Thibault
  98120. * @see http://blog.robrowser.com/javascript-tga-loader.html
  98121. */
  98122. var TGATools = /** @class */ (function () {
  98123. function TGATools() {
  98124. }
  98125. /**
  98126. * Gets the header of a TGA file
  98127. * @param data defines the TGA data
  98128. * @returns the header
  98129. */
  98130. TGATools.GetTGAHeader = function (data) {
  98131. var offset = 0;
  98132. var header = {
  98133. id_length: data[offset++],
  98134. colormap_type: data[offset++],
  98135. image_type: data[offset++],
  98136. colormap_index: data[offset++] | data[offset++] << 8,
  98137. colormap_length: data[offset++] | data[offset++] << 8,
  98138. colormap_size: data[offset++],
  98139. origin: [
  98140. data[offset++] | data[offset++] << 8,
  98141. data[offset++] | data[offset++] << 8
  98142. ],
  98143. width: data[offset++] | data[offset++] << 8,
  98144. height: data[offset++] | data[offset++] << 8,
  98145. pixel_size: data[offset++],
  98146. flags: data[offset++]
  98147. };
  98148. return header;
  98149. };
  98150. /**
  98151. * Uploads TGA content to a Babylon Texture
  98152. * @hidden
  98153. */
  98154. TGATools.UploadContent = function (texture, data) {
  98155. // Not enough data to contain header ?
  98156. if (data.length < 19) {
  98157. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  98158. return;
  98159. }
  98160. // Read Header
  98161. var offset = 18;
  98162. var header = TGATools.GetTGAHeader(data);
  98163. // Assume it's a valid Targa file.
  98164. if (header.id_length + offset > data.length) {
  98165. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  98166. return;
  98167. }
  98168. // Skip not needed data
  98169. offset += header.id_length;
  98170. var use_rle = false;
  98171. var use_pal = false;
  98172. var use_grey = false;
  98173. // Get some informations.
  98174. switch (header.image_type) {
  98175. case TGATools._TYPE_RLE_INDEXED:
  98176. use_rle = true;
  98177. case TGATools._TYPE_INDEXED:
  98178. use_pal = true;
  98179. break;
  98180. case TGATools._TYPE_RLE_RGB:
  98181. use_rle = true;
  98182. case TGATools._TYPE_RGB:
  98183. // use_rgb = true;
  98184. break;
  98185. case TGATools._TYPE_RLE_GREY:
  98186. use_rle = true;
  98187. case TGATools._TYPE_GREY:
  98188. use_grey = true;
  98189. break;
  98190. }
  98191. var pixel_data;
  98192. // var numAlphaBits = header.flags & 0xf;
  98193. var pixel_size = header.pixel_size >> 3;
  98194. var pixel_total = header.width * header.height * pixel_size;
  98195. // Read palettes
  98196. var palettes;
  98197. if (use_pal) {
  98198. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  98199. }
  98200. // Read LRE
  98201. if (use_rle) {
  98202. pixel_data = new Uint8Array(pixel_total);
  98203. var c, count, i;
  98204. var localOffset = 0;
  98205. var pixels = new Uint8Array(pixel_size);
  98206. while (offset < pixel_total && localOffset < pixel_total) {
  98207. c = data[offset++];
  98208. count = (c & 0x7f) + 1;
  98209. // RLE pixels
  98210. if (c & 0x80) {
  98211. // Bind pixel tmp array
  98212. for (i = 0; i < pixel_size; ++i) {
  98213. pixels[i] = data[offset++];
  98214. }
  98215. // Copy pixel array
  98216. for (i = 0; i < count; ++i) {
  98217. pixel_data.set(pixels, localOffset + i * pixel_size);
  98218. }
  98219. localOffset += pixel_size * count;
  98220. }
  98221. // Raw pixels
  98222. else {
  98223. count *= pixel_size;
  98224. for (i = 0; i < count; ++i) {
  98225. pixel_data[localOffset + i] = data[offset++];
  98226. }
  98227. localOffset += count;
  98228. }
  98229. }
  98230. }
  98231. // RAW Pixels
  98232. else {
  98233. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  98234. }
  98235. // Load to texture
  98236. var x_start, y_start, x_step, y_step, y_end, x_end;
  98237. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  98238. default:
  98239. case TGATools._ORIGIN_UL:
  98240. x_start = 0;
  98241. x_step = 1;
  98242. x_end = header.width;
  98243. y_start = 0;
  98244. y_step = 1;
  98245. y_end = header.height;
  98246. break;
  98247. case TGATools._ORIGIN_BL:
  98248. x_start = 0;
  98249. x_step = 1;
  98250. x_end = header.width;
  98251. y_start = header.height - 1;
  98252. y_step = -1;
  98253. y_end = -1;
  98254. break;
  98255. case TGATools._ORIGIN_UR:
  98256. x_start = header.width - 1;
  98257. x_step = -1;
  98258. x_end = -1;
  98259. y_start = 0;
  98260. y_step = 1;
  98261. y_end = header.height;
  98262. break;
  98263. case TGATools._ORIGIN_BR:
  98264. x_start = header.width - 1;
  98265. x_step = -1;
  98266. x_end = -1;
  98267. y_start = header.height - 1;
  98268. y_step = -1;
  98269. y_end = -1;
  98270. break;
  98271. }
  98272. // Load the specify method
  98273. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  98274. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  98275. var engine = texture.getEngine();
  98276. engine._uploadDataToTextureDirectly(texture, imageData);
  98277. };
  98278. /** @hidden */
  98279. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98280. var image = pixel_data, colormap = palettes;
  98281. var width = header.width, height = header.height;
  98282. var color, i = 0, x, y;
  98283. var imageData = new Uint8Array(width * height * 4);
  98284. for (y = y_start; y !== y_end; y += y_step) {
  98285. for (x = x_start; x !== x_end; x += x_step, i++) {
  98286. color = image[i];
  98287. imageData[(x + width * y) * 4 + 3] = 255;
  98288. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  98289. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  98290. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  98291. }
  98292. }
  98293. return imageData;
  98294. };
  98295. /** @hidden */
  98296. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98297. var image = pixel_data;
  98298. var width = header.width, height = header.height;
  98299. var color, i = 0, x, y;
  98300. var imageData = new Uint8Array(width * height * 4);
  98301. for (y = y_start; y !== y_end; y += y_step) {
  98302. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  98303. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  98304. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  98305. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  98306. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  98307. imageData[(x + width * y) * 4 + 0] = r;
  98308. imageData[(x + width * y) * 4 + 1] = g;
  98309. imageData[(x + width * y) * 4 + 2] = b;
  98310. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  98311. }
  98312. }
  98313. return imageData;
  98314. };
  98315. /** @hidden */
  98316. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98317. var image = pixel_data;
  98318. var width = header.width, height = header.height;
  98319. var i = 0, x, y;
  98320. var imageData = new Uint8Array(width * height * 4);
  98321. for (y = y_start; y !== y_end; y += y_step) {
  98322. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  98323. imageData[(x + width * y) * 4 + 3] = 255;
  98324. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  98325. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  98326. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  98327. }
  98328. }
  98329. return imageData;
  98330. };
  98331. /** @hidden */
  98332. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98333. var image = pixel_data;
  98334. var width = header.width, height = header.height;
  98335. var i = 0, x, y;
  98336. var imageData = new Uint8Array(width * height * 4);
  98337. for (y = y_start; y !== y_end; y += y_step) {
  98338. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  98339. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  98340. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  98341. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  98342. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  98343. }
  98344. }
  98345. return imageData;
  98346. };
  98347. /** @hidden */
  98348. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98349. var image = pixel_data;
  98350. var width = header.width, height = header.height;
  98351. var color, i = 0, x, y;
  98352. var imageData = new Uint8Array(width * height * 4);
  98353. for (y = y_start; y !== y_end; y += y_step) {
  98354. for (x = x_start; x !== x_end; x += x_step, i++) {
  98355. color = image[i];
  98356. imageData[(x + width * y) * 4 + 0] = color;
  98357. imageData[(x + width * y) * 4 + 1] = color;
  98358. imageData[(x + width * y) * 4 + 2] = color;
  98359. imageData[(x + width * y) * 4 + 3] = 255;
  98360. }
  98361. }
  98362. return imageData;
  98363. };
  98364. /** @hidden */
  98365. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98366. var image = pixel_data;
  98367. var width = header.width, height = header.height;
  98368. var i = 0, x, y;
  98369. var imageData = new Uint8Array(width * height * 4);
  98370. for (y = y_start; y !== y_end; y += y_step) {
  98371. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  98372. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  98373. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  98374. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  98375. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  98376. }
  98377. }
  98378. return imageData;
  98379. };
  98380. //private static _TYPE_NO_DATA = 0;
  98381. TGATools._TYPE_INDEXED = 1;
  98382. TGATools._TYPE_RGB = 2;
  98383. TGATools._TYPE_GREY = 3;
  98384. TGATools._TYPE_RLE_INDEXED = 9;
  98385. TGATools._TYPE_RLE_RGB = 10;
  98386. TGATools._TYPE_RLE_GREY = 11;
  98387. TGATools._ORIGIN_MASK = 0x30;
  98388. TGATools._ORIGIN_SHIFT = 0x04;
  98389. TGATools._ORIGIN_BL = 0x00;
  98390. TGATools._ORIGIN_BR = 0x01;
  98391. TGATools._ORIGIN_UL = 0x02;
  98392. TGATools._ORIGIN_UR = 0x03;
  98393. return TGATools;
  98394. }());
  98395. BABYLON.TGATools = TGATools;
  98396. })(BABYLON || (BABYLON = {}));
  98397. //# sourceMappingURL=babylon.tga.js.map
  98398. var BABYLON;
  98399. (function (BABYLON) {
  98400. /**
  98401. * Implementation of the TGA Texture Loader.
  98402. */
  98403. var TGATextureLoader = /** @class */ (function () {
  98404. function TGATextureLoader() {
  98405. /**
  98406. * Defines wether the loader supports cascade loading the different faces.
  98407. */
  98408. this.supportCascades = false;
  98409. }
  98410. /**
  98411. * This returns if the loader support the current file information.
  98412. * @param extension defines the file extension of the file being loaded
  98413. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98414. * @param fallback defines the fallback internal texture if any
  98415. * @param isBase64 defines whether the texture is encoded as a base64
  98416. * @param isBuffer defines whether the texture data are stored as a buffer
  98417. * @returns true if the loader can load the specified file
  98418. */
  98419. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  98420. return extension.indexOf(".tga") === 0;
  98421. };
  98422. /**
  98423. * Transform the url before loading if required.
  98424. * @param rootUrl the url of the texture
  98425. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98426. * @returns the transformed texture
  98427. */
  98428. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  98429. return rootUrl;
  98430. };
  98431. /**
  98432. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  98433. * @param rootUrl the url of the texture
  98434. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98435. * @returns the fallback texture
  98436. */
  98437. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  98438. return null;
  98439. };
  98440. /**
  98441. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  98442. * @param data contains the texture data
  98443. * @param texture defines the BabylonJS internal texture
  98444. * @param createPolynomials will be true if polynomials have been requested
  98445. * @param onLoad defines the callback to trigger once the texture is ready
  98446. * @param onError defines the callback to trigger in case of error
  98447. */
  98448. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  98449. throw ".env not supported in Cube.";
  98450. };
  98451. /**
  98452. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  98453. * @param data contains the texture data
  98454. * @param texture defines the BabylonJS internal texture
  98455. * @param callback defines the method to call once ready to upload
  98456. */
  98457. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  98458. var uintData = new Uint8Array(data);
  98459. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  98460. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  98461. BABYLON.TGATools.UploadContent(texture, uintData);
  98462. });
  98463. };
  98464. return TGATextureLoader;
  98465. }());
  98466. // Register the loader.
  98467. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  98468. })(BABYLON || (BABYLON = {}));
  98469. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  98470. var BABYLON;
  98471. (function (BABYLON) {
  98472. /**
  98473. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  98474. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  98475. */
  98476. var KhronosTextureContainer = /** @class */ (function () {
  98477. /**
  98478. * Creates a new KhronosTextureContainer
  98479. * @param arrayBuffer contents of the KTX container file
  98480. * @param facesExpected should be either 1 or 6, based whether a cube texture or or
  98481. * @param threeDExpected provision for indicating that data should be a 3D texture, not implemented
  98482. * @param textureArrayExpected provision for indicating that data should be a texture array, not implemented
  98483. */
  98484. function KhronosTextureContainer(
  98485. /** contents of the KTX container file */
  98486. arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  98487. this.arrayBuffer = arrayBuffer;
  98488. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  98489. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  98490. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  98491. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  98492. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  98493. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  98494. BABYLON.Tools.Error("texture missing KTX identifier");
  98495. return;
  98496. }
  98497. // load the reset of the header in native 32 bit int
  98498. var header = new Int32Array(this.arrayBuffer, 12, 13);
  98499. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  98500. var oppositeEndianess = header[0] === 0x01020304;
  98501. // read all the header elements in order they exist in the file, without modification (sans endainness)
  98502. this.glType = oppositeEndianess ? this.switchEndianness(header[1]) : header[1]; // must be 0 for compressed textures
  98503. this.glTypeSize = oppositeEndianess ? this.switchEndianness(header[2]) : header[2]; // must be 1 for compressed textures
  98504. this.glFormat = oppositeEndianess ? this.switchEndianness(header[3]) : header[3]; // must be 0 for compressed textures
  98505. this.glInternalFormat = oppositeEndianess ? this.switchEndianness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  98506. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndianness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  98507. this.pixelWidth = oppositeEndianess ? this.switchEndianness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  98508. this.pixelHeight = oppositeEndianess ? this.switchEndianness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  98509. this.pixelDepth = oppositeEndianess ? this.switchEndianness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  98510. this.numberOfArrayElements = oppositeEndianess ? this.switchEndianness(header[9]) : header[9]; // used for texture arrays
  98511. this.numberOfFaces = oppositeEndianess ? this.switchEndianness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  98512. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndianness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  98513. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndianness(header[12]) : header[12]; // the amount of space after the header for meta-data
  98514. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  98515. if (this.glType !== 0) {
  98516. BABYLON.Tools.Error("only compressed formats currently supported");
  98517. return;
  98518. }
  98519. else {
  98520. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  98521. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  98522. }
  98523. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  98524. BABYLON.Tools.Error("only 2D textures currently supported");
  98525. return;
  98526. }
  98527. if (this.numberOfArrayElements !== 0) {
  98528. BABYLON.Tools.Error("texture arrays not currently supported");
  98529. return;
  98530. }
  98531. if (this.numberOfFaces !== facesExpected) {
  98532. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  98533. return;
  98534. }
  98535. // we now have a completely validated file, so could use existence of loadType as success
  98536. // would need to make this more elaborate & adjust checks above to support more than one load type
  98537. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  98538. }
  98539. //
  98540. /**
  98541. * Revert the endianness of a value.
  98542. * Not as fast hardware based, but will probably never need to use
  98543. * @param val defines the value to convert
  98544. * @returns the new value
  98545. */
  98546. KhronosTextureContainer.prototype.switchEndianness = function (val) {
  98547. return ((val & 0xFF) << 24)
  98548. | ((val & 0xFF00) << 8)
  98549. | ((val >> 8) & 0xFF00)
  98550. | ((val >> 24) & 0xFF);
  98551. };
  98552. /**
  98553. * Uploads KTX content to a Babylon Texture.
  98554. * It is assumed that the texture has already been created & is currently bound
  98555. * @hidden
  98556. */
  98557. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  98558. switch (this.loadType) {
  98559. case KhronosTextureContainer.COMPRESSED_2D:
  98560. this._upload2DCompressedLevels(texture, loadMipmaps);
  98561. break;
  98562. case KhronosTextureContainer.TEX_2D:
  98563. case KhronosTextureContainer.COMPRESSED_3D:
  98564. case KhronosTextureContainer.TEX_3D:
  98565. }
  98566. };
  98567. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  98568. // initialize width & height for level 1
  98569. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  98570. var width = this.pixelWidth;
  98571. var height = this.pixelHeight;
  98572. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  98573. for (var level = 0; level < mipmapCount; level++) {
  98574. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  98575. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  98576. for (var face = 0; face < this.numberOfFaces; face++) {
  98577. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  98578. var engine = texture.getEngine();
  98579. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  98580. dataOffset += imageSize; // add size of the image for the next face/mipmap
  98581. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  98582. }
  98583. width = Math.max(1.0, width * 0.5);
  98584. height = Math.max(1.0, height * 0.5);
  98585. }
  98586. };
  98587. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  98588. // load types
  98589. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  98590. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  98591. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  98592. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  98593. return KhronosTextureContainer;
  98594. }());
  98595. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  98596. })(BABYLON || (BABYLON = {}));
  98597. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  98598. var BABYLON;
  98599. (function (BABYLON) {
  98600. /**
  98601. * Implementation of the KTX Texture Loader.
  98602. */
  98603. var KTXTextureLoader = /** @class */ (function () {
  98604. function KTXTextureLoader() {
  98605. /**
  98606. * Defines wether the loader supports cascade loading the different faces.
  98607. */
  98608. this.supportCascades = false;
  98609. }
  98610. /**
  98611. * This returns if the loader support the current file information.
  98612. * @param extension defines the file extension of the file being loaded
  98613. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98614. * @param fallback defines the fallback internal texture if any
  98615. * @param isBase64 defines whether the texture is encoded as a base64
  98616. * @param isBuffer defines whether the texture data are stored as a buffer
  98617. * @returns true if the loader can load the specified file
  98618. */
  98619. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  98620. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  98621. return true;
  98622. }
  98623. return false;
  98624. };
  98625. /**
  98626. * Transform the url before loading if required.
  98627. * @param rootUrl the url of the texture
  98628. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98629. * @returns the transformed texture
  98630. */
  98631. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  98632. var lastDot = rootUrl.lastIndexOf('.');
  98633. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  98634. };
  98635. /**
  98636. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  98637. * @param rootUrl the url of the texture
  98638. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98639. * @returns the fallback texture
  98640. */
  98641. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  98642. // remove the format appended to the rootUrl in the original createCubeTexture call.
  98643. var exp = new RegExp("" + textureFormatInUse + "$");
  98644. return rootUrl.replace(exp, "");
  98645. };
  98646. /**
  98647. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  98648. * @param data contains the texture data
  98649. * @param texture defines the BabylonJS internal texture
  98650. * @param createPolynomials will be true if polynomials have been requested
  98651. * @param onLoad defines the callback to trigger once the texture is ready
  98652. * @param onError defines the callback to trigger in case of error
  98653. */
  98654. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  98655. if (Array.isArray(data)) {
  98656. return;
  98657. }
  98658. var engine = texture.getEngine();
  98659. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  98660. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  98661. engine._unpackFlipY(true);
  98662. ktx.uploadLevels(texture, texture.generateMipMaps);
  98663. texture.width = ktx.pixelWidth;
  98664. texture.height = ktx.pixelHeight;
  98665. engine._setCubeMapTextureParams(loadMipmap);
  98666. texture.isReady = true;
  98667. };
  98668. /**
  98669. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  98670. * @param data contains the texture data
  98671. * @param texture defines the BabylonJS internal texture
  98672. * @param callback defines the method to call once ready to upload
  98673. */
  98674. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  98675. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  98676. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  98677. ktx.uploadLevels(texture, texture.generateMipMaps);
  98678. });
  98679. };
  98680. return KTXTextureLoader;
  98681. }());
  98682. // Register the loader.
  98683. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  98684. })(BABYLON || (BABYLON = {}));
  98685. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  98686. var BABYLON;
  98687. (function (BABYLON) {
  98688. /**
  98689. * Sets of helpers addressing the serialization and deserialization of environment texture
  98690. * stored in a BabylonJS env file.
  98691. * Those files are usually stored as .env files.
  98692. */
  98693. var EnvironmentTextureTools = /** @class */ (function () {
  98694. function EnvironmentTextureTools() {
  98695. }
  98696. /**
  98697. * Gets the environment info from an env file.
  98698. * @param data The array buffer containing the .env bytes.
  98699. * @returns the environment file info (the json header) if successfully parsed.
  98700. */
  98701. EnvironmentTextureTools.GetEnvInfo = function (data) {
  98702. var dataView = new DataView(data);
  98703. var pos = 0;
  98704. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  98705. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  98706. BABYLON.Tools.Error('Not a babylon environment map');
  98707. return null;
  98708. }
  98709. }
  98710. // Read json manifest - collect characters up to null terminator
  98711. var manifestString = '';
  98712. var charCode = 0x00;
  98713. while ((charCode = dataView.getUint8(pos++))) {
  98714. manifestString += String.fromCharCode(charCode);
  98715. }
  98716. var manifest = JSON.parse(manifestString);
  98717. if (manifest.specular) {
  98718. // Extend the header with the position of the payload.
  98719. manifest.specular.specularDataPosition = pos;
  98720. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  98721. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  98722. }
  98723. return manifest;
  98724. };
  98725. /**
  98726. * Creates an environment texture from a loaded cube texture.
  98727. * @param texture defines the cube texture to convert in env file
  98728. * @return a promise containing the environment data if succesfull.
  98729. */
  98730. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  98731. var _this = this;
  98732. var internalTexture = texture.getInternalTexture();
  98733. if (!internalTexture) {
  98734. return Promise.reject("The cube texture is invalid.");
  98735. }
  98736. if (!texture._prefiltered) {
  98737. return Promise.reject("The cube texture is invalid (not prefiltered).");
  98738. }
  98739. var engine = internalTexture.getEngine();
  98740. if (engine && engine.premultipliedAlpha) {
  98741. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  98742. }
  98743. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  98744. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  98745. }
  98746. var canvas = engine.getRenderingCanvas();
  98747. if (!canvas) {
  98748. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  98749. }
  98750. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  98751. if (!engine.getCaps().textureFloatRender) {
  98752. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98753. if (!engine.getCaps().textureHalfFloatRender) {
  98754. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  98755. }
  98756. }
  98757. var cubeWidth = internalTexture.width;
  98758. var hostingScene = new BABYLON.Scene(engine);
  98759. var specularTextures = {};
  98760. var promises = [];
  98761. // Read and collect all mipmaps data from the cube.
  98762. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  98763. mipmapsCount = Math.round(mipmapsCount);
  98764. var _loop_1 = function (i) {
  98765. var faceWidth = Math.pow(2, mipmapsCount - i);
  98766. var _loop_2 = function (face) {
  98767. var data = texture.readPixels(face, i);
  98768. // Creates a temp texture with the face data.
  98769. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  98770. // And rgbdEncode them.
  98771. var promise = new Promise(function (resolve, reject) {
  98772. 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);
  98773. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  98774. rgbdPostProcess.onApply = function (effect) {
  98775. effect._bindTexture("textureSampler", tempTexture);
  98776. };
  98777. // As the process needs to happen on the main canvas, keep track of the current size
  98778. var currentW = engine.getRenderWidth();
  98779. var currentH = engine.getRenderHeight();
  98780. // Set the desired size for the texture
  98781. engine.setSize(faceWidth, faceWidth);
  98782. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  98783. // Reading datas from WebGL
  98784. BABYLON.Tools.ToBlob(canvas, function (blob) {
  98785. var fileReader = new FileReader();
  98786. fileReader.onload = function (event) {
  98787. var arrayBuffer = event.target.result;
  98788. specularTextures[i * 6 + face] = arrayBuffer;
  98789. resolve();
  98790. };
  98791. fileReader.readAsArrayBuffer(blob);
  98792. });
  98793. // Reapply the previous canvas size
  98794. engine.setSize(currentW, currentH);
  98795. });
  98796. });
  98797. promises.push(promise);
  98798. };
  98799. // All faces of the cube.
  98800. for (var face = 0; face < 6; face++) {
  98801. _loop_2(face);
  98802. }
  98803. };
  98804. for (var i = 0; i <= mipmapsCount; i++) {
  98805. _loop_1(i);
  98806. }
  98807. // Once all the textures haves been collected as RGBD stored in PNGs
  98808. return Promise.all(promises).then(function () {
  98809. // We can delete the hosting scene keeping track of all the creation objects
  98810. hostingScene.dispose();
  98811. // Creates the json header for the env texture
  98812. var info = {
  98813. version: 1,
  98814. width: cubeWidth,
  98815. irradiance: _this._CreateEnvTextureIrradiance(texture),
  98816. specular: {
  98817. mipmaps: [],
  98818. lodGenerationScale: texture.lodGenerationScale
  98819. }
  98820. };
  98821. // Sets the specular image data information
  98822. var position = 0;
  98823. for (var i = 0; i <= mipmapsCount; i++) {
  98824. for (var face = 0; face < 6; face++) {
  98825. var byteLength = specularTextures[i * 6 + face].byteLength;
  98826. info.specular.mipmaps.push({
  98827. length: byteLength,
  98828. position: position
  98829. });
  98830. position += byteLength;
  98831. }
  98832. }
  98833. // Encode the JSON as an array buffer
  98834. var infoString = JSON.stringify(info);
  98835. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  98836. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  98837. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  98838. infoView[i] = infoString.charCodeAt(i);
  98839. }
  98840. // Ends up with a null terminator for easier parsing
  98841. infoView[infoString.length] = 0x00;
  98842. // Computes the final required size and creates the storage
  98843. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  98844. var finalBuffer = new ArrayBuffer(totalSize);
  98845. var finalBufferView = new Uint8Array(finalBuffer);
  98846. var dataView = new DataView(finalBuffer);
  98847. // Copy the magic bytes identifying the file in
  98848. var pos = 0;
  98849. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  98850. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  98851. }
  98852. // Add the json info
  98853. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  98854. pos += infoBuffer.byteLength;
  98855. // Finally inserts the texture data
  98856. for (var i = 0; i <= mipmapsCount; i++) {
  98857. for (var face = 0; face < 6; face++) {
  98858. var dataBuffer = specularTextures[i * 6 + face];
  98859. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  98860. pos += dataBuffer.byteLength;
  98861. }
  98862. }
  98863. // Voila
  98864. return finalBuffer;
  98865. });
  98866. };
  98867. /**
  98868. * Creates a JSON representation of the spherical data.
  98869. * @param texture defines the texture containing the polynomials
  98870. * @return the JSON representation of the spherical info
  98871. */
  98872. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  98873. var polynmials = texture.sphericalPolynomial;
  98874. if (polynmials == null) {
  98875. return null;
  98876. }
  98877. return {
  98878. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  98879. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  98880. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  98881. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  98882. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  98883. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  98884. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  98885. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  98886. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  98887. };
  98888. };
  98889. /**
  98890. * Uploads the texture info contained in the env file to the GPU.
  98891. * @param texture defines the internal texture to upload to
  98892. * @param arrayBuffer defines the buffer cotaining the data to load
  98893. * @param info defines the texture info retrieved through the GetEnvInfo method
  98894. * @returns a promise
  98895. */
  98896. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  98897. if (info.version !== 1) {
  98898. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  98899. }
  98900. var specularInfo = info.specular;
  98901. if (!specularInfo) {
  98902. // Nothing else parsed so far
  98903. return Promise.resolve();
  98904. }
  98905. // Double checks the enclosed info
  98906. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  98907. mipmapsCount = Math.round(mipmapsCount) + 1;
  98908. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  98909. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  98910. }
  98911. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  98912. var imageData = new Array(mipmapsCount);
  98913. for (var i = 0; i < mipmapsCount; i++) {
  98914. imageData[i] = new Array(6);
  98915. for (var face = 0; face < 6; face++) {
  98916. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  98917. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  98918. }
  98919. }
  98920. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  98921. };
  98922. /**
  98923. * Uploads the levels of image data to the GPU.
  98924. * @param texture defines the internal texture to upload to
  98925. * @param imageData defines the array buffer views of image data [mipmap][face]
  98926. * @returns a promise
  98927. */
  98928. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  98929. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  98930. throw new Error("Texture size must be a power of two");
  98931. }
  98932. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  98933. // Gets everything ready.
  98934. var engine = texture.getEngine();
  98935. var expandTexture = false;
  98936. var generateNonLODTextures = false;
  98937. var rgbdPostProcess = null;
  98938. var cubeRtt = null;
  98939. var lodTextures = null;
  98940. var caps = engine.getCaps();
  98941. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  98942. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98943. texture.generateMipMaps = true;
  98944. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  98945. // Add extra process if texture lod is not supported
  98946. if (!caps.textureLOD) {
  98947. expandTexture = false;
  98948. generateNonLODTextures = true;
  98949. lodTextures = {};
  98950. }
  98951. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  98952. else if (engine.webGLVersion < 2) {
  98953. expandTexture = false;
  98954. }
  98955. // If half float available we can uncompress the texture
  98956. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  98957. expandTexture = true;
  98958. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98959. }
  98960. // If full float available we can uncompress the texture
  98961. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  98962. expandTexture = true;
  98963. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  98964. }
  98965. // Expand the texture if possible
  98966. if (expandTexture) {
  98967. // Simply run through the decode PP
  98968. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  98969. texture._isRGBD = false;
  98970. texture.invertY = false;
  98971. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  98972. generateDepthBuffer: false,
  98973. generateMipMaps: true,
  98974. generateStencilBuffer: false,
  98975. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  98976. type: texture.type,
  98977. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  98978. });
  98979. }
  98980. else {
  98981. texture._isRGBD = true;
  98982. texture.invertY = true;
  98983. // In case of missing support, applies the same patch than DDS files.
  98984. if (generateNonLODTextures) {
  98985. var mipSlices = 3;
  98986. var scale = texture._lodGenerationScale;
  98987. var offset = texture._lodGenerationOffset;
  98988. for (var i = 0; i < mipSlices; i++) {
  98989. //compute LOD from even spacing in smoothness (matching shader calculation)
  98990. var smoothness = i / (mipSlices - 1);
  98991. var roughness = 1 - smoothness;
  98992. var minLODIndex = offset; // roughness = 0
  98993. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  98994. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  98995. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  98996. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  98997. glTextureFromLod.isCube = true;
  98998. glTextureFromLod.invertY = true;
  98999. glTextureFromLod.generateMipMaps = false;
  99000. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  99001. // Wrap in a base texture for easy binding.
  99002. var lodTexture = new BABYLON.BaseTexture(null);
  99003. lodTexture.isCube = true;
  99004. lodTexture._texture = glTextureFromLod;
  99005. lodTextures[mipmapIndex] = lodTexture;
  99006. switch (i) {
  99007. case 0:
  99008. texture._lodTextureLow = lodTexture;
  99009. break;
  99010. case 1:
  99011. texture._lodTextureMid = lodTexture;
  99012. break;
  99013. case 2:
  99014. texture._lodTextureHigh = lodTexture;
  99015. break;
  99016. }
  99017. }
  99018. }
  99019. }
  99020. var promises = [];
  99021. var _loop_3 = function (i) {
  99022. var _loop_4 = function (face) {
  99023. // Constructs an image element from image data
  99024. var bytes = imageData[i][face];
  99025. var blob = new Blob([bytes], { type: 'image/png' });
  99026. var url = URL.createObjectURL(blob);
  99027. var image = new Image();
  99028. image.src = url;
  99029. // Enqueue promise to upload to the texture.
  99030. var promise = new Promise(function (resolve, reject) {
  99031. image.onload = function () {
  99032. if (expandTexture) {
  99033. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  99034. reject(message);
  99035. }, image);
  99036. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  99037. // Uncompress the data to a RTT
  99038. rgbdPostProcess.onApply = function (effect) {
  99039. effect._bindTexture("textureSampler", tempTexture_1);
  99040. effect.setFloat2("scale", 1, 1);
  99041. };
  99042. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  99043. // Cleanup
  99044. engine.restoreDefaultFramebuffer();
  99045. tempTexture_1.dispose();
  99046. window.URL.revokeObjectURL(url);
  99047. resolve();
  99048. });
  99049. }
  99050. else {
  99051. engine._uploadImageToTexture(texture, image, face, i);
  99052. // Upload the face to the non lod texture support
  99053. if (generateNonLODTextures) {
  99054. var lodTexture = lodTextures[i];
  99055. if (lodTexture) {
  99056. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  99057. }
  99058. }
  99059. resolve();
  99060. }
  99061. };
  99062. image.onerror = function (error) {
  99063. reject(error);
  99064. };
  99065. });
  99066. promises.push(promise);
  99067. };
  99068. // All faces
  99069. for (var face = 0; face < 6; face++) {
  99070. _loop_4(face);
  99071. }
  99072. };
  99073. // All mipmaps up to provided number of images
  99074. for (var i = 0; i < imageData.length; i++) {
  99075. _loop_3(i);
  99076. }
  99077. // Fill remaining mipmaps with black textures.
  99078. if (imageData.length < mipmapsCount) {
  99079. var data = void 0;
  99080. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  99081. var dataLength = size * size * 4;
  99082. switch (texture.type) {
  99083. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  99084. data = new Uint8Array(dataLength);
  99085. break;
  99086. }
  99087. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  99088. data = new Uint16Array(dataLength);
  99089. break;
  99090. }
  99091. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  99092. data = new Float32Array(dataLength);
  99093. break;
  99094. }
  99095. }
  99096. for (var i = imageData.length; i < mipmapsCount; i++) {
  99097. for (var face = 0; face < 6; face++) {
  99098. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  99099. }
  99100. }
  99101. }
  99102. // Once all done, finishes the cleanup and return
  99103. return Promise.all(promises).then(function () {
  99104. // Release temp RTT.
  99105. if (cubeRtt) {
  99106. engine._releaseFramebufferObjects(cubeRtt);
  99107. cubeRtt._swapAndDie(texture);
  99108. }
  99109. // Release temp Post Process.
  99110. if (rgbdPostProcess) {
  99111. rgbdPostProcess.dispose();
  99112. }
  99113. // Flag internal texture as ready in case they are in use.
  99114. if (generateNonLODTextures) {
  99115. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  99116. texture._lodTextureHigh._texture.isReady = true;
  99117. }
  99118. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  99119. texture._lodTextureMid._texture.isReady = true;
  99120. }
  99121. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  99122. texture._lodTextureLow._texture.isReady = true;
  99123. }
  99124. }
  99125. });
  99126. };
  99127. /**
  99128. * Uploads spherical polynomials information to the texture.
  99129. * @param texture defines the texture we are trying to upload the information to
  99130. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  99131. */
  99132. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  99133. if (info.version !== 1) {
  99134. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  99135. }
  99136. var irradianceInfo = info.irradiance;
  99137. if (!irradianceInfo) {
  99138. return;
  99139. }
  99140. var sp = new BABYLON.SphericalPolynomial();
  99141. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  99142. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  99143. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  99144. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  99145. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  99146. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  99147. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  99148. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  99149. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  99150. texture._sphericalPolynomial = sp;
  99151. };
  99152. /**
  99153. * Magic number identifying the env file.
  99154. */
  99155. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  99156. return EnvironmentTextureTools;
  99157. }());
  99158. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  99159. })(BABYLON || (BABYLON = {}));
  99160. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  99161. var BABYLON;
  99162. (function (BABYLON) {
  99163. /**
  99164. * Implementation of the ENV Texture Loader.
  99165. */
  99166. var ENVTextureLoader = /** @class */ (function () {
  99167. function ENVTextureLoader() {
  99168. /**
  99169. * Defines wether the loader supports cascade loading the different faces.
  99170. */
  99171. this.supportCascades = false;
  99172. }
  99173. /**
  99174. * This returns if the loader support the current file information.
  99175. * @param extension defines the file extension of the file being loaded
  99176. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99177. * @param fallback defines the fallback internal texture if any
  99178. * @param isBase64 defines whether the texture is encoded as a base64
  99179. * @param isBuffer defines whether the texture data are stored as a buffer
  99180. * @returns true if the loader can load the specified file
  99181. */
  99182. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  99183. return extension.indexOf(".env") === 0;
  99184. };
  99185. /**
  99186. * Transform the url before loading if required.
  99187. * @param rootUrl the url of the texture
  99188. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99189. * @returns the transformed texture
  99190. */
  99191. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  99192. return rootUrl;
  99193. };
  99194. /**
  99195. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  99196. * @param rootUrl the url of the texture
  99197. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99198. * @returns the fallback texture
  99199. */
  99200. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  99201. return null;
  99202. };
  99203. /**
  99204. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  99205. * @param data contains the texture data
  99206. * @param texture defines the BabylonJS internal texture
  99207. * @param createPolynomials will be true if polynomials have been requested
  99208. * @param onLoad defines the callback to trigger once the texture is ready
  99209. * @param onError defines the callback to trigger in case of error
  99210. */
  99211. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  99212. if (Array.isArray(data)) {
  99213. return;
  99214. }
  99215. data = data;
  99216. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  99217. if (info) {
  99218. texture.width = info.width;
  99219. texture.height = info.width;
  99220. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  99221. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  99222. texture.isReady = true;
  99223. if (onLoad) {
  99224. onLoad();
  99225. }
  99226. });
  99227. }
  99228. else if (onError) {
  99229. onError("Can not parse the environment file", null);
  99230. }
  99231. };
  99232. /**
  99233. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  99234. * @param data contains the texture data
  99235. * @param texture defines the BabylonJS internal texture
  99236. * @param callback defines the method to call once ready to upload
  99237. */
  99238. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  99239. throw ".env not supported in 2d.";
  99240. };
  99241. return ENVTextureLoader;
  99242. }());
  99243. // Register the loader.
  99244. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  99245. })(BABYLON || (BABYLON = {}));
  99246. //# sourceMappingURL=babylon.envTextureLoader.js.map
  99247. var BABYLON;
  99248. (function (BABYLON) {
  99249. /**
  99250. * Renders a layer on top of an existing scene
  99251. */
  99252. var UtilityLayerRenderer = /** @class */ (function () {
  99253. /**
  99254. * Instantiates a UtilityLayerRenderer
  99255. * @param originalScene the original scene that will be rendered on top of
  99256. */
  99257. function UtilityLayerRenderer(
  99258. /** the original scene that will be rendered on top of */
  99259. originalScene) {
  99260. var _this = this;
  99261. this.originalScene = originalScene;
  99262. this._pointerCaptures = {};
  99263. this._lastPointerEvents = {};
  99264. /**
  99265. * If the utility layer should automatically be rendered on top of existing scene
  99266. */
  99267. this.shouldRender = true;
  99268. /**
  99269. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  99270. */
  99271. this.onlyCheckPointerDownEvents = true;
  99272. /**
  99273. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  99274. */
  99275. this.processAllEvents = false;
  99276. /**
  99277. * Observable raised when the pointer move from the utility layer scene to the main scene
  99278. */
  99279. this.onPointerOutObservable = new BABYLON.Observable();
  99280. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  99281. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  99282. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  99283. this.utilityLayerScene._allowPostProcessClearColor = false;
  99284. originalScene.getEngine().scenes.pop();
  99285. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  99286. this.utilityLayerScene.detachControl();
  99287. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  99288. if (!_this.processAllEvents) {
  99289. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  99290. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  99291. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  99292. return;
  99293. }
  99294. }
  99295. var pointerEvent = (prePointerInfo.event);
  99296. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  99297. _this._pointerCaptures[pointerEvent.pointerId] = false;
  99298. return;
  99299. }
  99300. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  99301. if (!prePointerInfo.ray && utilityScenePick) {
  99302. prePointerInfo.ray = utilityScenePick.ray;
  99303. }
  99304. // always fire the prepointer oversvable
  99305. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  99306. // allow every non pointer down event to flow to the utility layer
  99307. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  99308. if (!prePointerInfo.skipOnPointerObservable) {
  99309. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  99310. }
  99311. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  99312. _this._pointerCaptures[pointerEvent.pointerId] = false;
  99313. }
  99314. return;
  99315. }
  99316. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  99317. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  99318. if (utilityScenePick && utilityScenePick.hit) {
  99319. if (!prePointerInfo.skipOnPointerObservable) {
  99320. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  99321. }
  99322. prePointerInfo.skipOnPointerObservable = true;
  99323. }
  99324. }
  99325. else {
  99326. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  99327. var pointerEvent_1 = (prePointerInfo.event);
  99328. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  99329. if (originalScenePick && utilityScenePick) {
  99330. // No pick in utility scene
  99331. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  99332. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  99333. // We touched an utility mesh present in the main scene
  99334. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  99335. prePointerInfo.skipOnPointerObservable = true;
  99336. }
  99337. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  99338. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  99339. }
  99340. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  99341. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  99342. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  99343. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  99344. }
  99345. }
  99346. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  99347. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  99348. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  99349. // If a previous utility layer set this, do not unset this
  99350. if (!prePointerInfo.skipOnPointerObservable) {
  99351. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  99352. }
  99353. }
  99354. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  99355. // We have a pick in both scenes but main is closer than utility
  99356. // We touched an utility mesh present in the main scene
  99357. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  99358. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  99359. prePointerInfo.skipOnPointerObservable = true;
  99360. }
  99361. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  99362. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  99363. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  99364. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  99365. }
  99366. }
  99367. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  99368. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  99369. }
  99370. }
  99371. }
  99372. });
  99373. // Render directly on top of existing scene without clearing
  99374. this.utilityLayerScene.autoClear = false;
  99375. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  99376. if (_this.shouldRender) {
  99377. _this.render();
  99378. }
  99379. });
  99380. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  99381. _this.dispose();
  99382. });
  99383. this._updateCamera();
  99384. }
  99385. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  99386. /**
  99387. * 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)
  99388. */
  99389. get: function () {
  99390. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  99391. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  99392. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  99393. UtilityLayerRenderer._DefaultUtilityLayer = null;
  99394. });
  99395. }
  99396. return UtilityLayerRenderer._DefaultUtilityLayer;
  99397. },
  99398. enumerable: true,
  99399. configurable: true
  99400. });
  99401. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  99402. /**
  99403. * 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)
  99404. */
  99405. get: function () {
  99406. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  99407. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  99408. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  99409. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  99410. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  99411. });
  99412. }
  99413. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  99414. },
  99415. enumerable: true,
  99416. configurable: true
  99417. });
  99418. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  99419. if (!prePointerInfo.skipOnPointerObservable) {
  99420. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  99421. this._lastPointerEvents[pointerEvent.pointerId] = true;
  99422. }
  99423. };
  99424. /**
  99425. * Renders the utility layers scene on top of the original scene
  99426. */
  99427. UtilityLayerRenderer.prototype.render = function () {
  99428. this._updateCamera();
  99429. if (this.utilityLayerScene.activeCamera) {
  99430. // Set the camera's scene to utility layers scene
  99431. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  99432. var camera = this.utilityLayerScene.activeCamera;
  99433. camera._scene = this.utilityLayerScene;
  99434. if (camera.leftCamera) {
  99435. camera.leftCamera._scene = this.utilityLayerScene;
  99436. }
  99437. if (camera.rightCamera) {
  99438. camera.rightCamera._scene = this.utilityLayerScene;
  99439. }
  99440. this.utilityLayerScene.render(false);
  99441. // Reset camera's scene back to original
  99442. camera._scene = oldScene;
  99443. if (camera.leftCamera) {
  99444. camera.leftCamera._scene = oldScene;
  99445. }
  99446. if (camera.rightCamera) {
  99447. camera.rightCamera._scene = oldScene;
  99448. }
  99449. }
  99450. };
  99451. /**
  99452. * Disposes of the renderer
  99453. */
  99454. UtilityLayerRenderer.prototype.dispose = function () {
  99455. this.onPointerOutObservable.clear();
  99456. if (this._afterRenderObserver) {
  99457. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  99458. }
  99459. if (this._sceneDisposeObserver) {
  99460. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  99461. }
  99462. if (this._originalPointerObserver) {
  99463. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  99464. }
  99465. this.utilityLayerScene.dispose();
  99466. };
  99467. UtilityLayerRenderer.prototype._updateCamera = function () {
  99468. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  99469. };
  99470. UtilityLayerRenderer._DefaultUtilityLayer = null;
  99471. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  99472. return UtilityLayerRenderer;
  99473. }());
  99474. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  99475. })(BABYLON || (BABYLON = {}));
  99476. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  99477. //# sourceMappingURL=babylon.behavior.js.map
  99478. var BABYLON;
  99479. (function (BABYLON) {
  99480. /**
  99481. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  99482. */
  99483. var PointerDragBehavior = /** @class */ (function () {
  99484. /**
  99485. * Creates a pointer drag behavior that can be attached to a mesh
  99486. * @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)
  99487. */
  99488. function PointerDragBehavior(options) {
  99489. /**
  99490. * 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)
  99491. */
  99492. this.maxDragAngle = 0;
  99493. /**
  99494. * @hidden
  99495. */
  99496. this._useAlternatePickedPointAboveMaxDragAngle = false;
  99497. /**
  99498. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  99499. */
  99500. this.currentDraggingPointerID = -1;
  99501. /**
  99502. * If the behavior is currently in a dragging state
  99503. */
  99504. this.dragging = false;
  99505. /**
  99506. * 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)
  99507. */
  99508. this.dragDeltaRatio = 0.2;
  99509. /**
  99510. * If the drag plane orientation should be updated during the dragging (Default: true)
  99511. */
  99512. this.updateDragPlane = true;
  99513. // Debug mode will display drag planes to help visualize behavior
  99514. this._debugMode = false;
  99515. this._moving = false;
  99516. /**
  99517. * Fires each time the attached mesh is dragged with the pointer
  99518. * * delta between last drag position and current drag position in world space
  99519. * * dragDistance along the drag axis
  99520. * * dragPlaneNormal normal of the current drag plane used during the drag
  99521. * * dragPlanePoint in world space where the drag intersects the drag plane
  99522. */
  99523. this.onDragObservable = new BABYLON.Observable();
  99524. /**
  99525. * Fires each time a drag begins (eg. mouse down on mesh)
  99526. */
  99527. this.onDragStartObservable = new BABYLON.Observable();
  99528. /**
  99529. * Fires each time a drag ends (eg. mouse release after drag)
  99530. */
  99531. this.onDragEndObservable = new BABYLON.Observable();
  99532. /**
  99533. * If the attached mesh should be moved when dragged
  99534. */
  99535. this.moveAttached = true;
  99536. /**
  99537. * If the drag behavior will react to drag events (Default: true)
  99538. */
  99539. this.enabled = true;
  99540. /**
  99541. * If camera controls should be detached during the drag
  99542. */
  99543. this.detachCameraControls = true;
  99544. /**
  99545. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  99546. */
  99547. this.useObjectOrienationForDragging = true;
  99548. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  99549. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  99550. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  99551. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  99552. this._attachedElement = null;
  99553. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  99554. this._lastPointerRay = {};
  99555. this._dragDelta = new BABYLON.Vector3();
  99556. // Variables to avoid instantiation in the below method
  99557. this._pointA = new BABYLON.Vector3(0, 0, 0);
  99558. this._pointB = new BABYLON.Vector3(0, 0, 0);
  99559. this._pointC = new BABYLON.Vector3(0, 0, 0);
  99560. this._lineA = new BABYLON.Vector3(0, 0, 0);
  99561. this._lineB = new BABYLON.Vector3(0, 0, 0);
  99562. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  99563. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  99564. this._options = options ? options : {};
  99565. var optionCount = 0;
  99566. if (this._options.dragAxis) {
  99567. optionCount++;
  99568. }
  99569. if (this._options.dragPlaneNormal) {
  99570. optionCount++;
  99571. }
  99572. if (optionCount > 1) {
  99573. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  99574. }
  99575. }
  99576. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  99577. /**
  99578. * The name of the behavior
  99579. */
  99580. get: function () {
  99581. return "PointerDrag";
  99582. },
  99583. enumerable: true,
  99584. configurable: true
  99585. });
  99586. /**
  99587. * Initializes the behavior
  99588. */
  99589. PointerDragBehavior.prototype.init = function () { };
  99590. /**
  99591. * Attaches the drag behavior the passed in mesh
  99592. * @param ownerNode The mesh that will be dragged around once attached
  99593. */
  99594. PointerDragBehavior.prototype.attach = function (ownerNode) {
  99595. var _this = this;
  99596. this._scene = ownerNode.getScene();
  99597. this._attachedNode = ownerNode;
  99598. // Initialize drag plane to not interfere with existing scene
  99599. if (!PointerDragBehavior._planeScene) {
  99600. if (this._debugMode) {
  99601. PointerDragBehavior._planeScene = this._scene;
  99602. }
  99603. else {
  99604. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  99605. PointerDragBehavior._planeScene.detachControl();
  99606. this._scene.getEngine().scenes.pop();
  99607. this._scene.onDisposeObservable.addOnce(function () {
  99608. PointerDragBehavior._planeScene.dispose();
  99609. PointerDragBehavior._planeScene = null;
  99610. });
  99611. }
  99612. }
  99613. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  99614. // State of the drag
  99615. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  99616. var pickPredicate = function (m) {
  99617. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  99618. };
  99619. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  99620. if (!_this.enabled) {
  99621. return;
  99622. }
  99623. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  99624. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  99625. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  99626. }
  99627. }
  99628. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  99629. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  99630. _this.releaseDrag();
  99631. }
  99632. }
  99633. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  99634. var pointerId = pointerInfo.event.pointerId;
  99635. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  99636. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  99637. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  99638. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  99639. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  99640. }
  99641. _this.currentDraggingPointerID = pointerId;
  99642. }
  99643. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  99644. if (!_this._lastPointerRay[pointerId]) {
  99645. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  99646. }
  99647. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  99648. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  99649. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  99650. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  99651. _this._moveDrag(pointerInfo.pickInfo.ray);
  99652. }
  99653. }
  99654. }
  99655. });
  99656. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  99657. if (_this._moving && _this.moveAttached) {
  99658. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  99659. // Slowly move mesh to avoid jitter
  99660. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  99661. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  99662. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  99663. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  99664. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  99665. }
  99666. });
  99667. };
  99668. /**
  99669. * Force relase the drag action by code.
  99670. */
  99671. PointerDragBehavior.prototype.releaseDrag = function () {
  99672. this.dragging = false;
  99673. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  99674. this.currentDraggingPointerID = -1;
  99675. this._moving = false;
  99676. // Reattach camera controls
  99677. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  99678. this._scene.activeCamera.attachControl(this._attachedElement, true);
  99679. }
  99680. };
  99681. /**
  99682. * Simulates the start of a pointer drag event on the behavior
  99683. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  99684. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  99685. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  99686. */
  99687. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  99688. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  99689. this._startDrag(pointerId, fromRay, startPickedPoint);
  99690. var lastRay = this._lastPointerRay[pointerId];
  99691. if (pointerId === PointerDragBehavior._AnyMouseID) {
  99692. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  99693. }
  99694. if (lastRay) {
  99695. // if there was a last pointer ray drag the object there
  99696. this._moveDrag(lastRay);
  99697. }
  99698. };
  99699. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  99700. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  99701. return;
  99702. }
  99703. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  99704. // Create start ray from the camera to the object
  99705. if (fromRay) {
  99706. this._startDragRay.direction.copyFrom(fromRay.direction);
  99707. this._startDragRay.origin.copyFrom(fromRay.origin);
  99708. }
  99709. else {
  99710. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  99711. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  99712. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  99713. }
  99714. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  99715. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  99716. if (pickedPoint) {
  99717. this.dragging = true;
  99718. this.currentDraggingPointerID = pointerId;
  99719. this.lastDragPosition.copyFrom(pickedPoint);
  99720. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  99721. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  99722. // Detatch camera controls
  99723. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  99724. if (this._scene.activeCamera.inputs.attachedElement) {
  99725. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  99726. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  99727. }
  99728. else {
  99729. this._attachedElement = null;
  99730. }
  99731. }
  99732. }
  99733. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  99734. };
  99735. PointerDragBehavior.prototype._moveDrag = function (ray) {
  99736. this._moving = true;
  99737. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  99738. if (pickedPoint) {
  99739. if (this.updateDragPlane) {
  99740. this._updateDragPlanePosition(ray, pickedPoint);
  99741. }
  99742. var dragLength = 0;
  99743. // depending on the drag mode option drag accordingly
  99744. if (this._options.dragAxis) {
  99745. // Convert local drag axis to world
  99746. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  99747. // Project delta drag from the drag plane onto the drag axis
  99748. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  99749. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  99750. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  99751. }
  99752. else {
  99753. dragLength = this._dragDelta.length();
  99754. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  99755. }
  99756. this._targetPosition.addInPlace(this._dragDelta);
  99757. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  99758. this.lastDragPosition.copyFrom(pickedPoint);
  99759. }
  99760. };
  99761. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  99762. var _this = this;
  99763. if (!ray) {
  99764. return null;
  99765. }
  99766. // Calculate angle between plane normal and ray
  99767. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  99768. // Correct if ray is casted from oposite side
  99769. if (angle > Math.PI / 2) {
  99770. angle = Math.PI - angle;
  99771. }
  99772. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  99773. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  99774. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  99775. // Invert ray direction along the towards object axis
  99776. this._tmpVector.copyFrom(ray.direction);
  99777. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  99778. this._alternatePickedPoint.normalize();
  99779. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  99780. this._tmpVector.addInPlace(this._alternatePickedPoint);
  99781. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  99782. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  99783. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  99784. this._alternatePickedPoint.addInPlace(this._tmpVector);
  99785. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  99786. return this._alternatePickedPoint;
  99787. }
  99788. else {
  99789. return null;
  99790. }
  99791. }
  99792. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  99793. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  99794. return pickResult.pickedPoint;
  99795. }
  99796. else {
  99797. return null;
  99798. }
  99799. };
  99800. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  99801. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  99802. this._pointA.copyFrom(dragPlanePosition);
  99803. if (this._options.dragAxis) {
  99804. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  99805. // Calculate plane normal in direction of camera but perpendicular to drag axis
  99806. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  99807. ray.origin.subtractToRef(this._pointA, this._pointC);
  99808. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  99809. // Get perpendicular line from direction to camera and drag axis
  99810. this._pointB.subtractToRef(this._pointA, this._lineA);
  99811. this._pointC.subtractToRef(this._pointA, this._lineB);
  99812. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  99813. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  99814. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  99815. this._lookAt.normalize();
  99816. this._dragPlane.position.copyFrom(this._pointA);
  99817. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  99818. this._dragPlane.lookAt(this._lookAt);
  99819. }
  99820. else if (this._options.dragPlaneNormal) {
  99821. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  99822. this._dragPlane.position.copyFrom(this._pointA);
  99823. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  99824. this._dragPlane.lookAt(this._lookAt);
  99825. }
  99826. else {
  99827. this._dragPlane.position.copyFrom(this._pointA);
  99828. this._dragPlane.lookAt(ray.origin);
  99829. }
  99830. this._dragPlane.computeWorldMatrix(true);
  99831. };
  99832. /**
  99833. * Detaches the behavior from the mesh
  99834. */
  99835. PointerDragBehavior.prototype.detach = function () {
  99836. if (this._pointerObserver) {
  99837. this._scene.onPointerObservable.remove(this._pointerObserver);
  99838. }
  99839. if (this._beforeRenderObserver) {
  99840. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  99841. }
  99842. };
  99843. PointerDragBehavior._AnyMouseID = -2;
  99844. return PointerDragBehavior;
  99845. }());
  99846. BABYLON.PointerDragBehavior = PointerDragBehavior;
  99847. })(BABYLON || (BABYLON = {}));
  99848. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  99849. var BABYLON;
  99850. (function (BABYLON) {
  99851. /**
  99852. * A behavior that when attached to a mesh will allow the mesh to be scaled
  99853. */
  99854. var MultiPointerScaleBehavior = /** @class */ (function () {
  99855. /**
  99856. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  99857. */
  99858. function MultiPointerScaleBehavior() {
  99859. this._startDistance = 0;
  99860. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  99861. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  99862. this._sceneRenderObserver = null;
  99863. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  99864. this._dragBehaviorA.moveAttached = false;
  99865. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  99866. this._dragBehaviorB.moveAttached = false;
  99867. }
  99868. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  99869. /**
  99870. * The name of the behavior
  99871. */
  99872. get: function () {
  99873. return "MultiPointerScale";
  99874. },
  99875. enumerable: true,
  99876. configurable: true
  99877. });
  99878. /**
  99879. * Initializes the behavior
  99880. */
  99881. MultiPointerScaleBehavior.prototype.init = function () { };
  99882. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  99883. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  99884. };
  99885. /**
  99886. * Attaches the scale behavior the passed in mesh
  99887. * @param ownerNode The mesh that will be scaled around once attached
  99888. */
  99889. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  99890. var _this = this;
  99891. this._ownerNode = ownerNode;
  99892. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  99893. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  99894. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99895. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  99896. _this._dragBehaviorA.releaseDrag();
  99897. }
  99898. else {
  99899. _this._initialScale.copyFrom(ownerNode.scaling);
  99900. _this._startDistance = _this._getCurrentDistance();
  99901. }
  99902. }
  99903. });
  99904. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  99905. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99906. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  99907. _this._dragBehaviorB.releaseDrag();
  99908. }
  99909. else {
  99910. _this._initialScale.copyFrom(ownerNode.scaling);
  99911. _this._startDistance = _this._getCurrentDistance();
  99912. }
  99913. }
  99914. });
  99915. // Once both drag behaviors are active scale based on the distance between the two pointers
  99916. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  99917. behavior.onDragObservable.add(function () {
  99918. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99919. var ratio = _this._getCurrentDistance() / _this._startDistance;
  99920. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  99921. }
  99922. });
  99923. });
  99924. ownerNode.addBehavior(this._dragBehaviorA);
  99925. ownerNode.addBehavior(this._dragBehaviorB);
  99926. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  99927. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  99928. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99929. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  99930. if (change.length() > 0.01) {
  99931. ownerNode.scaling.addInPlace(change);
  99932. }
  99933. }
  99934. });
  99935. };
  99936. /**
  99937. * Detaches the behavior from the mesh
  99938. */
  99939. MultiPointerScaleBehavior.prototype.detach = function () {
  99940. var _this = this;
  99941. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  99942. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  99943. behavior.onDragStartObservable.clear();
  99944. behavior.onDragObservable.clear();
  99945. _this._ownerNode.removeBehavior(behavior);
  99946. });
  99947. };
  99948. return MultiPointerScaleBehavior;
  99949. }());
  99950. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  99951. })(BABYLON || (BABYLON = {}));
  99952. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  99953. var BABYLON;
  99954. (function (BABYLON) {
  99955. /**
  99956. * 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
  99957. */
  99958. var SixDofDragBehavior = /** @class */ (function () {
  99959. /**
  99960. * Instantiates a behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray
  99961. */
  99962. function SixDofDragBehavior() {
  99963. this._sceneRenderObserver = null;
  99964. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  99965. this._moving = false;
  99966. this._startingOrientation = new BABYLON.Quaternion();
  99967. /**
  99968. * 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)
  99969. */
  99970. this.zDragFactor = 3;
  99971. /**
  99972. * If the behavior is currently in a dragging state
  99973. */
  99974. this.dragging = false;
  99975. /**
  99976. * 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)
  99977. */
  99978. this.dragDeltaRatio = 0.2;
  99979. /**
  99980. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  99981. */
  99982. this.currentDraggingPointerID = -1;
  99983. /**
  99984. * If camera controls should be detached during the drag
  99985. */
  99986. this.detachCameraControls = true;
  99987. /**
  99988. * Fires each time a drag starts
  99989. */
  99990. this.onDragStartObservable = new BABYLON.Observable();
  99991. /**
  99992. * Fires each time a drag ends (eg. mouse release after drag)
  99993. */
  99994. this.onDragEndObservable = new BABYLON.Observable();
  99995. }
  99996. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  99997. /**
  99998. * The name of the behavior
  99999. */
  100000. get: function () {
  100001. return "SixDofDrag";
  100002. },
  100003. enumerable: true,
  100004. configurable: true
  100005. });
  100006. /**
  100007. * Initializes the behavior
  100008. */
  100009. SixDofDragBehavior.prototype.init = function () { };
  100010. /**
  100011. * Attaches the scale behavior the passed in mesh
  100012. * @param ownerNode The mesh that will be scaled around once attached
  100013. */
  100014. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  100015. var _this = this;
  100016. this._ownerNode = ownerNode;
  100017. this._scene = this._ownerNode.getScene();
  100018. if (!SixDofDragBehavior._virtualScene) {
  100019. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  100020. this._scene.getEngine().scenes.pop();
  100021. }
  100022. var pickedMesh = null;
  100023. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  100024. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  100025. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  100026. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  100027. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  100028. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  100029. var pickPredicate = function (m) {
  100030. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  100031. };
  100032. var attachedElement = null;
  100033. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  100034. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  100035. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  100036. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  100037. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  100038. }
  100039. pickedMesh = _this._ownerNode;
  100040. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  100041. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  100042. // Set position and orientation of the controller
  100043. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  100044. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  100045. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  100046. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  100047. pickedMesh.computeWorldMatrix();
  100048. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  100049. if (!pickedMesh.rotationQuaternion) {
  100050. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  100051. }
  100052. var oldParent = pickedMesh.parent;
  100053. pickedMesh.setParent(null);
  100054. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  100055. pickedMesh.setParent(oldParent);
  100056. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  100057. // Update state
  100058. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  100059. _this.dragging = true;
  100060. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  100061. // Detatch camera controls
  100062. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  100063. if (_this._scene.activeCamera.inputs.attachedElement) {
  100064. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  100065. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  100066. }
  100067. else {
  100068. attachedElement = null;
  100069. }
  100070. }
  100071. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  100072. _this.onDragStartObservable.notifyObservers({});
  100073. }
  100074. }
  100075. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  100076. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  100077. _this.dragging = false;
  100078. _this._moving = false;
  100079. _this.currentDraggingPointerID = -1;
  100080. pickedMesh = null;
  100081. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  100082. // Reattach camera controls
  100083. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  100084. _this._scene.activeCamera.attachControl(attachedElement, true);
  100085. }
  100086. _this.onDragEndObservable.notifyObservers({});
  100087. }
  100088. }
  100089. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  100090. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  100091. var zDragFactor = _this.zDragFactor;
  100092. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  100093. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  100094. zDragFactor = 0;
  100095. }
  100096. // Calculate controller drag distance in controller space
  100097. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  100098. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  100099. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  100100. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  100101. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  100102. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  100103. if (_this._virtualDragMesh.position.z < 0) {
  100104. _this._virtualDragMesh.position.z = 0;
  100105. }
  100106. // Update the controller position
  100107. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  100108. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  100109. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  100110. // Move the virtualObjectsPosition into the picked mesh's space if needed
  100111. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  100112. if (pickedMesh.parent) {
  100113. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  100114. }
  100115. if (!_this._moving) {
  100116. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  100117. }
  100118. _this._moving = true;
  100119. }
  100120. }
  100121. });
  100122. var tmpQuaternion = new BABYLON.Quaternion();
  100123. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  100124. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  100125. if (_this.dragging && _this._moving && pickedMesh) {
  100126. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  100127. // Slowly move mesh to avoid jitter
  100128. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  100129. // Get change in rotation
  100130. tmpQuaternion.copyFrom(_this._startingOrientation);
  100131. tmpQuaternion.x = -tmpQuaternion.x;
  100132. tmpQuaternion.y = -tmpQuaternion.y;
  100133. tmpQuaternion.z = -tmpQuaternion.z;
  100134. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  100135. // Convert change in rotation to only y axis rotation
  100136. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  100137. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  100138. // Slowly move mesh to avoid jitter
  100139. var oldParent = pickedMesh.parent;
  100140. pickedMesh.setParent(null);
  100141. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  100142. pickedMesh.setParent(oldParent);
  100143. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  100144. }
  100145. });
  100146. };
  100147. /**
  100148. * Detaches the behavior from the mesh
  100149. */
  100150. SixDofDragBehavior.prototype.detach = function () {
  100151. if (this._scene) {
  100152. this._scene.onPointerObservable.remove(this._pointerObserver);
  100153. }
  100154. if (this._ownerNode) {
  100155. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  100156. }
  100157. if (this._virtualOriginMesh) {
  100158. this._virtualOriginMesh.dispose();
  100159. }
  100160. if (this._virtualDragMesh) {
  100161. this._virtualDragMesh.dispose();
  100162. }
  100163. this.onDragEndObservable.clear();
  100164. this.onDragStartObservable.clear();
  100165. };
  100166. return SixDofDragBehavior;
  100167. }());
  100168. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  100169. })(BABYLON || (BABYLON = {}));
  100170. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  100171. var BABYLON;
  100172. (function (BABYLON) {
  100173. /**
  100174. * @hidden
  100175. */
  100176. var FaceDirectionInfo = /** @class */ (function () {
  100177. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  100178. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  100179. if (diff === void 0) { diff = 0; }
  100180. if (ignore === void 0) { ignore = false; }
  100181. this.direction = direction;
  100182. this.rotatedDirection = rotatedDirection;
  100183. this.diff = diff;
  100184. this.ignore = ignore;
  100185. }
  100186. return FaceDirectionInfo;
  100187. }());
  100188. /**
  100189. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  100190. */
  100191. var AttachToBoxBehavior = /** @class */ (function () {
  100192. /**
  100193. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  100194. * @param ui The transform node that should be attched to the mesh
  100195. */
  100196. function AttachToBoxBehavior(ui) {
  100197. this.ui = ui;
  100198. /**
  100199. * The name of the behavior
  100200. */
  100201. this.name = "AttachToBoxBehavior";
  100202. /**
  100203. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  100204. */
  100205. this.distanceAwayFromFace = 0.15;
  100206. /**
  100207. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  100208. */
  100209. this.distanceAwayFromBottomOfFace = 0.15;
  100210. 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))];
  100211. this._tmpMatrix = new BABYLON.Matrix();
  100212. this._tmpVector = new BABYLON.Vector3();
  100213. this._zeroVector = BABYLON.Vector3.Zero();
  100214. this._lookAtTmpMatrix = new BABYLON.Matrix();
  100215. /* Does nothing */
  100216. }
  100217. /**
  100218. * Initializes the behavior
  100219. */
  100220. AttachToBoxBehavior.prototype.init = function () {
  100221. /* Does nothing */
  100222. };
  100223. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  100224. var _this = this;
  100225. // Go over each face and calculate the angle between the face's normal and targetDirection
  100226. this._faceVectors.forEach(function (v) {
  100227. if (!_this._target.rotationQuaternion) {
  100228. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  100229. }
  100230. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  100231. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  100232. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  100233. });
  100234. // Return the face information of the one with the normal closeset to target direction
  100235. return this._faceVectors.reduce(function (min, p) {
  100236. if (min.ignore) {
  100237. return p;
  100238. }
  100239. else if (p.ignore) {
  100240. return min;
  100241. }
  100242. else {
  100243. return min.diff < p.diff ? min : p;
  100244. }
  100245. }, this._faceVectors[0]);
  100246. };
  100247. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  100248. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  100249. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  100250. this._lookAtTmpMatrix.invert();
  100251. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  100252. };
  100253. /**
  100254. * Attaches the AttachToBoxBehavior to the passed in mesh
  100255. * @param target The mesh that the specified node will be attached to
  100256. */
  100257. AttachToBoxBehavior.prototype.attach = function (target) {
  100258. var _this = this;
  100259. this._target = target;
  100260. this._scene = this._target.getScene();
  100261. // Every frame, update the app bars position
  100262. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  100263. if (!_this._scene.activeCamera) {
  100264. return;
  100265. }
  100266. // Find the face closest to the cameras position
  100267. var cameraPos = _this._scene.activeCamera.position;
  100268. if (_this._scene.activeCamera.devicePosition) {
  100269. cameraPos = _this._scene.activeCamera.devicePosition;
  100270. }
  100271. var facing = _this._closestFace(cameraPos.subtract(target.position));
  100272. if (_this._scene.activeCamera.leftCamera) {
  100273. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  100274. }
  100275. else {
  100276. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  100277. }
  100278. // Get camera up direction
  100279. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  100280. // Ignore faces to not select a parrelel face for the up vector of the UI
  100281. _this._faceVectors.forEach(function (v) {
  100282. if (facing.direction.x && v.direction.x) {
  100283. v.ignore = true;
  100284. }
  100285. if (facing.direction.y && v.direction.y) {
  100286. v.ignore = true;
  100287. }
  100288. if (facing.direction.z && v.direction.z) {
  100289. v.ignore = true;
  100290. }
  100291. });
  100292. var facingUp = _this._closestFace(_this._tmpVector);
  100293. // Unignore faces
  100294. _this._faceVectors.forEach(function (v) {
  100295. v.ignore = false;
  100296. });
  100297. // Position the app bar on that face
  100298. _this.ui.position.copyFrom(target.position);
  100299. if (facing.direction.x) {
  100300. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  100301. _this.ui.position.addInPlace(_this._tmpVector);
  100302. }
  100303. if (facing.direction.y) {
  100304. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  100305. _this.ui.position.addInPlace(_this._tmpVector);
  100306. }
  100307. if (facing.direction.z) {
  100308. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  100309. _this.ui.position.addInPlace(_this._tmpVector);
  100310. }
  100311. // Rotate to be oriented properly to the camera
  100312. if (!_this.ui.rotationQuaternion) {
  100313. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  100314. }
  100315. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  100316. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  100317. // Place ui the correct distance from the bottom of the mesh
  100318. if (facingUp.direction.x) {
  100319. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  100320. }
  100321. if (facingUp.direction.y) {
  100322. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  100323. }
  100324. if (facingUp.direction.z) {
  100325. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  100326. }
  100327. _this.ui.position.addInPlace(_this._tmpVector);
  100328. });
  100329. };
  100330. /**
  100331. * Detaches the behavior from the mesh
  100332. */
  100333. AttachToBoxBehavior.prototype.detach = function () {
  100334. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  100335. };
  100336. return AttachToBoxBehavior;
  100337. }());
  100338. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  100339. })(BABYLON || (BABYLON = {}));
  100340. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  100341. var BABYLON;
  100342. (function (BABYLON) {
  100343. /**
  100344. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  100345. */
  100346. var FadeInOutBehavior = /** @class */ (function () {
  100347. /**
  100348. * Instatiates the FadeInOutBehavior
  100349. */
  100350. function FadeInOutBehavior() {
  100351. var _this = this;
  100352. /**
  100353. * Time in milliseconds to delay before fading in (Default: 0)
  100354. */
  100355. this.delay = 0;
  100356. /**
  100357. * Time in milliseconds for the mesh to fade in (Default: 300)
  100358. */
  100359. this.fadeInTime = 300;
  100360. this._millisecondsPerFrame = 1000 / 60;
  100361. this._hovered = false;
  100362. this._hoverValue = 0;
  100363. this._ownerNode = null;
  100364. this._update = function () {
  100365. if (_this._ownerNode) {
  100366. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  100367. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  100368. if (_this._ownerNode.visibility > 1) {
  100369. _this._setAllVisibility(_this._ownerNode, 1);
  100370. _this._hoverValue = _this.fadeInTime + _this.delay;
  100371. return;
  100372. }
  100373. else if (_this._ownerNode.visibility < 0) {
  100374. _this._setAllVisibility(_this._ownerNode, 0);
  100375. if (_this._hoverValue < 0) {
  100376. _this._hoverValue = 0;
  100377. return;
  100378. }
  100379. }
  100380. setTimeout(_this._update, _this._millisecondsPerFrame);
  100381. }
  100382. };
  100383. }
  100384. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  100385. /**
  100386. * The name of the behavior
  100387. */
  100388. get: function () {
  100389. return "FadeInOut";
  100390. },
  100391. enumerable: true,
  100392. configurable: true
  100393. });
  100394. /**
  100395. * Initializes the behavior
  100396. */
  100397. FadeInOutBehavior.prototype.init = function () {
  100398. };
  100399. /**
  100400. * Attaches the fade behavior on the passed in mesh
  100401. * @param ownerNode The mesh that will be faded in/out once attached
  100402. */
  100403. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  100404. this._ownerNode = ownerNode;
  100405. this._setAllVisibility(this._ownerNode, 0);
  100406. };
  100407. /**
  100408. * Detaches the behavior from the mesh
  100409. */
  100410. FadeInOutBehavior.prototype.detach = function () {
  100411. this._ownerNode = null;
  100412. };
  100413. /**
  100414. * Triggers the mesh to begin fading in or out
  100415. * @param value if the object should fade in or out (true to fade in)
  100416. */
  100417. FadeInOutBehavior.prototype.fadeIn = function (value) {
  100418. this._hovered = value;
  100419. this._update();
  100420. };
  100421. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  100422. var _this = this;
  100423. mesh.visibility = value;
  100424. mesh.getChildMeshes().forEach(function (c) {
  100425. _this._setAllVisibility(c, value);
  100426. });
  100427. };
  100428. return FadeInOutBehavior;
  100429. }());
  100430. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  100431. })(BABYLON || (BABYLON = {}));
  100432. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  100433. var BABYLON;
  100434. (function (BABYLON) {
  100435. /**
  100436. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  100437. */
  100438. var Gizmo = /** @class */ (function () {
  100439. /**
  100440. * Creates a gizmo
  100441. * @param gizmoLayer The utility layer the gizmo will be added to
  100442. */
  100443. function Gizmo(
  100444. /** The utility layer the gizmo will be added to */
  100445. gizmoLayer) {
  100446. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100447. var _this = this;
  100448. this.gizmoLayer = gizmoLayer;
  100449. /**
  100450. * Ratio for the scale of the gizmo (Default: 1)
  100451. */
  100452. this.scaleRatio = 1;
  100453. this._tmpMatrix = new BABYLON.Matrix();
  100454. /**
  100455. * If a custom mesh has been set (Default: false)
  100456. */
  100457. this._customMeshSet = false;
  100458. /**
  100459. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  100460. */
  100461. this.updateGizmoRotationToMatchAttachedMesh = true;
  100462. /**
  100463. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  100464. */
  100465. this.updateGizmoPositionToMatchAttachedMesh = true;
  100466. /**
  100467. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  100468. */
  100469. this._updateScale = true;
  100470. this._interactionsEnabled = true;
  100471. this._tempVector = new BABYLON.Vector3();
  100472. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  100473. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  100474. _this._update();
  100475. });
  100476. this.attachedMesh = null;
  100477. }
  100478. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  100479. /**
  100480. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  100481. * * When set, interactions will be enabled
  100482. */
  100483. get: function () {
  100484. return this._attachedMesh;
  100485. },
  100486. set: function (value) {
  100487. this._attachedMesh = value;
  100488. this._rootMesh.setEnabled(value ? true : false);
  100489. this._attachedMeshChanged(value);
  100490. },
  100491. enumerable: true,
  100492. configurable: true
  100493. });
  100494. /**
  100495. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  100496. * @param mesh The mesh to replace the default mesh of the gizmo
  100497. */
  100498. Gizmo.prototype.setCustomMesh = function (mesh) {
  100499. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  100500. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  100501. }
  100502. this._rootMesh.getChildMeshes().forEach(function (c) {
  100503. c.dispose();
  100504. });
  100505. mesh.parent = this._rootMesh;
  100506. this._customMeshSet = true;
  100507. };
  100508. Gizmo.prototype._attachedMeshChanged = function (value) {
  100509. };
  100510. /**
  100511. * @hidden
  100512. * Updates the gizmo to match the attached mesh's position/rotation
  100513. */
  100514. Gizmo.prototype._update = function () {
  100515. if (this.attachedMesh) {
  100516. if (this.updateGizmoRotationToMatchAttachedMesh) {
  100517. if (!this._rootMesh.rotationQuaternion) {
  100518. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  100519. }
  100520. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  100521. this._tempVector.copyFrom(this.attachedMesh.scaling);
  100522. if (this.attachedMesh.scaling.x < 0) {
  100523. this.attachedMesh.scaling.x *= -1;
  100524. }
  100525. if (this.attachedMesh.scaling.y < 0) {
  100526. this.attachedMesh.scaling.y *= -1;
  100527. }
  100528. if (this.attachedMesh.scaling.z < 0) {
  100529. this.attachedMesh.scaling.z *= -1;
  100530. }
  100531. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  100532. this.attachedMesh.scaling.copyFrom(this._tempVector);
  100533. this.attachedMesh.computeWorldMatrix();
  100534. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  100535. }
  100536. else if (this._rootMesh.rotationQuaternion) {
  100537. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  100538. }
  100539. if (this.updateGizmoPositionToMatchAttachedMesh) {
  100540. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  100541. }
  100542. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  100543. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  100544. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  100545. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  100546. }
  100547. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  100548. var dist = this._tempVector.length() * this.scaleRatio;
  100549. this._rootMesh.scaling.set(dist, dist, dist);
  100550. }
  100551. }
  100552. };
  100553. /**
  100554. * Disposes of the gizmo
  100555. */
  100556. Gizmo.prototype.dispose = function () {
  100557. this._rootMesh.dispose();
  100558. if (this._beforeRenderObserver) {
  100559. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  100560. }
  100561. };
  100562. return Gizmo;
  100563. }());
  100564. BABYLON.Gizmo = Gizmo;
  100565. })(BABYLON || (BABYLON = {}));
  100566. //# sourceMappingURL=babylon.gizmo.js.map
  100567. var BABYLON;
  100568. (function (BABYLON) {
  100569. /**
  100570. * Single axis drag gizmo
  100571. */
  100572. var AxisDragGizmo = /** @class */ (function (_super) {
  100573. __extends(AxisDragGizmo, _super);
  100574. /**
  100575. * Creates an AxisDragGizmo
  100576. * @param gizmoLayer The utility layer the gizmo will be added to
  100577. * @param dragAxis The axis which the gizmo will be able to drag on
  100578. * @param color The color of the gizmo
  100579. */
  100580. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  100581. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  100582. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100583. var _this = _super.call(this, gizmoLayer) || this;
  100584. _this._pointerObserver = null;
  100585. /**
  100586. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  100587. */
  100588. _this.snapDistance = 0;
  100589. /**
  100590. * Event that fires each time the gizmo snaps to a new location.
  100591. * * snapDistance is the the change in distance
  100592. */
  100593. _this.onSnapObservable = new BABYLON.Observable();
  100594. // Create Material
  100595. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100596. coloredMaterial.disableLighting = true;
  100597. coloredMaterial.emissiveColor = color;
  100598. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100599. hoverMaterial.disableLighting = true;
  100600. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  100601. // Build mesh on root node
  100602. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  100603. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  100604. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  100605. arrowTail.color = coloredMaterial.emissiveColor;
  100606. arrow.addChild(arrowMesh);
  100607. arrow.addChild(arrowTail);
  100608. // Position arrow pointing in its drag axis
  100609. arrowMesh.scaling.scaleInPlace(0.05);
  100610. arrowMesh.material = coloredMaterial;
  100611. arrowMesh.rotation.x = Math.PI / 2;
  100612. arrowMesh.position.z += 0.3;
  100613. arrowTail.scaling.scaleInPlace(0.26);
  100614. arrowTail.rotation.x = Math.PI / 2;
  100615. arrowTail.material = coloredMaterial;
  100616. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  100617. arrow.scaling.scaleInPlace(1 / 3);
  100618. _this._rootMesh.addChild(arrow);
  100619. var currentSnapDragDistance = 0;
  100620. var tmpVector = new BABYLON.Vector3();
  100621. var tmpSnapEvent = { snapDistance: 0 };
  100622. // Add drag behavior to handle events when the gizmo is dragged
  100623. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  100624. _this.dragBehavior.moveAttached = false;
  100625. _this._rootMesh.addBehavior(_this.dragBehavior);
  100626. var localDelta = new BABYLON.Vector3();
  100627. var tmpMatrix = new BABYLON.Matrix();
  100628. _this.dragBehavior.onDragObservable.add(function (event) {
  100629. if (_this.attachedMesh) {
  100630. // Convert delta to local translation if it has a parent
  100631. if (_this.attachedMesh.parent) {
  100632. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  100633. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  100634. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  100635. }
  100636. else {
  100637. localDelta.copyFrom(event.delta);
  100638. }
  100639. // Snapping logic
  100640. if (_this.snapDistance == 0) {
  100641. _this.attachedMesh.position.addInPlace(localDelta);
  100642. }
  100643. else {
  100644. currentSnapDragDistance += event.dragDistance;
  100645. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  100646. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  100647. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  100648. localDelta.normalizeToRef(tmpVector);
  100649. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  100650. _this.attachedMesh.position.addInPlace(tmpVector);
  100651. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  100652. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  100653. }
  100654. }
  100655. }
  100656. });
  100657. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  100658. if (_this._customMeshSet) {
  100659. return;
  100660. }
  100661. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  100662. var material = isHovered ? hoverMaterial : coloredMaterial;
  100663. _this._rootMesh.getChildMeshes().forEach(function (m) {
  100664. m.material = material;
  100665. if (m.color) {
  100666. m.color = material.emissiveColor;
  100667. }
  100668. });
  100669. });
  100670. return _this;
  100671. }
  100672. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  100673. if (this.dragBehavior) {
  100674. this.dragBehavior.enabled = value ? true : false;
  100675. }
  100676. };
  100677. /**
  100678. * Disposes of the gizmo
  100679. */
  100680. AxisDragGizmo.prototype.dispose = function () {
  100681. this.onSnapObservable.clear();
  100682. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  100683. this.dragBehavior.detach();
  100684. _super.prototype.dispose.call(this);
  100685. };
  100686. return AxisDragGizmo;
  100687. }(BABYLON.Gizmo));
  100688. BABYLON.AxisDragGizmo = AxisDragGizmo;
  100689. })(BABYLON || (BABYLON = {}));
  100690. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  100691. var BABYLON;
  100692. (function (BABYLON) {
  100693. /**
  100694. * Single axis scale gizmo
  100695. */
  100696. var AxisScaleGizmo = /** @class */ (function (_super) {
  100697. __extends(AxisScaleGizmo, _super);
  100698. /**
  100699. * Creates an AxisScaleGizmo
  100700. * @param gizmoLayer The utility layer the gizmo will be added to
  100701. * @param dragAxis The axis which the gizmo will be able to scale on
  100702. * @param color The color of the gizmo
  100703. */
  100704. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  100705. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  100706. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100707. var _this = _super.call(this, gizmoLayer) || this;
  100708. _this._pointerObserver = null;
  100709. /**
  100710. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  100711. */
  100712. _this.snapDistance = 0;
  100713. /**
  100714. * Event that fires each time the gizmo snaps to a new location.
  100715. * * snapDistance is the the change in distance
  100716. */
  100717. _this.onSnapObservable = new BABYLON.Observable();
  100718. /**
  100719. * If the scaling operation should be done on all axis (default: false)
  100720. */
  100721. _this.uniformScaling = false;
  100722. // Create Material
  100723. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100724. _this._coloredMaterial.disableLighting = true;
  100725. _this._coloredMaterial.emissiveColor = color;
  100726. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100727. hoverMaterial.disableLighting = true;
  100728. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  100729. // Build mesh on root node
  100730. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  100731. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  100732. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  100733. arrowTail.color = _this._coloredMaterial.emissiveColor;
  100734. arrow.addChild(arrowMesh);
  100735. arrow.addChild(arrowTail);
  100736. // Position arrow pointing in its drag axis
  100737. arrowMesh.scaling.scaleInPlace(0.1);
  100738. arrowMesh.material = _this._coloredMaterial;
  100739. arrowMesh.rotation.x = Math.PI / 2;
  100740. arrowMesh.position.z += 0.3;
  100741. arrowTail.scaling.scaleInPlace(0.26);
  100742. arrowTail.rotation.x = Math.PI / 2;
  100743. arrowTail.material = _this._coloredMaterial;
  100744. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  100745. _this._rootMesh.addChild(arrow);
  100746. arrow.scaling.scaleInPlace(1 / 3);
  100747. // Add drag behavior to handle events when the gizmo is dragged
  100748. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  100749. _this.dragBehavior.moveAttached = false;
  100750. _this._rootMesh.addBehavior(_this.dragBehavior);
  100751. var currentSnapDragDistance = 0;
  100752. var tmpVector = new BABYLON.Vector3();
  100753. var tmpSnapEvent = { snapDistance: 0 };
  100754. _this.dragBehavior.onDragObservable.add(function (event) {
  100755. if (_this.attachedMesh) {
  100756. // Snapping logic
  100757. var snapped = false;
  100758. var dragSteps = 0;
  100759. if (_this.uniformScaling) {
  100760. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  100761. if (tmpVector.y < 0) {
  100762. tmpVector.scaleInPlace(-1);
  100763. }
  100764. }
  100765. else {
  100766. tmpVector.copyFrom(dragAxis);
  100767. }
  100768. if (_this.snapDistance == 0) {
  100769. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  100770. }
  100771. else {
  100772. currentSnapDragDistance += event.dragDistance;
  100773. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  100774. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  100775. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  100776. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  100777. snapped = true;
  100778. }
  100779. else {
  100780. tmpVector.scaleInPlace(0);
  100781. }
  100782. }
  100783. _this.attachedMesh.scaling.addInPlace(tmpVector);
  100784. if (snapped) {
  100785. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  100786. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  100787. }
  100788. }
  100789. });
  100790. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  100791. if (_this._customMeshSet) {
  100792. return;
  100793. }
  100794. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  100795. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  100796. _this._rootMesh.getChildMeshes().forEach(function (m) {
  100797. m.material = material;
  100798. if (m.color) {
  100799. m.color = material.emissiveColor;
  100800. }
  100801. });
  100802. });
  100803. return _this;
  100804. }
  100805. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  100806. if (this.dragBehavior) {
  100807. this.dragBehavior.enabled = value ? true : false;
  100808. }
  100809. };
  100810. /**
  100811. * Disposes of the gizmo
  100812. */
  100813. AxisScaleGizmo.prototype.dispose = function () {
  100814. this.onSnapObservable.clear();
  100815. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  100816. this.dragBehavior.detach();
  100817. _super.prototype.dispose.call(this);
  100818. };
  100819. /**
  100820. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  100821. * @param mesh The mesh to replace the default mesh of the gizmo
  100822. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  100823. */
  100824. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  100825. var _this = this;
  100826. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  100827. _super.prototype.setCustomMesh.call(this, mesh);
  100828. if (useGizmoMaterial) {
  100829. this._rootMesh.getChildMeshes().forEach(function (m) {
  100830. m.material = _this._coloredMaterial;
  100831. if (m.color) {
  100832. m.color = _this._coloredMaterial.emissiveColor;
  100833. }
  100834. });
  100835. this._customMeshSet = false;
  100836. }
  100837. };
  100838. return AxisScaleGizmo;
  100839. }(BABYLON.Gizmo));
  100840. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  100841. })(BABYLON || (BABYLON = {}));
  100842. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  100843. var BABYLON;
  100844. (function (BABYLON) {
  100845. /**
  100846. * Single plane rotation gizmo
  100847. */
  100848. var PlaneRotationGizmo = /** @class */ (function (_super) {
  100849. __extends(PlaneRotationGizmo, _super);
  100850. /**
  100851. * Creates a PlaneRotationGizmo
  100852. * @param gizmoLayer The utility layer the gizmo will be added to
  100853. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  100854. * @param color The color of the gizmo
  100855. * @param tessellation Amount of tessellation to be used when creating rotation circles
  100856. */
  100857. function PlaneRotationGizmo(planeNormal, color, gizmoLayer, tessellation) {
  100858. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  100859. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100860. if (tessellation === void 0) { tessellation = 32; }
  100861. var _this = _super.call(this, gizmoLayer) || this;
  100862. _this._pointerObserver = null;
  100863. /**
  100864. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  100865. */
  100866. _this.snapDistance = 0;
  100867. /**
  100868. * Event that fires each time the gizmo snaps to a new location.
  100869. * * snapDistance is the the change in distance
  100870. */
  100871. _this.onSnapObservable = new BABYLON.Observable();
  100872. // Create Material
  100873. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100874. coloredMaterial.disableLighting = true;
  100875. coloredMaterial.emissiveColor = color;
  100876. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100877. hoverMaterial.disableLighting = true;
  100878. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  100879. // Build mesh on root node
  100880. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  100881. // Create circle out of lines
  100882. var radius = 0.8;
  100883. var points = new Array();
  100884. for (var i = 0; i < tessellation; i++) {
  100885. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  100886. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  100887. }
  100888. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  100889. rotationMesh.color = coloredMaterial.emissiveColor;
  100890. // Position arrow pointing in its drag axis
  100891. rotationMesh.scaling.scaleInPlace(0.26);
  100892. rotationMesh.material = coloredMaterial;
  100893. rotationMesh.rotation.x = Math.PI / 2;
  100894. parentMesh.addChild(rotationMesh);
  100895. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  100896. _this._rootMesh.addChild(parentMesh);
  100897. parentMesh.scaling.scaleInPlace(1 / 3);
  100898. // Add drag behavior to handle events when the gizmo is dragged
  100899. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  100900. _this.dragBehavior.moveAttached = false;
  100901. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  100902. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  100903. _this._rootMesh.addBehavior(_this.dragBehavior);
  100904. var lastDragPosition = new BABYLON.Vector3();
  100905. _this.dragBehavior.onDragStartObservable.add(function (e) {
  100906. if (_this.attachedMesh) {
  100907. lastDragPosition.copyFrom(e.dragPlanePoint);
  100908. }
  100909. });
  100910. var rotationMatrix = new BABYLON.Matrix();
  100911. var planeNormalTowardsCamera = new BABYLON.Vector3();
  100912. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  100913. var tmpSnapEvent = { snapDistance: 0 };
  100914. var currentSnapDragDistance = 0;
  100915. var tmpMatrix = new BABYLON.Matrix();
  100916. var tmpVector = new BABYLON.Vector3();
  100917. var amountToRotate = new BABYLON.Quaternion();
  100918. _this.dragBehavior.onDragObservable.add(function (event) {
  100919. if (_this.attachedMesh) {
  100920. if (!_this.attachedMesh.rotationQuaternion) {
  100921. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  100922. }
  100923. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  100924. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  100925. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  100926. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  100927. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  100928. var angle = Math.atan2(cross.length(), dot);
  100929. planeNormalTowardsCamera.copyFrom(planeNormal);
  100930. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  100931. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  100932. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  100933. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  100934. }
  100935. // Flip up vector depending on which side the camera is on
  100936. if (gizmoLayer.utilityLayerScene.activeCamera) {
  100937. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  100938. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  100939. planeNormalTowardsCamera.scaleInPlace(-1);
  100940. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  100941. }
  100942. }
  100943. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  100944. if (halfCircleSide) {
  100945. angle = -angle;
  100946. }
  100947. // Snapping logic
  100948. var snapped = false;
  100949. if (_this.snapDistance != 0) {
  100950. currentSnapDragDistance += angle;
  100951. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  100952. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  100953. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  100954. angle = _this.snapDistance * dragSteps;
  100955. snapped = true;
  100956. }
  100957. else {
  100958. angle = 0;
  100959. }
  100960. }
  100961. // If the mesh has a parent, convert needed world rotation to local rotation
  100962. tmpMatrix.reset();
  100963. if (_this.attachedMesh.parent) {
  100964. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  100965. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  100966. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  100967. }
  100968. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  100969. var quaternionCoefficient = Math.sin(angle / 2);
  100970. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  100971. // 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
  100972. if (tmpMatrix.determinant() > 0) {
  100973. amountToRotate.toEulerAnglesToRef(tmpVector);
  100974. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  100975. }
  100976. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  100977. // Rotate selected mesh quaternion over fixed axis
  100978. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  100979. }
  100980. else {
  100981. // Rotate selected mesh quaternion over rotated axis
  100982. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  100983. }
  100984. lastDragPosition.copyFrom(event.dragPlanePoint);
  100985. if (snapped) {
  100986. tmpSnapEvent.snapDistance = angle;
  100987. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  100988. }
  100989. }
  100990. });
  100991. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  100992. if (_this._customMeshSet) {
  100993. return;
  100994. }
  100995. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  100996. var material = isHovered ? hoverMaterial : coloredMaterial;
  100997. _this._rootMesh.getChildMeshes().forEach(function (m) {
  100998. m.material = material;
  100999. if (m.color) {
  101000. m.color = material.emissiveColor;
  101001. }
  101002. });
  101003. });
  101004. return _this;
  101005. }
  101006. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  101007. if (this.dragBehavior) {
  101008. this.dragBehavior.enabled = value ? true : false;
  101009. }
  101010. };
  101011. /**
  101012. * Disposes of the gizmo
  101013. */
  101014. PlaneRotationGizmo.prototype.dispose = function () {
  101015. this.onSnapObservable.clear();
  101016. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  101017. this.dragBehavior.detach();
  101018. _super.prototype.dispose.call(this);
  101019. };
  101020. return PlaneRotationGizmo;
  101021. }(BABYLON.Gizmo));
  101022. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  101023. })(BABYLON || (BABYLON = {}));
  101024. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  101025. var BABYLON;
  101026. (function (BABYLON) {
  101027. /**
  101028. * Gizmo that enables dragging a mesh along 3 axis
  101029. */
  101030. var PositionGizmo = /** @class */ (function (_super) {
  101031. __extends(PositionGizmo, _super);
  101032. /**
  101033. * Creates a PositionGizmo
  101034. * @param gizmoLayer The utility layer the gizmo will be added to
  101035. */
  101036. function PositionGizmo(gizmoLayer) {
  101037. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  101038. var _this = _super.call(this, gizmoLayer) || this;
  101039. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  101040. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  101041. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  101042. _this.attachedMesh = null;
  101043. return _this;
  101044. }
  101045. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  101046. set: function (mesh) {
  101047. if (this.xGizmo) {
  101048. this.xGizmo.attachedMesh = mesh;
  101049. this.yGizmo.attachedMesh = mesh;
  101050. this.zGizmo.attachedMesh = mesh;
  101051. }
  101052. },
  101053. enumerable: true,
  101054. configurable: true
  101055. });
  101056. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  101057. get: function () {
  101058. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  101059. },
  101060. set: function (value) {
  101061. if (this.xGizmo) {
  101062. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101063. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101064. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101065. }
  101066. },
  101067. enumerable: true,
  101068. configurable: true
  101069. });
  101070. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  101071. get: function () {
  101072. return this.xGizmo.snapDistance;
  101073. },
  101074. /**
  101075. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  101076. */
  101077. set: function (value) {
  101078. if (this.xGizmo) {
  101079. this.xGizmo.snapDistance = value;
  101080. this.yGizmo.snapDistance = value;
  101081. this.zGizmo.snapDistance = value;
  101082. }
  101083. },
  101084. enumerable: true,
  101085. configurable: true
  101086. });
  101087. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  101088. get: function () {
  101089. return this.xGizmo.scaleRatio;
  101090. },
  101091. /**
  101092. * Ratio for the scale of the gizmo (Default: 1)
  101093. */
  101094. set: function (value) {
  101095. if (this.xGizmo) {
  101096. this.xGizmo.scaleRatio = value;
  101097. this.yGizmo.scaleRatio = value;
  101098. this.zGizmo.scaleRatio = value;
  101099. }
  101100. },
  101101. enumerable: true,
  101102. configurable: true
  101103. });
  101104. /**
  101105. * Disposes of the gizmo
  101106. */
  101107. PositionGizmo.prototype.dispose = function () {
  101108. this.xGizmo.dispose();
  101109. this.yGizmo.dispose();
  101110. this.zGizmo.dispose();
  101111. };
  101112. /**
  101113. * CustomMeshes are not supported by this gizmo
  101114. * @param mesh The mesh to replace the default mesh of the gizmo
  101115. */
  101116. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  101117. 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)");
  101118. };
  101119. return PositionGizmo;
  101120. }(BABYLON.Gizmo));
  101121. BABYLON.PositionGizmo = PositionGizmo;
  101122. })(BABYLON || (BABYLON = {}));
  101123. //# sourceMappingURL=babylon.positionGizmo.js.map
  101124. var BABYLON;
  101125. (function (BABYLON) {
  101126. /**
  101127. * Gizmo that enables rotating a mesh along 3 axis
  101128. */
  101129. var RotationGizmo = /** @class */ (function (_super) {
  101130. __extends(RotationGizmo, _super);
  101131. /**
  101132. * Creates a RotationGizmo
  101133. * @param gizmoLayer The utility layer the gizmo will be added to
  101134. * @param tessellation Amount of tessellation to be used when creating rotation circles
  101135. */
  101136. function RotationGizmo(gizmoLayer, tessellation) {
  101137. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  101138. if (tessellation === void 0) { tessellation = 32; }
  101139. var _this = _super.call(this, gizmoLayer) || this;
  101140. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer, tessellation);
  101141. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer, tessellation);
  101142. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer, tessellation);
  101143. _this.attachedMesh = null;
  101144. return _this;
  101145. }
  101146. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  101147. set: function (mesh) {
  101148. if (this.xGizmo) {
  101149. this.xGizmo.attachedMesh = mesh;
  101150. this.yGizmo.attachedMesh = mesh;
  101151. this.zGizmo.attachedMesh = mesh;
  101152. }
  101153. },
  101154. enumerable: true,
  101155. configurable: true
  101156. });
  101157. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  101158. get: function () {
  101159. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  101160. },
  101161. set: function (value) {
  101162. if (this.xGizmo) {
  101163. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101164. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101165. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101166. }
  101167. },
  101168. enumerable: true,
  101169. configurable: true
  101170. });
  101171. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  101172. get: function () {
  101173. return this.xGizmo.snapDistance;
  101174. },
  101175. /**
  101176. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  101177. */
  101178. set: function (value) {
  101179. if (this.xGizmo) {
  101180. this.xGizmo.snapDistance = value;
  101181. this.yGizmo.snapDistance = value;
  101182. this.zGizmo.snapDistance = value;
  101183. }
  101184. },
  101185. enumerable: true,
  101186. configurable: true
  101187. });
  101188. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  101189. get: function () {
  101190. return this.xGizmo.scaleRatio;
  101191. },
  101192. /**
  101193. * Ratio for the scale of the gizmo (Default: 1)
  101194. */
  101195. set: function (value) {
  101196. if (this.xGizmo) {
  101197. this.xGizmo.scaleRatio = value;
  101198. this.yGizmo.scaleRatio = value;
  101199. this.zGizmo.scaleRatio = value;
  101200. }
  101201. },
  101202. enumerable: true,
  101203. configurable: true
  101204. });
  101205. /**
  101206. * Disposes of the gizmo
  101207. */
  101208. RotationGizmo.prototype.dispose = function () {
  101209. this.xGizmo.dispose();
  101210. this.yGizmo.dispose();
  101211. this.zGizmo.dispose();
  101212. };
  101213. /**
  101214. * CustomMeshes are not supported by this gizmo
  101215. * @param mesh The mesh to replace the default mesh of the gizmo
  101216. */
  101217. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  101218. 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)");
  101219. };
  101220. return RotationGizmo;
  101221. }(BABYLON.Gizmo));
  101222. BABYLON.RotationGizmo = RotationGizmo;
  101223. })(BABYLON || (BABYLON = {}));
  101224. //# sourceMappingURL=babylon.rotationGizmo.js.map
  101225. var BABYLON;
  101226. (function (BABYLON) {
  101227. /**
  101228. * Gizmo that enables scaling a mesh along 3 axis
  101229. */
  101230. var ScaleGizmo = /** @class */ (function (_super) {
  101231. __extends(ScaleGizmo, _super);
  101232. /**
  101233. * Creates a ScaleGizmo
  101234. * @param gizmoLayer The utility layer the gizmo will be added to
  101235. */
  101236. function ScaleGizmo(gizmoLayer) {
  101237. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  101238. var _this = _super.call(this, gizmoLayer) || this;
  101239. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  101240. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  101241. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  101242. // Create uniform scale gizmo
  101243. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  101244. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  101245. _this.uniformScaleGizmo.uniformScaling = true;
  101246. var uniformScalingMesh = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  101247. uniformScalingMesh.scaling.scaleInPlace(0.02);
  101248. uniformScalingMesh.visibility = 0;
  101249. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  101250. octahedron.scaling.scaleInPlace(0.007);
  101251. uniformScalingMesh.addChild(octahedron);
  101252. _this.uniformScaleGizmo.setCustomMesh(uniformScalingMesh, true);
  101253. _this.attachedMesh = null;
  101254. return _this;
  101255. }
  101256. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  101257. set: function (mesh) {
  101258. if (this.xGizmo) {
  101259. this.xGizmo.attachedMesh = mesh;
  101260. this.yGizmo.attachedMesh = mesh;
  101261. this.zGizmo.attachedMesh = mesh;
  101262. this.uniformScaleGizmo.attachedMesh = mesh;
  101263. }
  101264. },
  101265. enumerable: true,
  101266. configurable: true
  101267. });
  101268. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  101269. get: function () {
  101270. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  101271. },
  101272. set: function (value) {
  101273. if (!value) {
  101274. BABYLON.Tools.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.");
  101275. }
  101276. if (this.xGizmo) {
  101277. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101278. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101279. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101280. }
  101281. },
  101282. enumerable: true,
  101283. configurable: true
  101284. });
  101285. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  101286. get: function () {
  101287. return this.xGizmo.snapDistance;
  101288. },
  101289. /**
  101290. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  101291. */
  101292. set: function (value) {
  101293. if (this.xGizmo) {
  101294. this.xGizmo.snapDistance = value;
  101295. this.yGizmo.snapDistance = value;
  101296. this.zGizmo.snapDistance = value;
  101297. this.uniformScaleGizmo.snapDistance = value;
  101298. }
  101299. },
  101300. enumerable: true,
  101301. configurable: true
  101302. });
  101303. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  101304. get: function () {
  101305. return this.xGizmo.scaleRatio;
  101306. },
  101307. /**
  101308. * Ratio for the scale of the gizmo (Default: 1)
  101309. */
  101310. set: function (value) {
  101311. if (this.xGizmo) {
  101312. this.xGizmo.scaleRatio = value;
  101313. this.yGizmo.scaleRatio = value;
  101314. this.zGizmo.scaleRatio = value;
  101315. this.uniformScaleGizmo.scaleRatio = value;
  101316. }
  101317. },
  101318. enumerable: true,
  101319. configurable: true
  101320. });
  101321. /**
  101322. * Disposes of the gizmo
  101323. */
  101324. ScaleGizmo.prototype.dispose = function () {
  101325. this.xGizmo.dispose();
  101326. this.yGizmo.dispose();
  101327. this.zGizmo.dispose();
  101328. this.uniformScaleGizmo.dispose();
  101329. };
  101330. return ScaleGizmo;
  101331. }(BABYLON.Gizmo));
  101332. BABYLON.ScaleGizmo = ScaleGizmo;
  101333. })(BABYLON || (BABYLON = {}));
  101334. //# sourceMappingURL=babylon.scaleGizmo.js.map
  101335. var BABYLON;
  101336. (function (BABYLON) {
  101337. /**
  101338. * Bounding box gizmo
  101339. */
  101340. var BoundingBoxGizmo = /** @class */ (function (_super) {
  101341. __extends(BoundingBoxGizmo, _super);
  101342. /**
  101343. * Creates an BoundingBoxGizmo
  101344. * @param gizmoLayer The utility layer the gizmo will be added to
  101345. * @param color The color of the gizmo
  101346. */
  101347. function BoundingBoxGizmo(color, gizmoLayer) {
  101348. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  101349. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  101350. var _this = _super.call(this, gizmoLayer) || this;
  101351. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  101352. _this._renderObserver = null;
  101353. _this._pointerObserver = null;
  101354. _this._scaleDragSpeed = 0.2;
  101355. _this._tmpQuaternion = new BABYLON.Quaternion();
  101356. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  101357. _this._tmpRotationMatrix = new BABYLON.Matrix();
  101358. /**
  101359. * 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)
  101360. */
  101361. _this.ignoreChildren = false;
  101362. /**
  101363. * 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)
  101364. */
  101365. _this.includeChildPredicate = null;
  101366. /**
  101367. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  101368. */
  101369. _this.rotationSphereSize = 0.1;
  101370. /**
  101371. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  101372. */
  101373. _this.scaleBoxSize = 0.1;
  101374. /**
  101375. * 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)
  101376. */
  101377. _this.fixedDragMeshScreenSize = false;
  101378. /**
  101379. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  101380. */
  101381. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  101382. /**
  101383. * Fired when a rotation sphere or scale box is dragged
  101384. */
  101385. _this.onDragStartObservable = new BABYLON.Observable();
  101386. /**
  101387. * Fired when a scale box is dragged
  101388. */
  101389. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  101390. /**
  101391. * Fired when a scale box drag is ended
  101392. */
  101393. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  101394. /**
  101395. * Fired when a rotation sphere is dragged
  101396. */
  101397. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  101398. /**
  101399. * Fired when a rotation sphere drag is ended
  101400. */
  101401. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  101402. /**
  101403. * 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)
  101404. */
  101405. _this.scalePivot = null;
  101406. _this._existingMeshScale = new BABYLON.Vector3();
  101407. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  101408. _this._updateScale = false;
  101409. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  101410. // Create Materials
  101411. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101412. coloredMaterial.disableLighting = true;
  101413. coloredMaterial.emissiveColor = color;
  101414. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101415. hoverColoredMaterial.disableLighting = true;
  101416. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  101417. // Build bounding box out of lines
  101418. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101419. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  101420. var lines = [];
  101421. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  101422. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  101423. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  101424. 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));
  101425. 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));
  101426. 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));
  101427. 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));
  101428. 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));
  101429. 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));
  101430. 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));
  101431. 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));
  101432. 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));
  101433. lines.forEach(function (l) {
  101434. l.color = color;
  101435. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  101436. l.isPickable = false;
  101437. _this._lineBoundingBox.addChild(l);
  101438. });
  101439. _this._rootMesh.addChild(_this._lineBoundingBox);
  101440. // Create rotation spheres
  101441. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101442. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  101443. var _loop_1 = function (i_1) {
  101444. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  101445. sphere.rotationQuaternion = new BABYLON.Quaternion();
  101446. sphere.material = coloredMaterial;
  101447. // Drag behavior
  101448. _dragBehavior = new BABYLON.PointerDragBehavior({});
  101449. _dragBehavior.moveAttached = false;
  101450. _dragBehavior.updateDragPlane = false;
  101451. sphere.addBehavior(_dragBehavior);
  101452. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  101453. var totalTurnAmountOfDrag = 0;
  101454. _dragBehavior.onDragStartObservable.add(function (event) {
  101455. startingTurnDirection.copyFrom(sphere.forward);
  101456. totalTurnAmountOfDrag = 0;
  101457. });
  101458. _dragBehavior.onDragObservable.add(function (event) {
  101459. _this.onRotationSphereDragObservable.notifyObservers({});
  101460. if (_this.attachedMesh) {
  101461. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  101462. var worldDragDirection = startingTurnDirection;
  101463. // Project the world right on to the drag plane
  101464. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  101465. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  101466. // project drag delta on to the resulting drag axis and rotate based on that
  101467. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  101468. // Make rotation relative to size of mesh.
  101469. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  101470. // Rotate based on axis
  101471. if (!_this.attachedMesh.rotationQuaternion) {
  101472. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  101473. }
  101474. if (!_this._anchorMesh.rotationQuaternion) {
  101475. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  101476. }
  101477. // Do not allow the object to turn more than a full circle
  101478. totalTurnAmountOfDrag += projectDist;
  101479. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  101480. if (i_1 >= 8) {
  101481. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  101482. }
  101483. else if (i_1 >= 4) {
  101484. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  101485. }
  101486. else {
  101487. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  101488. }
  101489. // Rotate around center of bounding box
  101490. _this._anchorMesh.addChild(_this.attachedMesh);
  101491. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  101492. _this._anchorMesh.removeChild(_this.attachedMesh);
  101493. }
  101494. _this.updateBoundingBox();
  101495. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  101496. }
  101497. });
  101498. // Selection/deselection
  101499. _dragBehavior.onDragStartObservable.add(function () {
  101500. _this.onDragStartObservable.notifyObservers({});
  101501. _this._selectNode(sphere);
  101502. });
  101503. _dragBehavior.onDragEndObservable.add(function () {
  101504. _this.onRotationSphereDragEndObservable.notifyObservers({});
  101505. _this._selectNode(null);
  101506. });
  101507. this_1._rotateSpheresParent.addChild(sphere);
  101508. };
  101509. var this_1 = this, _dragBehavior;
  101510. for (var i_1 = 0; i_1 < 12; i_1++) {
  101511. _loop_1(i_1);
  101512. }
  101513. _this._rootMesh.addChild(_this._rotateSpheresParent);
  101514. // Create scale cubes
  101515. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101516. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  101517. for (var i = 0; i < 2; i++) {
  101518. for (var j = 0; j < 2; j++) {
  101519. var _loop_2 = function () {
  101520. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  101521. box.material = coloredMaterial;
  101522. // Dragging logic
  101523. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  101524. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  101525. _dragBehavior.moveAttached = false;
  101526. box.addBehavior(_dragBehavior);
  101527. _dragBehavior.onDragObservable.add(function (event) {
  101528. _this.onScaleBoxDragObservable.notifyObservers({});
  101529. if (_this.attachedMesh) {
  101530. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  101531. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  101532. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  101533. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  101534. _this.updateBoundingBox();
  101535. if (_this.scalePivot) {
  101536. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  101537. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  101538. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  101539. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  101540. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  101541. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  101542. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  101543. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  101544. }
  101545. else {
  101546. // Scale from the position of the opposite corner
  101547. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  101548. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  101549. }
  101550. _this._anchorMesh.addChild(_this.attachedMesh);
  101551. _this._anchorMesh.scaling.addInPlace(deltaScale);
  101552. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  101553. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  101554. }
  101555. _this._anchorMesh.removeChild(_this.attachedMesh);
  101556. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  101557. }
  101558. });
  101559. // Selection/deselection
  101560. _dragBehavior.onDragStartObservable.add(function () {
  101561. _this.onDragStartObservable.notifyObservers({});
  101562. _this._selectNode(box);
  101563. });
  101564. _dragBehavior.onDragEndObservable.add(function () {
  101565. _this.onScaleBoxDragEndObservable.notifyObservers({});
  101566. _this._selectNode(null);
  101567. });
  101568. this_2._scaleBoxesParent.addChild(box);
  101569. };
  101570. var this_2 = this, _dragBehavior;
  101571. for (var k = 0; k < 2; k++) {
  101572. _loop_2();
  101573. }
  101574. }
  101575. }
  101576. _this._rootMesh.addChild(_this._scaleBoxesParent);
  101577. // Hover color change
  101578. var pointerIds = new Array();
  101579. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  101580. if (!pointerIds[pointerInfo.event.pointerId]) {
  101581. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  101582. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  101583. pointerIds[pointerInfo.event.pointerId] = mesh;
  101584. mesh.material = hoverColoredMaterial;
  101585. }
  101586. });
  101587. }
  101588. else {
  101589. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  101590. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  101591. delete pointerIds[pointerInfo.event.pointerId];
  101592. }
  101593. }
  101594. });
  101595. // Update bounding box positions
  101596. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  101597. // Only update the bouding box if scaling has changed
  101598. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  101599. _this.updateBoundingBox();
  101600. }
  101601. });
  101602. _this.updateBoundingBox();
  101603. return _this;
  101604. }
  101605. /** @hidden */
  101606. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  101607. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  101608. // Save old pivot and set pivot to 0,0,0
  101609. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  101610. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  101611. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  101612. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  101613. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  101614. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  101615. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  101616. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  101617. }
  101618. }
  101619. BoundingBoxGizmo._PivotCached++;
  101620. };
  101621. /** @hidden */
  101622. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  101623. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  101624. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  101625. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  101626. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  101627. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  101628. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  101629. }
  101630. this._PivotCached--;
  101631. };
  101632. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  101633. if (value) {
  101634. // Reset anchor mesh to match attached mesh's scale
  101635. // This is needed to avoid invalid box/sphere position on first drag
  101636. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  101637. this._anchorMesh.addChild(value);
  101638. this._anchorMesh.removeChild(value);
  101639. BoundingBoxGizmo._RestorePivotPoint(value);
  101640. this.updateBoundingBox();
  101641. }
  101642. };
  101643. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  101644. this._rotateSpheresParent.getChildMeshes()
  101645. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  101646. m.isVisible = (!selectedMesh || m == selectedMesh);
  101647. });
  101648. };
  101649. /**
  101650. * Updates the bounding box information for the Gizmo
  101651. */
  101652. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  101653. if (this.attachedMesh) {
  101654. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  101655. this._update();
  101656. // Rotate based on axis
  101657. if (!this.attachedMesh.rotationQuaternion) {
  101658. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  101659. }
  101660. if (!this._anchorMesh.rotationQuaternion) {
  101661. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  101662. }
  101663. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  101664. // Store original position and reset mesh to origin before computing the bounding box
  101665. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  101666. this._tmpVector.copyFrom(this.attachedMesh.position);
  101667. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  101668. this.attachedMesh.position.set(0, 0, 0);
  101669. // Update bounding dimensions/positions
  101670. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  101671. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  101672. // Update gizmo to match bounding box scaling and rotation
  101673. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  101674. 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);
  101675. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  101676. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  101677. this._lineBoundingBox.computeWorldMatrix();
  101678. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  101679. // restore position/rotation values
  101680. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  101681. this.attachedMesh.position.copyFrom(this._tmpVector);
  101682. }
  101683. // Update rotation sphere locations
  101684. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  101685. for (var i = 0; i < 3; i++) {
  101686. for (var j = 0; j < 2; j++) {
  101687. for (var k = 0; k < 2; k++) {
  101688. var index = ((i * 4) + (j * 2)) + k;
  101689. if (i == 0) {
  101690. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  101691. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101692. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  101693. }
  101694. if (i == 1) {
  101695. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  101696. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101697. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  101698. }
  101699. if (i == 2) {
  101700. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  101701. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101702. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  101703. }
  101704. if (this.fixedDragMeshScreenSize) {
  101705. this._rootMesh.computeWorldMatrix();
  101706. this._rotateSpheresParent.computeWorldMatrix();
  101707. rotateSpheres[index].computeWorldMatrix();
  101708. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  101709. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  101710. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  101711. }
  101712. else {
  101713. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  101714. }
  101715. }
  101716. }
  101717. }
  101718. // Update scale box locations
  101719. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  101720. for (var i = 0; i < 2; i++) {
  101721. for (var j = 0; j < 2; j++) {
  101722. for (var k = 0; k < 2; k++) {
  101723. var index = ((i * 4) + (j * 2)) + k;
  101724. if (scaleBoxes[index]) {
  101725. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  101726. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101727. if (this.fixedDragMeshScreenSize) {
  101728. this._rootMesh.computeWorldMatrix();
  101729. this._scaleBoxesParent.computeWorldMatrix();
  101730. scaleBoxes[index].computeWorldMatrix();
  101731. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  101732. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  101733. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  101734. }
  101735. else {
  101736. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  101737. }
  101738. }
  101739. }
  101740. }
  101741. }
  101742. if (this.attachedMesh) {
  101743. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  101744. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  101745. }
  101746. };
  101747. /**
  101748. * Enables rotation on the specified axis and disables rotation on the others
  101749. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  101750. */
  101751. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  101752. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  101753. if (i < 4) {
  101754. m.setEnabled(axis.indexOf("x") != -1);
  101755. }
  101756. else if (i < 8) {
  101757. m.setEnabled(axis.indexOf("y") != -1);
  101758. }
  101759. else {
  101760. m.setEnabled(axis.indexOf("z") != -1);
  101761. }
  101762. });
  101763. };
  101764. /**
  101765. * Disposes of the gizmo
  101766. */
  101767. BoundingBoxGizmo.prototype.dispose = function () {
  101768. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  101769. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  101770. this._lineBoundingBox.dispose();
  101771. this._rotateSpheresParent.dispose();
  101772. this._scaleBoxesParent.dispose();
  101773. _super.prototype.dispose.call(this);
  101774. };
  101775. /**
  101776. * 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)
  101777. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  101778. * @returns the bounding box mesh with the passed in mesh as a child
  101779. */
  101780. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  101781. var makeNotPickable = function (root) {
  101782. root.isPickable = false;
  101783. root.getChildMeshes().forEach(function (c) {
  101784. makeNotPickable(c);
  101785. });
  101786. };
  101787. makeNotPickable(mesh);
  101788. // Reset position to get boudning box from origin with no rotation
  101789. if (!mesh.rotationQuaternion) {
  101790. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  101791. }
  101792. var oldPos = mesh.position.clone();
  101793. var oldRot = mesh.rotationQuaternion.clone();
  101794. mesh.rotationQuaternion.set(0, 0, 0, 1);
  101795. mesh.position.set(0, 0, 0);
  101796. // Update bounding dimensions/positions
  101797. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  101798. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  101799. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  101800. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  101801. // Restore original positions
  101802. mesh.addChild(box);
  101803. mesh.rotationQuaternion.copyFrom(oldRot);
  101804. mesh.position.copyFrom(oldPos);
  101805. // Reverse parenting
  101806. mesh.removeChild(box);
  101807. box.addChild(mesh);
  101808. box.visibility = 0;
  101809. return box;
  101810. };
  101811. /**
  101812. * CustomMeshes are not supported by this gizmo
  101813. * @param mesh The mesh to replace the default mesh of the gizmo
  101814. */
  101815. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  101816. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  101817. };
  101818. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  101819. // store/remove pivot point should only be applied during their outermost calls
  101820. BoundingBoxGizmo._PivotCached = 0;
  101821. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  101822. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  101823. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  101824. return BoundingBoxGizmo;
  101825. }(BABYLON.Gizmo));
  101826. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  101827. })(BABYLON || (BABYLON = {}));
  101828. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  101829. var BABYLON;
  101830. (function (BABYLON) {
  101831. /**
  101832. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  101833. */
  101834. var GizmoManager = /** @class */ (function () {
  101835. /**
  101836. * Instatiates a gizmo manager
  101837. * @param scene the scene to overlay the gizmos on top of
  101838. */
  101839. function GizmoManager(scene) {
  101840. var _this = this;
  101841. this.scene = scene;
  101842. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  101843. this._pointerObserver = null;
  101844. this._attachedMesh = null;
  101845. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  101846. /**
  101847. * When bounding box gizmo is enabled, this can be used to track drag/end events
  101848. */
  101849. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  101850. /**
  101851. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  101852. */
  101853. this.attachableMeshes = null;
  101854. /**
  101855. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  101856. */
  101857. this.usePointerToAttachGizmos = true;
  101858. this._defaultKeepDepthUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  101859. this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  101860. this._defaultUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  101861. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  101862. // Instatiate/dispose gizmos based on pointer actions
  101863. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  101864. if (!_this.usePointerToAttachGizmos) {
  101865. return;
  101866. }
  101867. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  101868. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  101869. var node = pointerInfo.pickInfo.pickedMesh;
  101870. if (_this.attachableMeshes == null) {
  101871. // Attach to the most parent node
  101872. while (node && node.parent != null) {
  101873. node = node.parent;
  101874. }
  101875. }
  101876. else {
  101877. // Attach to the parent node that is an attachableMesh
  101878. var found = false;
  101879. _this.attachableMeshes.forEach(function (mesh) {
  101880. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  101881. node = mesh;
  101882. found = true;
  101883. }
  101884. });
  101885. if (!found) {
  101886. node = null;
  101887. }
  101888. }
  101889. if (node instanceof BABYLON.AbstractMesh) {
  101890. if (_this._attachedMesh != node) {
  101891. _this.attachToMesh(node);
  101892. }
  101893. }
  101894. else {
  101895. _this.attachToMesh(null);
  101896. }
  101897. }
  101898. else {
  101899. _this.attachToMesh(null);
  101900. }
  101901. }
  101902. });
  101903. }
  101904. /**
  101905. * Attaches a set of gizmos to the specified mesh
  101906. * @param mesh The mesh the gizmo's should be attached to
  101907. */
  101908. GizmoManager.prototype.attachToMesh = function (mesh) {
  101909. if (this._attachedMesh) {
  101910. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  101911. }
  101912. this._attachedMesh = mesh;
  101913. for (var key in this.gizmos) {
  101914. var gizmo = (this.gizmos[key]);
  101915. if (gizmo && this._gizmosEnabled[key]) {
  101916. gizmo.attachedMesh = mesh;
  101917. }
  101918. }
  101919. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  101920. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  101921. }
  101922. };
  101923. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  101924. get: function () {
  101925. return this._gizmosEnabled.positionGizmo;
  101926. },
  101927. /**
  101928. * If the position gizmo is enabled
  101929. */
  101930. set: function (value) {
  101931. if (value) {
  101932. if (!this.gizmos.positionGizmo) {
  101933. this.gizmos.positionGizmo = new BABYLON.PositionGizmo(this._defaultUtilityLayer);
  101934. }
  101935. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  101936. }
  101937. else if (this.gizmos.positionGizmo) {
  101938. this.gizmos.positionGizmo.attachedMesh = null;
  101939. }
  101940. this._gizmosEnabled.positionGizmo = value;
  101941. },
  101942. enumerable: true,
  101943. configurable: true
  101944. });
  101945. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  101946. get: function () {
  101947. return this._gizmosEnabled.rotationGizmo;
  101948. },
  101949. /**
  101950. * If the rotation gizmo is enabled
  101951. */
  101952. set: function (value) {
  101953. if (value) {
  101954. if (!this.gizmos.rotationGizmo) {
  101955. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo(this._defaultUtilityLayer);
  101956. }
  101957. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  101958. }
  101959. else if (this.gizmos.rotationGizmo) {
  101960. this.gizmos.rotationGizmo.attachedMesh = null;
  101961. }
  101962. this._gizmosEnabled.rotationGizmo = value;
  101963. },
  101964. enumerable: true,
  101965. configurable: true
  101966. });
  101967. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  101968. get: function () {
  101969. return this._gizmosEnabled.scaleGizmo;
  101970. },
  101971. /**
  101972. * If the scale gizmo is enabled
  101973. */
  101974. set: function (value) {
  101975. if (value) {
  101976. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo(this._defaultUtilityLayer);
  101977. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  101978. }
  101979. else if (this.gizmos.scaleGizmo) {
  101980. this.gizmos.scaleGizmo.attachedMesh = null;
  101981. }
  101982. this._gizmosEnabled.scaleGizmo = value;
  101983. },
  101984. enumerable: true,
  101985. configurable: true
  101986. });
  101987. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  101988. get: function () {
  101989. return this._gizmosEnabled.boundingBoxGizmo;
  101990. },
  101991. /**
  101992. * If the boundingBox gizmo is enabled
  101993. */
  101994. set: function (value) {
  101995. if (value) {
  101996. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor, this._defaultKeepDepthUtilityLayer);
  101997. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  101998. if (this._attachedMesh) {
  101999. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  102000. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  102001. }
  102002. }
  102003. else if (this.gizmos.boundingBoxGizmo) {
  102004. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  102005. }
  102006. this._gizmosEnabled.boundingBoxGizmo = value;
  102007. },
  102008. enumerable: true,
  102009. configurable: true
  102010. });
  102011. /**
  102012. * Disposes of the gizmo manager
  102013. */
  102014. GizmoManager.prototype.dispose = function () {
  102015. this.scene.onPointerObservable.remove(this._pointerObserver);
  102016. for (var key in this.gizmos) {
  102017. var gizmo = (this.gizmos[key]);
  102018. if (gizmo) {
  102019. gizmo.dispose();
  102020. }
  102021. }
  102022. this._defaultKeepDepthUtilityLayer.dispose();
  102023. this._defaultUtilityLayer.dispose();
  102024. this.boundingBoxDragBehavior.detach();
  102025. };
  102026. return GizmoManager;
  102027. }());
  102028. BABYLON.GizmoManager = GizmoManager;
  102029. })(BABYLON || (BABYLON = {}));
  102030. //# sourceMappingURL=babylon.gizmoManager.js.map
  102031. var BABYLON;
  102032. (function (BABYLON) {
  102033. /**
  102034. * Defines a target to use with MorphTargetManager
  102035. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  102036. */
  102037. var MorphTarget = /** @class */ (function () {
  102038. /**
  102039. * Creates a new MorphTarget
  102040. * @param name defines the name of the target
  102041. * @param influence defines the influence to use
  102042. */
  102043. function MorphTarget(
  102044. /** defines the name of the target */
  102045. name, influence, scene) {
  102046. if (influence === void 0) { influence = 0; }
  102047. if (scene === void 0) { scene = null; }
  102048. this.name = name;
  102049. /**
  102050. * Gets or sets the list of animations
  102051. */
  102052. this.animations = new Array();
  102053. this._positions = null;
  102054. this._normals = null;
  102055. this._tangents = null;
  102056. /**
  102057. * Observable raised when the influence changes
  102058. */
  102059. this.onInfluenceChanged = new BABYLON.Observable();
  102060. this._animationPropertiesOverride = null;
  102061. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  102062. this.influence = influence;
  102063. }
  102064. Object.defineProperty(MorphTarget.prototype, "influence", {
  102065. /**
  102066. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  102067. */
  102068. get: function () {
  102069. return this._influence;
  102070. },
  102071. set: function (influence) {
  102072. if (this._influence === influence) {
  102073. return;
  102074. }
  102075. var previous = this._influence;
  102076. this._influence = influence;
  102077. if (this.onInfluenceChanged.hasObservers) {
  102078. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  102079. }
  102080. },
  102081. enumerable: true,
  102082. configurable: true
  102083. });
  102084. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  102085. /**
  102086. * Gets or sets the animation properties override
  102087. */
  102088. get: function () {
  102089. if (!this._animationPropertiesOverride && this._scene) {
  102090. return this._scene.animationPropertiesOverride;
  102091. }
  102092. return this._animationPropertiesOverride;
  102093. },
  102094. set: function (value) {
  102095. this._animationPropertiesOverride = value;
  102096. },
  102097. enumerable: true,
  102098. configurable: true
  102099. });
  102100. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  102101. /**
  102102. * Gets a boolean defining if the target contains position data
  102103. */
  102104. get: function () {
  102105. return !!this._positions;
  102106. },
  102107. enumerable: true,
  102108. configurable: true
  102109. });
  102110. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  102111. /**
  102112. * Gets a boolean defining if the target contains normal data
  102113. */
  102114. get: function () {
  102115. return !!this._normals;
  102116. },
  102117. enumerable: true,
  102118. configurable: true
  102119. });
  102120. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  102121. /**
  102122. * Gets a boolean defining if the target contains tangent data
  102123. */
  102124. get: function () {
  102125. return !!this._tangents;
  102126. },
  102127. enumerable: true,
  102128. configurable: true
  102129. });
  102130. /**
  102131. * Affects position data to this target
  102132. * @param data defines the position data to use
  102133. */
  102134. MorphTarget.prototype.setPositions = function (data) {
  102135. this._positions = data;
  102136. };
  102137. /**
  102138. * Gets the position data stored in this target
  102139. * @returns a FloatArray containing the position data (or null if not present)
  102140. */
  102141. MorphTarget.prototype.getPositions = function () {
  102142. return this._positions;
  102143. };
  102144. /**
  102145. * Affects normal data to this target
  102146. * @param data defines the normal data to use
  102147. */
  102148. MorphTarget.prototype.setNormals = function (data) {
  102149. this._normals = data;
  102150. };
  102151. /**
  102152. * Gets the normal data stored in this target
  102153. * @returns a FloatArray containing the normal data (or null if not present)
  102154. */
  102155. MorphTarget.prototype.getNormals = function () {
  102156. return this._normals;
  102157. };
  102158. /**
  102159. * Affects tangent data to this target
  102160. * @param data defines the tangent data to use
  102161. */
  102162. MorphTarget.prototype.setTangents = function (data) {
  102163. this._tangents = data;
  102164. };
  102165. /**
  102166. * Gets the tangent data stored in this target
  102167. * @returns a FloatArray containing the tangent data (or null if not present)
  102168. */
  102169. MorphTarget.prototype.getTangents = function () {
  102170. return this._tangents;
  102171. };
  102172. /**
  102173. * Serializes the current target into a Serialization object
  102174. * @returns the serialized object
  102175. */
  102176. MorphTarget.prototype.serialize = function () {
  102177. var serializationObject = {};
  102178. serializationObject.name = this.name;
  102179. serializationObject.influence = this.influence;
  102180. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  102181. if (this.hasNormals) {
  102182. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  102183. }
  102184. if (this.hasTangents) {
  102185. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  102186. }
  102187. // Animations
  102188. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  102189. return serializationObject;
  102190. };
  102191. // Statics
  102192. /**
  102193. * Creates a new target from serialized data
  102194. * @param serializationObject defines the serialized data to use
  102195. * @returns a new MorphTarget
  102196. */
  102197. MorphTarget.Parse = function (serializationObject) {
  102198. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  102199. result.setPositions(serializationObject.positions);
  102200. if (serializationObject.normals) {
  102201. result.setNormals(serializationObject.normals);
  102202. }
  102203. if (serializationObject.tangents) {
  102204. result.setTangents(serializationObject.tangents);
  102205. }
  102206. // Animations
  102207. if (serializationObject.animations) {
  102208. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  102209. var parsedAnimation = serializationObject.animations[animationIndex];
  102210. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  102211. }
  102212. }
  102213. return result;
  102214. };
  102215. /**
  102216. * Creates a MorphTarget from mesh data
  102217. * @param mesh defines the source mesh
  102218. * @param name defines the name to use for the new target
  102219. * @param influence defines the influence to attach to the target
  102220. * @returns a new MorphTarget
  102221. */
  102222. MorphTarget.FromMesh = function (mesh, name, influence) {
  102223. if (!name) {
  102224. name = mesh.name;
  102225. }
  102226. var result = new MorphTarget(name, influence, mesh.getScene());
  102227. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  102228. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  102229. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  102230. }
  102231. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  102232. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  102233. }
  102234. return result;
  102235. };
  102236. return MorphTarget;
  102237. }());
  102238. BABYLON.MorphTarget = MorphTarget;
  102239. })(BABYLON || (BABYLON = {}));
  102240. //# sourceMappingURL=babylon.morphTarget.js.map
  102241. var BABYLON;
  102242. (function (BABYLON) {
  102243. /**
  102244. * This class is used to deform meshes using morphing between different targets
  102245. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  102246. */
  102247. var MorphTargetManager = /** @class */ (function () {
  102248. /**
  102249. * Creates a new MorphTargetManager
  102250. * @param scene defines the current scene
  102251. */
  102252. function MorphTargetManager(scene) {
  102253. if (scene === void 0) { scene = null; }
  102254. this._targets = new Array();
  102255. this._targetObservable = new Array();
  102256. this._activeTargets = new BABYLON.SmartArray(16);
  102257. this._supportsNormals = false;
  102258. this._supportsTangents = false;
  102259. this._vertexCount = 0;
  102260. this._uniqueId = 0;
  102261. this._tempInfluences = new Array();
  102262. if (!scene) {
  102263. scene = BABYLON.Engine.LastCreatedScene;
  102264. }
  102265. this._scene = scene;
  102266. if (this._scene) {
  102267. this._scene.morphTargetManagers.push(this);
  102268. this._uniqueId = this._scene.getUniqueId();
  102269. }
  102270. }
  102271. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  102272. /**
  102273. * Gets the unique ID of this manager
  102274. */
  102275. get: function () {
  102276. return this._uniqueId;
  102277. },
  102278. enumerable: true,
  102279. configurable: true
  102280. });
  102281. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  102282. /**
  102283. * Gets the number of vertices handled by this manager
  102284. */
  102285. get: function () {
  102286. return this._vertexCount;
  102287. },
  102288. enumerable: true,
  102289. configurable: true
  102290. });
  102291. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  102292. /**
  102293. * Gets a boolean indicating if this manager supports morphing of normals
  102294. */
  102295. get: function () {
  102296. return this._supportsNormals;
  102297. },
  102298. enumerable: true,
  102299. configurable: true
  102300. });
  102301. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  102302. /**
  102303. * Gets a boolean indicating if this manager supports morphing of tangents
  102304. */
  102305. get: function () {
  102306. return this._supportsTangents;
  102307. },
  102308. enumerable: true,
  102309. configurable: true
  102310. });
  102311. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  102312. /**
  102313. * Gets the number of targets stored in this manager
  102314. */
  102315. get: function () {
  102316. return this._targets.length;
  102317. },
  102318. enumerable: true,
  102319. configurable: true
  102320. });
  102321. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  102322. /**
  102323. * Gets the number of influencers (ie. the number of targets with influences > 0)
  102324. */
  102325. get: function () {
  102326. return this._activeTargets.length;
  102327. },
  102328. enumerable: true,
  102329. configurable: true
  102330. });
  102331. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  102332. /**
  102333. * Gets the list of influences (one per target)
  102334. */
  102335. get: function () {
  102336. return this._influences;
  102337. },
  102338. enumerable: true,
  102339. configurable: true
  102340. });
  102341. /**
  102342. * Gets the active target at specified index. An active target is a target with an influence > 0
  102343. * @param index defines the index to check
  102344. * @returns the requested target
  102345. */
  102346. MorphTargetManager.prototype.getActiveTarget = function (index) {
  102347. return this._activeTargets.data[index];
  102348. };
  102349. /**
  102350. * Gets the target at specified index
  102351. * @param index defines the index to check
  102352. * @returns the requested target
  102353. */
  102354. MorphTargetManager.prototype.getTarget = function (index) {
  102355. return this._targets[index];
  102356. };
  102357. /**
  102358. * Add a new target to this manager
  102359. * @param target defines the target to add
  102360. */
  102361. MorphTargetManager.prototype.addTarget = function (target) {
  102362. var _this = this;
  102363. this._targets.push(target);
  102364. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  102365. _this._syncActiveTargets(needUpdate);
  102366. }));
  102367. this._syncActiveTargets(true);
  102368. };
  102369. /**
  102370. * Removes a target from the manager
  102371. * @param target defines the target to remove
  102372. */
  102373. MorphTargetManager.prototype.removeTarget = function (target) {
  102374. var index = this._targets.indexOf(target);
  102375. if (index >= 0) {
  102376. this._targets.splice(index, 1);
  102377. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  102378. this._syncActiveTargets(true);
  102379. }
  102380. };
  102381. /**
  102382. * Serializes the current manager into a Serialization object
  102383. * @returns the serialized object
  102384. */
  102385. MorphTargetManager.prototype.serialize = function () {
  102386. var serializationObject = {};
  102387. serializationObject.id = this.uniqueId;
  102388. serializationObject.targets = [];
  102389. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  102390. var target = _a[_i];
  102391. serializationObject.targets.push(target.serialize());
  102392. }
  102393. return serializationObject;
  102394. };
  102395. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  102396. var influenceCount = 0;
  102397. this._activeTargets.reset();
  102398. this._supportsNormals = true;
  102399. this._supportsTangents = true;
  102400. this._vertexCount = 0;
  102401. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  102402. var target = _a[_i];
  102403. this._activeTargets.push(target);
  102404. this._tempInfluences[influenceCount++] = target.influence;
  102405. var positions = target.getPositions();
  102406. if (positions) {
  102407. this._supportsNormals = this._supportsNormals && target.hasNormals;
  102408. this._supportsTangents = this._supportsTangents && target.hasTangents;
  102409. var vertexCount = positions.length / 3;
  102410. if (this._vertexCount === 0) {
  102411. this._vertexCount = vertexCount;
  102412. }
  102413. else if (this._vertexCount !== vertexCount) {
  102414. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  102415. return;
  102416. }
  102417. }
  102418. }
  102419. if (!this._influences || this._influences.length !== influenceCount) {
  102420. this._influences = new Float32Array(influenceCount);
  102421. }
  102422. for (var index = 0; index < influenceCount; index++) {
  102423. this._influences[index] = this._tempInfluences[index];
  102424. }
  102425. if (needUpdate) {
  102426. this.synchronize();
  102427. }
  102428. };
  102429. /**
  102430. * Syncrhonize the targets with all the meshes using this morph target manager
  102431. */
  102432. MorphTargetManager.prototype.synchronize = function () {
  102433. if (!this._scene) {
  102434. return;
  102435. }
  102436. // Flag meshes as dirty to resync with the active targets
  102437. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  102438. var mesh = _a[_i];
  102439. if (mesh.morphTargetManager === this) {
  102440. mesh._syncGeometryWithMorphTargetManager();
  102441. }
  102442. }
  102443. };
  102444. // Statics
  102445. /**
  102446. * Creates a new MorphTargetManager from serialized data
  102447. * @param serializationObject defines the serialized data
  102448. * @param scene defines the hosting scene
  102449. * @returns the new MorphTargetManager
  102450. */
  102451. MorphTargetManager.Parse = function (serializationObject, scene) {
  102452. var result = new MorphTargetManager(scene);
  102453. result._uniqueId = serializationObject.id;
  102454. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  102455. var targetData = _a[_i];
  102456. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  102457. }
  102458. return result;
  102459. };
  102460. return MorphTargetManager;
  102461. }());
  102462. BABYLON.MorphTargetManager = MorphTargetManager;
  102463. })(BABYLON || (BABYLON = {}));
  102464. //# sourceMappingURL=babylon.morphTargetManager.js.map
  102465. var BABYLON;
  102466. (function (BABYLON) {
  102467. /**
  102468. * Octrees are a really powerful data structure that can quickly select entities based on space coordinates.
  102469. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102470. */
  102471. var Octree = /** @class */ (function () {
  102472. /**
  102473. * Creates a octree
  102474. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102475. * @param creationFunc function to be used to instatiate the octree
  102476. * @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64)
  102477. * @param maxDepth defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.)
  102478. */
  102479. function Octree(creationFunc, maxBlockCapacity,
  102480. /** Defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.) */
  102481. maxDepth) {
  102482. if (maxDepth === void 0) { maxDepth = 2; }
  102483. this.maxDepth = maxDepth;
  102484. /**
  102485. * Content stored in the octree
  102486. */
  102487. this.dynamicContent = new Array();
  102488. this._maxBlockCapacity = maxBlockCapacity || 64;
  102489. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  102490. this._creationFunc = creationFunc;
  102491. }
  102492. // Methods
  102493. /**
  102494. * Updates the octree by adding blocks for the passed in meshes within the min and max world parameters
  102495. * @param worldMin worldMin for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  102496. * @param worldMax worldMax for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  102497. * @param entries meshes to be added to the octree blocks
  102498. */
  102499. Octree.prototype.update = function (worldMin, worldMax, entries) {
  102500. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  102501. };
  102502. /**
  102503. * Adds a mesh to the octree
  102504. * @param entry Mesh to add to the octree
  102505. */
  102506. Octree.prototype.addMesh = function (entry) {
  102507. for (var index = 0; index < this.blocks.length; index++) {
  102508. var block = this.blocks[index];
  102509. block.addEntry(entry);
  102510. }
  102511. };
  102512. /**
  102513. * Selects an array of meshes within the frustum
  102514. * @param frustumPlanes The frustum planes to use which will select all meshes within it
  102515. * @param allowDuplicate If duplicate objects are allowed in the resulting object array
  102516. * @returns array of meshes within the frustum
  102517. */
  102518. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  102519. this._selectionContent.reset();
  102520. for (var index = 0; index < this.blocks.length; index++) {
  102521. var block = this.blocks[index];
  102522. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  102523. }
  102524. if (allowDuplicate) {
  102525. this._selectionContent.concat(this.dynamicContent);
  102526. }
  102527. else {
  102528. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  102529. }
  102530. return this._selectionContent;
  102531. };
  102532. /**
  102533. * Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array
  102534. * @param sphereCenter defines the bounding sphere center
  102535. * @param sphereRadius defines the bounding sphere radius
  102536. * @param allowDuplicate defines if the selection array can contains duplicated entries
  102537. * @returns an array of objects that intersect the sphere
  102538. */
  102539. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  102540. this._selectionContent.reset();
  102541. for (var index = 0; index < this.blocks.length; index++) {
  102542. var block = this.blocks[index];
  102543. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  102544. }
  102545. if (allowDuplicate) {
  102546. this._selectionContent.concat(this.dynamicContent);
  102547. }
  102548. else {
  102549. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  102550. }
  102551. return this._selectionContent;
  102552. };
  102553. /**
  102554. * Test if the octree intersect with the given ray and if yes, then add its content to resulting array
  102555. * @param ray defines the ray to test with
  102556. * @returns array of intersected objects
  102557. */
  102558. Octree.prototype.intersectsRay = function (ray) {
  102559. this._selectionContent.reset();
  102560. for (var index = 0; index < this.blocks.length; index++) {
  102561. var block = this.blocks[index];
  102562. block.intersectsRay(ray, this._selectionContent);
  102563. }
  102564. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  102565. return this._selectionContent;
  102566. };
  102567. /**
  102568. * @hidden
  102569. */
  102570. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  102571. target.blocks = new Array();
  102572. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  102573. // Segmenting space
  102574. for (var x = 0; x < 2; x++) {
  102575. for (var y = 0; y < 2; y++) {
  102576. for (var z = 0; z < 2; z++) {
  102577. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  102578. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  102579. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  102580. block.addEntries(entries);
  102581. target.blocks.push(block);
  102582. }
  102583. }
  102584. }
  102585. };
  102586. /**
  102587. * Adds a mesh into the octree block if it intersects the block
  102588. */
  102589. Octree.CreationFuncForMeshes = function (entry, block) {
  102590. var boundingInfo = entry.getBoundingInfo();
  102591. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  102592. block.entries.push(entry);
  102593. }
  102594. };
  102595. /**
  102596. * Adds a submesh into the octree block if it intersects the block
  102597. */
  102598. Octree.CreationFuncForSubMeshes = function (entry, block) {
  102599. var boundingInfo = entry.getBoundingInfo();
  102600. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  102601. block.entries.push(entry);
  102602. }
  102603. };
  102604. return Octree;
  102605. }());
  102606. BABYLON.Octree = Octree;
  102607. })(BABYLON || (BABYLON = {}));
  102608. //# sourceMappingURL=babylon.octree.js.map
  102609. var BABYLON;
  102610. (function (BABYLON) {
  102611. /**
  102612. * Class used to store a cell in an octree
  102613. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102614. */
  102615. var OctreeBlock = /** @class */ (function () {
  102616. /**
  102617. * Creates a new block
  102618. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  102619. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  102620. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  102621. * @param depth defines the current depth of this block in the octree
  102622. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  102623. * @param creationFunc defines a callback to call when an element is added to the block
  102624. */
  102625. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  102626. /**
  102627. * Gets the content of the current block
  102628. */
  102629. this.entries = new Array();
  102630. this._boundingVectors = new Array();
  102631. this._capacity = capacity;
  102632. this._depth = depth;
  102633. this._maxDepth = maxDepth;
  102634. this._creationFunc = creationFunc;
  102635. this._minPoint = minPoint;
  102636. this._maxPoint = maxPoint;
  102637. this._boundingVectors.push(minPoint.clone());
  102638. this._boundingVectors.push(maxPoint.clone());
  102639. this._boundingVectors.push(minPoint.clone());
  102640. this._boundingVectors[2].x = maxPoint.x;
  102641. this._boundingVectors.push(minPoint.clone());
  102642. this._boundingVectors[3].y = maxPoint.y;
  102643. this._boundingVectors.push(minPoint.clone());
  102644. this._boundingVectors[4].z = maxPoint.z;
  102645. this._boundingVectors.push(maxPoint.clone());
  102646. this._boundingVectors[5].z = minPoint.z;
  102647. this._boundingVectors.push(maxPoint.clone());
  102648. this._boundingVectors[6].x = minPoint.x;
  102649. this._boundingVectors.push(maxPoint.clone());
  102650. this._boundingVectors[7].y = minPoint.y;
  102651. }
  102652. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  102653. // Property
  102654. /**
  102655. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  102656. */
  102657. get: function () {
  102658. return this._capacity;
  102659. },
  102660. enumerable: true,
  102661. configurable: true
  102662. });
  102663. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  102664. /**
  102665. * Gets the minimum vector (in world space) of the block's bounding box
  102666. */
  102667. get: function () {
  102668. return this._minPoint;
  102669. },
  102670. enumerable: true,
  102671. configurable: true
  102672. });
  102673. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  102674. /**
  102675. * Gets the maximum vector (in world space) of the block's bounding box
  102676. */
  102677. get: function () {
  102678. return this._maxPoint;
  102679. },
  102680. enumerable: true,
  102681. configurable: true
  102682. });
  102683. // Methods
  102684. /**
  102685. * Add a new element to this block
  102686. * @param entry defines the element to add
  102687. */
  102688. OctreeBlock.prototype.addEntry = function (entry) {
  102689. if (this.blocks) {
  102690. for (var index = 0; index < this.blocks.length; index++) {
  102691. var block = this.blocks[index];
  102692. block.addEntry(entry);
  102693. }
  102694. return;
  102695. }
  102696. this._creationFunc(entry, this);
  102697. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  102698. this.createInnerBlocks();
  102699. }
  102700. };
  102701. /**
  102702. * Add an array of elements to this block
  102703. * @param entries defines the array of elements to add
  102704. */
  102705. OctreeBlock.prototype.addEntries = function (entries) {
  102706. for (var index = 0; index < entries.length; index++) {
  102707. var mesh = entries[index];
  102708. this.addEntry(mesh);
  102709. }
  102710. };
  102711. /**
  102712. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  102713. * @param frustumPlanes defines the frustum planes to test
  102714. * @param selection defines the array to store current content if selection is positive
  102715. * @param allowDuplicate defines if the selection array can contains duplicated entries
  102716. */
  102717. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  102718. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  102719. if (this.blocks) {
  102720. for (var index = 0; index < this.blocks.length; index++) {
  102721. var block = this.blocks[index];
  102722. block.select(frustumPlanes, selection, allowDuplicate);
  102723. }
  102724. return;
  102725. }
  102726. if (allowDuplicate) {
  102727. selection.concat(this.entries);
  102728. }
  102729. else {
  102730. selection.concatWithNoDuplicate(this.entries);
  102731. }
  102732. }
  102733. };
  102734. /**
  102735. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  102736. * @param sphereCenter defines the bounding sphere center
  102737. * @param sphereRadius defines the bounding sphere radius
  102738. * @param selection defines the array to store current content if selection is positive
  102739. * @param allowDuplicate defines if the selection array can contains duplicated entries
  102740. */
  102741. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  102742. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  102743. if (this.blocks) {
  102744. for (var index = 0; index < this.blocks.length; index++) {
  102745. var block = this.blocks[index];
  102746. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  102747. }
  102748. return;
  102749. }
  102750. if (allowDuplicate) {
  102751. selection.concat(this.entries);
  102752. }
  102753. else {
  102754. selection.concatWithNoDuplicate(this.entries);
  102755. }
  102756. }
  102757. };
  102758. /**
  102759. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  102760. * @param ray defines the ray to test with
  102761. * @param selection defines the array to store current content if selection is positive
  102762. */
  102763. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  102764. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  102765. if (this.blocks) {
  102766. for (var index = 0; index < this.blocks.length; index++) {
  102767. var block = this.blocks[index];
  102768. block.intersectsRay(ray, selection);
  102769. }
  102770. return;
  102771. }
  102772. selection.concatWithNoDuplicate(this.entries);
  102773. }
  102774. };
  102775. /**
  102776. * Subdivide the content into child blocks (this block will then be empty)
  102777. */
  102778. OctreeBlock.prototype.createInnerBlocks = function () {
  102779. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  102780. };
  102781. return OctreeBlock;
  102782. }());
  102783. BABYLON.OctreeBlock = OctreeBlock;
  102784. })(BABYLON || (BABYLON = {}));
  102785. //# sourceMappingURL=babylon.octreeBlock.js.map
  102786. var BABYLON;
  102787. (function (BABYLON) {
  102788. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  102789. if (maxCapacity === void 0) { maxCapacity = 64; }
  102790. if (maxDepth === void 0) { maxDepth = 2; }
  102791. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  102792. if (!component) {
  102793. component = new OctreeSceneComponent(this);
  102794. this._addComponent(component);
  102795. }
  102796. if (!this._selectionOctree) {
  102797. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  102798. }
  102799. var worldExtends = this.getWorldExtends();
  102800. // Update octree
  102801. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  102802. return this._selectionOctree;
  102803. };
  102804. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  102805. get: function () {
  102806. return this._selectionOctree;
  102807. },
  102808. enumerable: true,
  102809. configurable: true
  102810. });
  102811. /**
  102812. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  102813. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  102814. * @param maxCapacity defines the maximum size of each block (64 by default)
  102815. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  102816. * @returns the new octree
  102817. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  102818. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102819. */
  102820. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  102821. if (maxCapacity === void 0) { maxCapacity = 64; }
  102822. if (maxDepth === void 0) { maxDepth = 2; }
  102823. var scene = this.getScene();
  102824. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  102825. if (!component) {
  102826. component = new OctreeSceneComponent(scene);
  102827. scene._addComponent(component);
  102828. }
  102829. if (!this._submeshesOctree) {
  102830. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  102831. }
  102832. this.computeWorldMatrix(true);
  102833. var boundingInfo = this.getBoundingInfo();
  102834. // Update octree
  102835. var bbox = boundingInfo.boundingBox;
  102836. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  102837. return this._submeshesOctree;
  102838. };
  102839. /**
  102840. * Defines the octree scene component responsible to manage any octrees
  102841. * in a given scene.
  102842. */
  102843. var OctreeSceneComponent = /** @class */ (function () {
  102844. /**
  102845. * Creates a new instance of the component for the given scene
  102846. * @param scene Defines the scene to register the component in
  102847. */
  102848. function OctreeSceneComponent(scene) {
  102849. /**
  102850. * The component name helpfull to identify the component in the list of scene components.
  102851. */
  102852. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  102853. /**
  102854. * Indicates if the meshes have been checked to make sure they are isEnabled()
  102855. */
  102856. this.checksIsEnabled = true;
  102857. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  102858. this.scene = scene;
  102859. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  102860. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  102861. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  102862. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  102863. }
  102864. /**
  102865. * Registers the component in a given scene
  102866. */
  102867. OctreeSceneComponent.prototype.register = function () {
  102868. var _this = this;
  102869. this.scene.onMeshRemovedObservable.add(function (mesh) {
  102870. var sceneOctree = _this.scene.selectionOctree;
  102871. if (sceneOctree !== undefined && sceneOctree !== null) {
  102872. var index = sceneOctree.dynamicContent.indexOf(mesh);
  102873. if (index !== -1) {
  102874. sceneOctree.dynamicContent.splice(index, 1);
  102875. }
  102876. }
  102877. });
  102878. this.scene.onMeshImportedObservable.add(function (mesh) {
  102879. var sceneOctree = _this.scene.selectionOctree;
  102880. if (sceneOctree !== undefined && sceneOctree !== null) {
  102881. sceneOctree.addMesh(mesh);
  102882. }
  102883. });
  102884. };
  102885. /**
  102886. * Return the list of active meshes
  102887. * @returns the list of active meshes
  102888. */
  102889. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  102890. if (this.scene._selectionOctree) {
  102891. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  102892. return selection;
  102893. }
  102894. return this.scene._getDefaultMeshCandidates();
  102895. };
  102896. /**
  102897. * Return the list of active sub meshes
  102898. * @param mesh The mesh to get the candidates sub meshes from
  102899. * @returns the list of active sub meshes
  102900. */
  102901. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  102902. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  102903. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  102904. return intersections;
  102905. }
  102906. return this.scene._getDefaultSubMeshCandidates(mesh);
  102907. };
  102908. /**
  102909. * Return the list of sub meshes intersecting with a given local ray
  102910. * @param mesh defines the mesh to find the submesh for
  102911. * @param localRay defines the ray in local space
  102912. * @returns the list of intersecting sub meshes
  102913. */
  102914. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  102915. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  102916. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  102917. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  102918. return intersections;
  102919. }
  102920. return this.scene._getDefaultSubMeshCandidates(mesh);
  102921. };
  102922. /**
  102923. * Return the list of sub meshes colliding with a collider
  102924. * @param mesh defines the mesh to find the submesh for
  102925. * @param collider defines the collider to evaluate the collision against
  102926. * @returns the list of colliding sub meshes
  102927. */
  102928. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  102929. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  102930. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  102931. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  102932. return intersections;
  102933. }
  102934. return this.scene._getDefaultSubMeshCandidates(mesh);
  102935. };
  102936. /**
  102937. * Rebuilds the elements related to this component in case of
  102938. * context lost for instance.
  102939. */
  102940. OctreeSceneComponent.prototype.rebuild = function () {
  102941. // Nothing to do here.
  102942. };
  102943. /**
  102944. * Disposes the component and the associated ressources.
  102945. */
  102946. OctreeSceneComponent.prototype.dispose = function () {
  102947. // Nothing to do here.
  102948. };
  102949. return OctreeSceneComponent;
  102950. }());
  102951. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  102952. })(BABYLON || (BABYLON = {}));
  102953. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  102954. var BABYLON;
  102955. (function (BABYLON) {
  102956. /**
  102957. * Postprocess used to generate anaglyphic rendering
  102958. */
  102959. var AnaglyphPostProcess = /** @class */ (function (_super) {
  102960. __extends(AnaglyphPostProcess, _super);
  102961. /**
  102962. * Creates a new AnaglyphPostProcess
  102963. * @param name defines postprocess name
  102964. * @param options defines creation options or target ratio scale
  102965. * @param rigCameras defines cameras using this postprocess
  102966. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  102967. * @param engine defines hosting engine
  102968. * @param reusable defines if the postprocess will be reused multiple times per frame
  102969. */
  102970. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  102971. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  102972. _this._passedProcess = rigCameras[0]._rigPostProcess;
  102973. _this.onApplyObservable.add(function (effect) {
  102974. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  102975. });
  102976. return _this;
  102977. }
  102978. return AnaglyphPostProcess;
  102979. }(BABYLON.PostProcess));
  102980. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  102981. })(BABYLON || (BABYLON = {}));
  102982. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  102983. var BABYLON;
  102984. (function (BABYLON) {
  102985. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  102986. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  102987. });
  102988. /**
  102989. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  102990. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  102991. */
  102992. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  102993. __extends(AnaglyphArcRotateCamera, _super);
  102994. /**
  102995. * Creates a new AnaglyphArcRotateCamera
  102996. * @param name defines camera name
  102997. * @param alpha defines alpha angle (in radians)
  102998. * @param beta defines beta angle (in radians)
  102999. * @param radius defines radius
  103000. * @param target defines camera target
  103001. * @param interaxialDistance defines distance between each color axis
  103002. * @param scene defines the hosting scene
  103003. */
  103004. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  103005. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  103006. _this.interaxialDistance = interaxialDistance;
  103007. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  103008. return _this;
  103009. }
  103010. /**
  103011. * Gets camera class name
  103012. * @returns AnaglyphArcRotateCamera
  103013. */
  103014. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  103015. return "AnaglyphArcRotateCamera";
  103016. };
  103017. return AnaglyphArcRotateCamera;
  103018. }(BABYLON.ArcRotateCamera));
  103019. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  103020. })(BABYLON || (BABYLON = {}));
  103021. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  103022. var BABYLON;
  103023. (function (BABYLON) {
  103024. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  103025. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  103026. });
  103027. /**
  103028. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  103029. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  103030. */
  103031. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  103032. __extends(AnaglyphFreeCamera, _super);
  103033. /**
  103034. * Creates a new AnaglyphFreeCamera
  103035. * @param name defines camera name
  103036. * @param position defines initial position
  103037. * @param interaxialDistance defines distance between each color axis
  103038. * @param scene defines the hosting scene
  103039. */
  103040. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  103041. var _this = _super.call(this, name, position, scene) || this;
  103042. _this.interaxialDistance = interaxialDistance;
  103043. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  103044. return _this;
  103045. }
  103046. /**
  103047. * Gets camera class name
  103048. * @returns AnaglyphFreeCamera
  103049. */
  103050. AnaglyphFreeCamera.prototype.getClassName = function () {
  103051. return "AnaglyphFreeCamera";
  103052. };
  103053. return AnaglyphFreeCamera;
  103054. }(BABYLON.FreeCamera));
  103055. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  103056. })(BABYLON || (BABYLON = {}));
  103057. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  103058. var BABYLON;
  103059. (function (BABYLON) {
  103060. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  103061. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  103062. });
  103063. /**
  103064. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  103065. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  103066. */
  103067. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  103068. __extends(AnaglyphGamepadCamera, _super);
  103069. /**
  103070. * Creates a new AnaglyphGamepadCamera
  103071. * @param name defines camera name
  103072. * @param position defines initial position
  103073. * @param interaxialDistance defines distance between each color axis
  103074. * @param scene defines the hosting scene
  103075. */
  103076. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  103077. var _this = _super.call(this, name, position, scene) || this;
  103078. _this.interaxialDistance = interaxialDistance;
  103079. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  103080. return _this;
  103081. }
  103082. /**
  103083. * Gets camera class name
  103084. * @returns AnaglyphGamepadCamera
  103085. */
  103086. AnaglyphGamepadCamera.prototype.getClassName = function () {
  103087. return "AnaglyphGamepadCamera";
  103088. };
  103089. return AnaglyphGamepadCamera;
  103090. }(BABYLON.GamepadCamera));
  103091. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  103092. })(BABYLON || (BABYLON = {}));
  103093. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  103094. var BABYLON;
  103095. (function (BABYLON) {
  103096. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  103097. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  103098. });
  103099. /**
  103100. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  103101. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  103102. */
  103103. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  103104. __extends(AnaglyphUniversalCamera, _super);
  103105. /**
  103106. * Creates a new AnaglyphUniversalCamera
  103107. * @param name defines camera name
  103108. * @param position defines initial position
  103109. * @param interaxialDistance defines distance between each color axis
  103110. * @param scene defines the hosting scene
  103111. */
  103112. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  103113. var _this = _super.call(this, name, position, scene) || this;
  103114. _this.interaxialDistance = interaxialDistance;
  103115. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  103116. return _this;
  103117. }
  103118. /**
  103119. * Gets camera class name
  103120. * @returns AnaglyphUniversalCamera
  103121. */
  103122. AnaglyphUniversalCamera.prototype.getClassName = function () {
  103123. return "AnaglyphUniversalCamera";
  103124. };
  103125. return AnaglyphUniversalCamera;
  103126. }(BABYLON.UniversalCamera));
  103127. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  103128. })(BABYLON || (BABYLON = {}));
  103129. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  103130. var BABYLON;
  103131. (function (BABYLON) {
  103132. /**
  103133. * StereoscopicInterlacePostProcess used to render stereo views from a rigged camera
  103134. */
  103135. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  103136. __extends(StereoscopicInterlacePostProcess, _super);
  103137. /**
  103138. * Initializes a StereoscopicInterlacePostProcess
  103139. * @param name The name of the effect.
  103140. * @param rigCameras The rig cameras to be appled to the post process
  103141. * @param isStereoscopicHoriz If the rendered results are horizontal or verticle
  103142. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  103143. * @param engine The engine which the post process will be applied. (default: current engine)
  103144. * @param reusable If the post process can be reused on the same frame. (default: false)
  103145. */
  103146. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  103147. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  103148. _this._passedProcess = rigCameras[0]._rigPostProcess;
  103149. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  103150. _this.onSizeChangedObservable.add(function () {
  103151. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  103152. });
  103153. _this.onApplyObservable.add(function (effect) {
  103154. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  103155. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  103156. });
  103157. return _this;
  103158. }
  103159. return StereoscopicInterlacePostProcess;
  103160. }(BABYLON.PostProcess));
  103161. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  103162. })(BABYLON || (BABYLON = {}));
  103163. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  103164. var BABYLON;
  103165. (function (BABYLON) {
  103166. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  103167. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  103168. });
  103169. /**
  103170. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  103171. * @see http://doc.babylonjs.com/features/cameras
  103172. */
  103173. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  103174. __extends(StereoscopicArcRotateCamera, _super);
  103175. /**
  103176. * Creates a new StereoscopicArcRotateCamera
  103177. * @param name defines camera name
  103178. * @param alpha defines alpha angle (in radians)
  103179. * @param beta defines beta angle (in radians)
  103180. * @param radius defines radius
  103181. * @param target defines camera target
  103182. * @param interaxialDistance defines distance between each color axis
  103183. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  103184. * @param scene defines the hosting scene
  103185. */
  103186. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  103187. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  103188. _this.interaxialDistance = interaxialDistance;
  103189. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  103190. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  103191. return _this;
  103192. }
  103193. /**
  103194. * Gets camera class name
  103195. * @returns StereoscopicArcRotateCamera
  103196. */
  103197. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  103198. return "StereoscopicArcRotateCamera";
  103199. };
  103200. return StereoscopicArcRotateCamera;
  103201. }(BABYLON.ArcRotateCamera));
  103202. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  103203. })(BABYLON || (BABYLON = {}));
  103204. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  103205. var BABYLON;
  103206. (function (BABYLON) {
  103207. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  103208. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  103209. });
  103210. /**
  103211. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  103212. * @see http://doc.babylonjs.com/features/cameras
  103213. */
  103214. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  103215. __extends(StereoscopicFreeCamera, _super);
  103216. /**
  103217. * Creates a new StereoscopicFreeCamera
  103218. * @param name defines camera name
  103219. * @param position defines initial position
  103220. * @param interaxialDistance defines distance between each color axis
  103221. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  103222. * @param scene defines the hosting scene
  103223. */
  103224. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  103225. var _this = _super.call(this, name, position, scene) || this;
  103226. _this.interaxialDistance = interaxialDistance;
  103227. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  103228. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  103229. return _this;
  103230. }
  103231. /**
  103232. * Gets camera class name
  103233. * @returns StereoscopicFreeCamera
  103234. */
  103235. StereoscopicFreeCamera.prototype.getClassName = function () {
  103236. return "StereoscopicFreeCamera";
  103237. };
  103238. return StereoscopicFreeCamera;
  103239. }(BABYLON.FreeCamera));
  103240. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  103241. })(BABYLON || (BABYLON = {}));
  103242. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  103243. var BABYLON;
  103244. (function (BABYLON) {
  103245. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  103246. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  103247. });
  103248. /**
  103249. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  103250. * @see http://doc.babylonjs.com/features/cameras
  103251. */
  103252. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  103253. __extends(StereoscopicGamepadCamera, _super);
  103254. /**
  103255. * Creates a new StereoscopicGamepadCamera
  103256. * @param name defines camera name
  103257. * @param position defines initial position
  103258. * @param interaxialDistance defines distance between each color axis
  103259. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  103260. * @param scene defines the hosting scene
  103261. */
  103262. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  103263. var _this = _super.call(this, name, position, scene) || this;
  103264. _this.interaxialDistance = interaxialDistance;
  103265. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  103266. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  103267. return _this;
  103268. }
  103269. /**
  103270. * Gets camera class name
  103271. * @returns StereoscopicGamepadCamera
  103272. */
  103273. StereoscopicGamepadCamera.prototype.getClassName = function () {
  103274. return "StereoscopicGamepadCamera";
  103275. };
  103276. return StereoscopicGamepadCamera;
  103277. }(BABYLON.GamepadCamera));
  103278. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  103279. })(BABYLON || (BABYLON = {}));
  103280. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  103281. var BABYLON;
  103282. (function (BABYLON) {
  103283. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  103284. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  103285. });
  103286. /**
  103287. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  103288. * @see http://doc.babylonjs.com/features/cameras
  103289. */
  103290. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  103291. __extends(StereoscopicUniversalCamera, _super);
  103292. /**
  103293. * Creates a new StereoscopicUniversalCamera
  103294. * @param name defines camera name
  103295. * @param position defines initial position
  103296. * @param interaxialDistance defines distance between each color axis
  103297. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  103298. * @param scene defines the hosting scene
  103299. */
  103300. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  103301. var _this = _super.call(this, name, position, scene) || this;
  103302. _this.interaxialDistance = interaxialDistance;
  103303. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  103304. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  103305. return _this;
  103306. }
  103307. /**
  103308. * Gets camera class name
  103309. * @returns StereoscopicUniversalCamera
  103310. */
  103311. StereoscopicUniversalCamera.prototype.getClassName = function () {
  103312. return "StereoscopicUniversalCamera";
  103313. };
  103314. return StereoscopicUniversalCamera;
  103315. }(BABYLON.UniversalCamera));
  103316. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  103317. })(BABYLON || (BABYLON = {}));
  103318. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  103319. var BABYLON;
  103320. (function (BABYLON) {
  103321. /**
  103322. * VRDistortionCorrectionPostProcess used for mobile VR
  103323. */
  103324. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  103325. __extends(VRDistortionCorrectionPostProcess, _super);
  103326. /**
  103327. * Initializes the VRDistortionCorrectionPostProcess
  103328. * @param name The name of the effect.
  103329. * @param camera The camera to apply the render pass to.
  103330. * @param isRightEye If this is for the right eye distortion
  103331. * @param vrMetrics All the required metrics for the VR camera
  103332. */
  103333. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  103334. var _this = _super.call(this, name, "vrDistortionCorrection", [
  103335. 'LensCenter',
  103336. 'Scale',
  103337. 'ScaleIn',
  103338. 'HmdWarpParam'
  103339. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  103340. _this._isRightEye = isRightEye;
  103341. _this._distortionFactors = vrMetrics.distortionK;
  103342. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  103343. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  103344. _this.adaptScaleToCurrentViewport = true;
  103345. _this.onSizeChangedObservable.add(function () {
  103346. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  103347. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  103348. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  103349. });
  103350. _this.onApplyObservable.add(function (effect) {
  103351. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  103352. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  103353. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  103354. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  103355. });
  103356. return _this;
  103357. }
  103358. return VRDistortionCorrectionPostProcess;
  103359. }(BABYLON.PostProcess));
  103360. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  103361. })(BABYLON || (BABYLON = {}));
  103362. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  103363. var BABYLON;
  103364. (function (BABYLON) {
  103365. /**
  103366. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  103367. * Screen rotation is taken into account.
  103368. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  103369. */
  103370. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  103371. /**
  103372. * Instantiates a new input
  103373. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  103374. */
  103375. function FreeCameraDeviceOrientationInput() {
  103376. var _this = this;
  103377. this._screenOrientationAngle = 0;
  103378. this._screenQuaternion = new BABYLON.Quaternion();
  103379. this._alpha = 0;
  103380. this._beta = 0;
  103381. this._gamma = 0;
  103382. this._orientationChanged = function () {
  103383. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  103384. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  103385. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  103386. };
  103387. this._deviceOrientation = function (evt) {
  103388. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  103389. _this._beta = evt.beta !== null ? evt.beta : 0;
  103390. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  103391. };
  103392. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  103393. this._orientationChanged();
  103394. }
  103395. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  103396. /**
  103397. * Define the camera controlled by the input.
  103398. */
  103399. get: function () {
  103400. return this._camera;
  103401. },
  103402. set: function (camera) {
  103403. this._camera = camera;
  103404. if (this._camera != null && !this._camera.rotationQuaternion) {
  103405. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  103406. }
  103407. },
  103408. enumerable: true,
  103409. configurable: true
  103410. });
  103411. /**
  103412. * Attach the input controls to a specific dom element to get the input from.
  103413. * @param element Defines the element the controls should be listened from
  103414. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  103415. */
  103416. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  103417. window.addEventListener("orientationchange", this._orientationChanged);
  103418. window.addEventListener("deviceorientation", this._deviceOrientation);
  103419. //In certain cases, the attach control is called AFTER orientation was changed,
  103420. //So this is needed.
  103421. this._orientationChanged();
  103422. };
  103423. /**
  103424. * Detach the current controls from the specified dom element.
  103425. * @param element Defines the element to stop listening the inputs from
  103426. */
  103427. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  103428. window.removeEventListener("orientationchange", this._orientationChanged);
  103429. window.removeEventListener("deviceorientation", this._deviceOrientation);
  103430. };
  103431. /**
  103432. * Update the current camera state depending on the inputs that have been used this frame.
  103433. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  103434. */
  103435. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  103436. //if no device orientation provided, don't update the rotation.
  103437. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  103438. if (!this._alpha) {
  103439. return;
  103440. }
  103441. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  103442. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  103443. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  103444. //Mirror on XY Plane
  103445. this._camera.rotationQuaternion.z *= -1;
  103446. this._camera.rotationQuaternion.w *= -1;
  103447. };
  103448. /**
  103449. * Gets the class name of the current intput.
  103450. * @returns the class name
  103451. */
  103452. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  103453. return "FreeCameraDeviceOrientationInput";
  103454. };
  103455. /**
  103456. * Get the friendly name associated with the input class.
  103457. * @returns the input friendly name
  103458. */
  103459. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  103460. return "deviceOrientation";
  103461. };
  103462. return FreeCameraDeviceOrientationInput;
  103463. }());
  103464. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  103465. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  103466. })(BABYLON || (BABYLON = {}));
  103467. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  103468. var BABYLON;
  103469. (function (BABYLON) {
  103470. /**
  103471. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  103472. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  103473. */
  103474. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  103475. /**
  103476. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  103477. */
  103478. function ArcRotateCameraVRDeviceOrientationInput() {
  103479. /**
  103480. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  103481. */
  103482. this.alphaCorrection = 1;
  103483. /**
  103484. * Defines a correction factor applied on the beta value retrieved from the orientation events.
  103485. */
  103486. this.betaCorrection = 1;
  103487. /**
  103488. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  103489. */
  103490. this.gammaCorrection = 1;
  103491. this._alpha = 0;
  103492. this._gamma = 0;
  103493. this._dirty = false;
  103494. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  103495. }
  103496. /**
  103497. * Attach the input controls to a specific dom element to get the input from.
  103498. * @param element Defines the element the controls should be listened from
  103499. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  103500. */
  103501. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  103502. this.camera.attachControl(element, noPreventDefault);
  103503. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  103504. };
  103505. /** @hidden */
  103506. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  103507. if (evt.alpha !== null) {
  103508. this._alpha = +evt.alpha | 0;
  103509. }
  103510. if (evt.gamma !== null) {
  103511. this._gamma = +evt.gamma | 0;
  103512. }
  103513. this._dirty = true;
  103514. };
  103515. /**
  103516. * Update the current camera state depending on the inputs that have been used this frame.
  103517. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  103518. */
  103519. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  103520. if (this._dirty) {
  103521. this._dirty = false;
  103522. if (this._gamma < 0) {
  103523. this._gamma = 180 + this._gamma;
  103524. }
  103525. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  103526. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  103527. }
  103528. };
  103529. /**
  103530. * Detach the current controls from the specified dom element.
  103531. * @param element Defines the element to stop listening the inputs from
  103532. */
  103533. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  103534. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  103535. };
  103536. /**
  103537. * Gets the class name of the current intput.
  103538. * @returns the class name
  103539. */
  103540. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  103541. return "ArcRotateCameraVRDeviceOrientationInput";
  103542. };
  103543. /**
  103544. * Get the friendly name associated with the input class.
  103545. * @returns the input friendly name
  103546. */
  103547. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  103548. return "VRDeviceOrientation";
  103549. };
  103550. return ArcRotateCameraVRDeviceOrientationInput;
  103551. }());
  103552. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  103553. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  103554. })(BABYLON || (BABYLON = {}));
  103555. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  103556. var BABYLON;
  103557. (function (BABYLON) {
  103558. /**
  103559. * This represents all the required metrics to create a VR camera.
  103560. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  103561. */
  103562. var VRCameraMetrics = /** @class */ (function () {
  103563. function VRCameraMetrics() {
  103564. /**
  103565. * Define if the current vr camera should compensate the distortion of the lense or not.
  103566. */
  103567. this.compensateDistortion = true;
  103568. }
  103569. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  103570. /**
  103571. * Gets the rendering aspect ratio based on the provided resolutions.
  103572. */
  103573. get: function () {
  103574. return this.hResolution / (2 * this.vResolution);
  103575. },
  103576. enumerable: true,
  103577. configurable: true
  103578. });
  103579. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  103580. /**
  103581. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  103582. */
  103583. get: function () {
  103584. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  103585. },
  103586. enumerable: true,
  103587. configurable: true
  103588. });
  103589. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  103590. /**
  103591. * @hidden
  103592. */
  103593. get: function () {
  103594. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  103595. var h = (4 * meters) / this.hScreenSize;
  103596. return BABYLON.Matrix.Translation(h, 0, 0);
  103597. },
  103598. enumerable: true,
  103599. configurable: true
  103600. });
  103601. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  103602. /**
  103603. * @hidden
  103604. */
  103605. get: function () {
  103606. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  103607. var h = (4 * meters) / this.hScreenSize;
  103608. return BABYLON.Matrix.Translation(-h, 0, 0);
  103609. },
  103610. enumerable: true,
  103611. configurable: true
  103612. });
  103613. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  103614. /**
  103615. * @hidden
  103616. */
  103617. get: function () {
  103618. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  103619. },
  103620. enumerable: true,
  103621. configurable: true
  103622. });
  103623. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  103624. /**
  103625. * @hidden
  103626. */
  103627. get: function () {
  103628. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  103629. },
  103630. enumerable: true,
  103631. configurable: true
  103632. });
  103633. /**
  103634. * Get the default VRMetrics based on the most generic setup.
  103635. * @returns the default vr metrics
  103636. */
  103637. VRCameraMetrics.GetDefault = function () {
  103638. var result = new VRCameraMetrics();
  103639. result.hResolution = 1280;
  103640. result.vResolution = 800;
  103641. result.hScreenSize = 0.149759993;
  103642. result.vScreenSize = 0.0935999975;
  103643. result.vScreenCenter = 0.0467999987;
  103644. result.eyeToScreenDistance = 0.0410000011;
  103645. result.lensSeparationDistance = 0.0635000020;
  103646. result.interpupillaryDistance = 0.0640000030;
  103647. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  103648. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  103649. result.postProcessScaleFactor = 1.714605507808412;
  103650. result.lensCenterOffset = 0.151976421;
  103651. return result;
  103652. };
  103653. return VRCameraMetrics;
  103654. }());
  103655. BABYLON.VRCameraMetrics = VRCameraMetrics;
  103656. })(BABYLON || (BABYLON = {}));
  103657. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  103658. var BABYLON;
  103659. (function (BABYLON) {
  103660. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  103661. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  103662. });
  103663. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  103664. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  103665. });
  103666. /**
  103667. * This represents a WebVR camera.
  103668. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  103669. * @example http://doc.babylonjs.com/how_to/webvr_camera
  103670. */
  103671. var WebVRFreeCamera = /** @class */ (function (_super) {
  103672. __extends(WebVRFreeCamera, _super);
  103673. /**
  103674. * Instantiates a WebVRFreeCamera.
  103675. * @param name The name of the WebVRFreeCamera
  103676. * @param position The starting anchor position for the camera
  103677. * @param scene The scene the camera belongs to
  103678. * @param webVROptions a set of customizable options for the webVRCamera
  103679. */
  103680. function WebVRFreeCamera(name, position, scene, webVROptions) {
  103681. if (webVROptions === void 0) { webVROptions = {}; }
  103682. var _this = _super.call(this, name, position, scene) || this;
  103683. _this.webVROptions = webVROptions;
  103684. /**
  103685. * @hidden
  103686. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  103687. */
  103688. _this._vrDevice = null;
  103689. /**
  103690. * The rawPose of the vrDevice.
  103691. */
  103692. _this.rawPose = null;
  103693. _this._specsVersion = "1.1";
  103694. _this._attached = false;
  103695. _this._descendants = [];
  103696. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  103697. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  103698. /** @hidden */
  103699. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  103700. _this._standingMatrix = null;
  103701. /**
  103702. * Represents device position in babylon space.
  103703. */
  103704. _this.devicePosition = BABYLON.Vector3.Zero();
  103705. /**
  103706. * Represents device rotation in babylon space.
  103707. */
  103708. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  103709. /**
  103710. * The scale of the device to be used when translating from device space to babylon space.
  103711. */
  103712. _this.deviceScaleFactor = 1;
  103713. _this._deviceToWorld = BABYLON.Matrix.Identity();
  103714. _this._worldToDevice = BABYLON.Matrix.Identity();
  103715. /**
  103716. * References to the webVR controllers for the vrDevice.
  103717. */
  103718. _this.controllers = [];
  103719. /**
  103720. * Emits an event when a controller is attached.
  103721. */
  103722. _this.onControllersAttachedObservable = new BABYLON.Observable();
  103723. /**
  103724. * Emits an event when a controller's mesh has been loaded;
  103725. */
  103726. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  103727. /**
  103728. * Emits an event when the HMD's pose has been updated.
  103729. */
  103730. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  103731. _this._poseSet = false;
  103732. /**
  103733. * If the rig cameras be used as parent instead of this camera.
  103734. */
  103735. _this.rigParenting = true;
  103736. _this._defaultHeight = undefined;
  103737. _this._htmlElementAttached = null;
  103738. _this._detachIfAttached = function () {
  103739. var vrDisplay = _this.getEngine().getVRDevice();
  103740. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  103741. _this.detachControl(_this._htmlElementAttached);
  103742. }
  103743. };
  103744. _this._workingVector = BABYLON.Vector3.Zero();
  103745. _this._oneVector = BABYLON.Vector3.One();
  103746. _this._workingMatrix = BABYLON.Matrix.Identity();
  103747. _this._tmpMatrix = new BABYLON.Matrix();
  103748. _this._cache.position = BABYLON.Vector3.Zero();
  103749. if (webVROptions.defaultHeight) {
  103750. _this._defaultHeight = webVROptions.defaultHeight;
  103751. _this.position.y = _this._defaultHeight;
  103752. }
  103753. _this.minZ = 0.1;
  103754. //legacy support - the compensation boolean was removed.
  103755. if (arguments.length === 5) {
  103756. _this.webVROptions = arguments[4];
  103757. }
  103758. // default webVR options
  103759. if (_this.webVROptions.trackPosition == undefined) {
  103760. _this.webVROptions.trackPosition = true;
  103761. }
  103762. if (_this.webVROptions.controllerMeshes == undefined) {
  103763. _this.webVROptions.controllerMeshes = true;
  103764. }
  103765. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  103766. _this.webVROptions.defaultLightingOnControllers = true;
  103767. }
  103768. _this.rotationQuaternion = new BABYLON.Quaternion();
  103769. if (_this.webVROptions && _this.webVROptions.positionScale) {
  103770. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  103771. }
  103772. //enable VR
  103773. var engine = _this.getEngine();
  103774. _this._onVREnabled = function (success) { if (success) {
  103775. _this.initControllers();
  103776. } };
  103777. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  103778. engine.initWebVR().add(function (event) {
  103779. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  103780. return;
  103781. }
  103782. _this._vrDevice = event.vrDisplay;
  103783. //reset the rig parameters.
  103784. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  103785. if (_this._attached) {
  103786. _this.getEngine().enableVR();
  103787. }
  103788. });
  103789. if (typeof (VRFrameData) !== "undefined") {
  103790. _this._frameData = new VRFrameData();
  103791. }
  103792. /**
  103793. * The idea behind the following lines:
  103794. * objects that have the camera as parent should actually have the rig cameras as a parent.
  103795. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  103796. * the second will not show it correctly.
  103797. *
  103798. * To solve this - each object that has the camera as parent will be added to a protected array.
  103799. * When the rig camera renders, it will take this array and set all of those to be its children.
  103800. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  103801. * Amazing!
  103802. */
  103803. scene.onBeforeCameraRenderObservable.add(function (camera) {
  103804. if (camera.parent === _this && _this.rigParenting) {
  103805. _this._descendants = _this.getDescendants(true, function (n) {
  103806. // don't take the cameras or the controllers!
  103807. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  103808. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  103809. return !isController && !isRigCamera;
  103810. });
  103811. _this._descendants.forEach(function (node) {
  103812. node.parent = camera;
  103813. });
  103814. }
  103815. });
  103816. scene.onAfterCameraRenderObservable.add(function (camera) {
  103817. if (camera.parent === _this && _this.rigParenting) {
  103818. _this._descendants.forEach(function (node) {
  103819. node.parent = _this;
  103820. });
  103821. }
  103822. });
  103823. return _this;
  103824. }
  103825. /**
  103826. * Gets the device distance from the ground in meters.
  103827. * @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.
  103828. */
  103829. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  103830. if (this._standingMatrix) {
  103831. // Add standing matrix offset to get real offset from ground in room
  103832. this._standingMatrix.getTranslationToRef(this._workingVector);
  103833. return this._deviceRoomPosition.y + this._workingVector.y;
  103834. }
  103835. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  103836. return this._defaultHeight || 0;
  103837. };
  103838. /**
  103839. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  103840. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  103841. */
  103842. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  103843. var _this = this;
  103844. if (callback === void 0) { callback = function (bool) { }; }
  103845. // Use standing matrix if available
  103846. this.getEngine().initWebVRAsync().then(function (result) {
  103847. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  103848. callback(false);
  103849. }
  103850. else {
  103851. _this._standingMatrix = new BABYLON.Matrix();
  103852. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  103853. if (!_this.getScene().useRightHandedSystem) {
  103854. [2, 6, 8, 9, 14].forEach(function (num) {
  103855. if (_this._standingMatrix) {
  103856. _this._standingMatrix.m[num] *= -1;
  103857. }
  103858. });
  103859. }
  103860. callback(true);
  103861. }
  103862. });
  103863. };
  103864. /**
  103865. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  103866. * @returns A promise with a boolean set to if the standing matrix is supported.
  103867. */
  103868. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  103869. var _this = this;
  103870. return new Promise(function (res, rej) {
  103871. _this.useStandingMatrix(function (supported) {
  103872. res(supported);
  103873. });
  103874. });
  103875. };
  103876. /**
  103877. * Disposes the camera
  103878. */
  103879. WebVRFreeCamera.prototype.dispose = function () {
  103880. this._detachIfAttached();
  103881. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  103882. if (this._updateCacheWhenTrackingDisabledObserver) {
  103883. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  103884. }
  103885. _super.prototype.dispose.call(this);
  103886. };
  103887. /**
  103888. * Gets a vrController by name.
  103889. * @param name The name of the controller to retreive
  103890. * @returns the controller matching the name specified or null if not found
  103891. */
  103892. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  103893. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  103894. var gp = _a[_i];
  103895. if (gp.hand === name) {
  103896. return gp;
  103897. }
  103898. }
  103899. return null;
  103900. };
  103901. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  103902. /**
  103903. * The controller corrisponding to the users left hand.
  103904. */
  103905. get: function () {
  103906. if (!this._leftController) {
  103907. this._leftController = this.getControllerByName("left");
  103908. }
  103909. return this._leftController;
  103910. },
  103911. enumerable: true,
  103912. configurable: true
  103913. });
  103914. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  103915. /**
  103916. * The controller corrisponding to the users right hand.
  103917. */
  103918. get: function () {
  103919. if (!this._rightController) {
  103920. this._rightController = this.getControllerByName("right");
  103921. }
  103922. return this._rightController;
  103923. },
  103924. enumerable: true,
  103925. configurable: true
  103926. });
  103927. /**
  103928. * Casts a ray forward from the vrCamera's gaze.
  103929. * @param length Length of the ray (default: 100)
  103930. * @returns the ray corrisponding to the gaze
  103931. */
  103932. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  103933. if (length === void 0) { length = 100; }
  103934. if (this.leftCamera) {
  103935. // Use left eye to avoid computation to compute center on every call
  103936. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  103937. }
  103938. else {
  103939. return _super.prototype.getForwardRay.call(this, length);
  103940. }
  103941. };
  103942. /**
  103943. * @hidden
  103944. * Updates the camera based on device's frame data
  103945. */
  103946. WebVRFreeCamera.prototype._checkInputs = function () {
  103947. if (this._vrDevice && this._vrDevice.isPresenting) {
  103948. this._vrDevice.getFrameData(this._frameData);
  103949. this.updateFromDevice(this._frameData.pose);
  103950. }
  103951. _super.prototype._checkInputs.call(this);
  103952. };
  103953. /**
  103954. * Updates the poseControlled values based on the input device pose.
  103955. * @param poseData Pose coming from the device
  103956. */
  103957. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  103958. if (poseData && poseData.orientation) {
  103959. this.rawPose = poseData;
  103960. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  103961. if (this.getScene().useRightHandedSystem) {
  103962. this._deviceRoomRotationQuaternion.z *= -1;
  103963. this._deviceRoomRotationQuaternion.w *= -1;
  103964. }
  103965. if (this.webVROptions.trackPosition && this.rawPose.position) {
  103966. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  103967. if (this.getScene().useRightHandedSystem) {
  103968. this._deviceRoomPosition.z *= -1;
  103969. }
  103970. }
  103971. this._poseSet = true;
  103972. }
  103973. };
  103974. /**
  103975. * WebVR's attach control will start broadcasting frames to the device.
  103976. * Note that in certain browsers (chrome for example) this function must be called
  103977. * within a user-interaction callback. Example:
  103978. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  103979. *
  103980. * @param element html element to attach the vrDevice to
  103981. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  103982. */
  103983. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  103984. _super.prototype.attachControl.call(this, element, noPreventDefault);
  103985. this._attached = true;
  103986. this._htmlElementAttached = element;
  103987. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  103988. if (this._vrDevice) {
  103989. this.getEngine().enableVR();
  103990. }
  103991. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  103992. };
  103993. /**
  103994. * Detaches the camera from the html element and disables VR
  103995. *
  103996. * @param element html element to detach from
  103997. */
  103998. WebVRFreeCamera.prototype.detachControl = function (element) {
  103999. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  104000. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  104001. _super.prototype.detachControl.call(this, element);
  104002. this._attached = false;
  104003. this.getEngine().disableVR();
  104004. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  104005. };
  104006. /**
  104007. * @returns the name of this class
  104008. */
  104009. WebVRFreeCamera.prototype.getClassName = function () {
  104010. return "WebVRFreeCamera";
  104011. };
  104012. /**
  104013. * Calls resetPose on the vrDisplay
  104014. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  104015. */
  104016. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  104017. //uses the vrDisplay's "resetPose()".
  104018. //pitch and roll won't be affected.
  104019. this._vrDevice.resetPose();
  104020. };
  104021. /**
  104022. * @hidden
  104023. * Updates the rig cameras (left and right eye)
  104024. */
  104025. WebVRFreeCamera.prototype._updateRigCameras = function () {
  104026. var camLeft = this._rigCameras[0];
  104027. var camRight = this._rigCameras[1];
  104028. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  104029. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  104030. camLeft.position.copyFrom(this._deviceRoomPosition);
  104031. camRight.position.copyFrom(this._deviceRoomPosition);
  104032. };
  104033. // Remove translation from 6dof headset if trackposition is set to false
  104034. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  104035. if (isViewMatrix === void 0) { isViewMatrix = false; }
  104036. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  104037. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  104038. if (!isViewMatrix) {
  104039. this._tmpMatrix.invert();
  104040. }
  104041. this._tmpMatrix.multiplyToRef(matrix, matrix);
  104042. }
  104043. };
  104044. /**
  104045. * @hidden
  104046. * Updates the cached values of the camera
  104047. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  104048. */
  104049. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  104050. var _this = this;
  104051. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  104052. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  104053. if (!this.updateCacheCalled) {
  104054. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  104055. this.updateCacheCalled = true;
  104056. this.update();
  104057. }
  104058. // Set working vector to the device position in room space rotated by the new rotation
  104059. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  104060. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  104061. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  104062. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  104063. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  104064. // Add translation from anchor position
  104065. this._deviceToWorld.getTranslationToRef(this._workingVector);
  104066. this._workingVector.addInPlace(this.position);
  104067. this._workingVector.subtractInPlace(this._cache.position);
  104068. this._deviceToWorld.setTranslation(this._workingVector);
  104069. // Set an inverted matrix to be used when updating the camera
  104070. this._deviceToWorld.invertToRef(this._worldToDevice);
  104071. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  104072. this.controllers.forEach(function (controller) {
  104073. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  104074. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  104075. controller.update();
  104076. });
  104077. }
  104078. if (!ignoreParentClass) {
  104079. _super.prototype._updateCache.call(this);
  104080. }
  104081. this.updateCacheCalled = false;
  104082. };
  104083. /**
  104084. * @hidden
  104085. * Get current device position in babylon world
  104086. */
  104087. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  104088. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  104089. };
  104090. /**
  104091. * Updates the current device position and rotation in the babylon world
  104092. */
  104093. WebVRFreeCamera.prototype.update = function () {
  104094. this._computeDevicePosition();
  104095. // Get current device rotation in babylon world
  104096. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  104097. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  104098. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  104099. if (this._poseSet) {
  104100. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  104101. }
  104102. _super.prototype.update.call(this);
  104103. };
  104104. /**
  104105. * @hidden
  104106. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  104107. * @returns an identity matrix
  104108. */
  104109. WebVRFreeCamera.prototype._getViewMatrix = function () {
  104110. return BABYLON.Matrix.Identity();
  104111. };
  104112. /**
  104113. * This function is called by the two RIG cameras.
  104114. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  104115. */
  104116. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  104117. var _this = this;
  104118. // Update the parent camera prior to using a child camera to avoid desynchronization
  104119. var parentCamera = this._cameraRigParams["parentCamera"];
  104120. parentCamera._updateCache();
  104121. //WebVR 1.1
  104122. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  104123. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  104124. if (!this.getScene().useRightHandedSystem) {
  104125. [2, 6, 8, 9, 14].forEach(function (num) {
  104126. _this._webvrViewMatrix.m[num] *= -1;
  104127. });
  104128. }
  104129. // update the camera rotation matrix
  104130. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  104131. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  104132. // Computing target and final matrix
  104133. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  104134. // should the view matrix be updated with scale and position offset?
  104135. if (parentCamera.deviceScaleFactor !== 1) {
  104136. this._webvrViewMatrix.invert();
  104137. // scale the position, if set
  104138. if (parentCamera.deviceScaleFactor) {
  104139. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  104140. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  104141. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  104142. }
  104143. this._webvrViewMatrix.invert();
  104144. }
  104145. // Remove translation from 6dof headset if trackposition is set to false
  104146. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  104147. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  104148. // Compute global position
  104149. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  104150. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  104151. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  104152. this._workingMatrix.getTranslationToRef(this._globalPosition);
  104153. this._markSyncedWithParent();
  104154. return this._webvrViewMatrix;
  104155. };
  104156. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  104157. var _this = this;
  104158. var parentCamera = this.parent;
  104159. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  104160. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  104161. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  104162. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  104163. //babylon compatible matrix
  104164. if (!this.getScene().useRightHandedSystem) {
  104165. [8, 9, 10, 11].forEach(function (num) {
  104166. _this._projectionMatrix.m[num] *= -1;
  104167. });
  104168. }
  104169. return this._projectionMatrix;
  104170. };
  104171. /**
  104172. * Initializes the controllers and their meshes
  104173. */
  104174. WebVRFreeCamera.prototype.initControllers = function () {
  104175. var _this = this;
  104176. this.controllers = [];
  104177. var manager = this.getScene().gamepadManager;
  104178. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  104179. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  104180. var webVrController = gamepad;
  104181. if (webVrController.defaultModel) {
  104182. webVrController.defaultModel.setEnabled(false);
  104183. }
  104184. if (webVrController.hand === "right") {
  104185. _this._rightController = null;
  104186. }
  104187. if (webVrController.hand === "left") {
  104188. _this._leftController = null;
  104189. }
  104190. var controllerIndex = _this.controllers.indexOf(webVrController);
  104191. if (controllerIndex !== -1) {
  104192. _this.controllers.splice(controllerIndex, 1);
  104193. }
  104194. }
  104195. });
  104196. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  104197. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  104198. var webVrController_1 = gamepad;
  104199. if (!_this.webVROptions.trackPosition) {
  104200. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  104201. // Cache must be updated before rendering controllers to avoid them being one frame behind
  104202. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  104203. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  104204. _this._updateCache();
  104205. });
  104206. }
  104207. }
  104208. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  104209. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  104210. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  104211. if (_this.webVROptions.controllerMeshes) {
  104212. if (webVrController_1.defaultModel) {
  104213. webVrController_1.defaultModel.setEnabled(true);
  104214. }
  104215. else {
  104216. // Load the meshes
  104217. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  104218. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  104219. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  104220. if (_this.webVROptions.defaultLightingOnControllers) {
  104221. if (!_this._lightOnControllers) {
  104222. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  104223. }
  104224. var activateLightOnSubMeshes_1 = function (mesh, light) {
  104225. var children = mesh.getChildren();
  104226. if (children && children.length !== 0) {
  104227. children.forEach(function (mesh) {
  104228. light.includedOnlyMeshes.push(mesh);
  104229. activateLightOnSubMeshes_1(mesh, light);
  104230. });
  104231. }
  104232. };
  104233. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  104234. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  104235. }
  104236. });
  104237. }
  104238. }
  104239. webVrController_1.attachToPoseControlledCamera(_this);
  104240. // since this is async - sanity check. Is the controller already stored?
  104241. if (_this.controllers.indexOf(webVrController_1) === -1) {
  104242. //add to the controllers array
  104243. _this.controllers.push(webVrController_1);
  104244. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  104245. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  104246. // So we're overriding setting left & right manually to be sure
  104247. var firstViveWandDetected = false;
  104248. for (var i = 0; i < _this.controllers.length; i++) {
  104249. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  104250. if (!firstViveWandDetected) {
  104251. firstViveWandDetected = true;
  104252. _this.controllers[i].hand = "left";
  104253. }
  104254. else {
  104255. _this.controllers[i].hand = "right";
  104256. }
  104257. }
  104258. }
  104259. //did we find enough controllers? Great! let the developer know.
  104260. if (_this.controllers.length >= 2) {
  104261. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  104262. }
  104263. }
  104264. }
  104265. });
  104266. };
  104267. return WebVRFreeCamera;
  104268. }(BABYLON.FreeCamera));
  104269. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  104270. })(BABYLON || (BABYLON = {}));
  104271. //# sourceMappingURL=babylon.webVRCamera.js.map
  104272. var BABYLON;
  104273. (function (BABYLON) {
  104274. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  104275. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  104276. });
  104277. // We're mainly based on the logic defined into the FreeCamera code
  104278. /**
  104279. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  104280. * being tilted forward or back and left or right.
  104281. */
  104282. var DeviceOrientationCamera = /** @class */ (function (_super) {
  104283. __extends(DeviceOrientationCamera, _super);
  104284. /**
  104285. * Creates a new device orientation camera
  104286. * @param name The name of the camera
  104287. * @param position The start position camera
  104288. * @param scene The scene the camera belongs to
  104289. */
  104290. function DeviceOrientationCamera(name, position, scene) {
  104291. var _this = _super.call(this, name, position, scene) || this;
  104292. _this._quaternionCache = new BABYLON.Quaternion();
  104293. _this.inputs.addDeviceOrientation();
  104294. return _this;
  104295. }
  104296. /**
  104297. * Gets the current instance class name ("DeviceOrientationCamera").
  104298. * This helps avoiding instanceof at run time.
  104299. * @returns the class name
  104300. */
  104301. DeviceOrientationCamera.prototype.getClassName = function () {
  104302. return "DeviceOrientationCamera";
  104303. };
  104304. /**
  104305. * @hidden
  104306. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  104307. */
  104308. DeviceOrientationCamera.prototype._checkInputs = function () {
  104309. _super.prototype._checkInputs.call(this);
  104310. this._quaternionCache.copyFrom(this.rotationQuaternion);
  104311. if (this._initialQuaternion) {
  104312. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  104313. }
  104314. };
  104315. /**
  104316. * Reset the camera to its default orientation on the specified axis only.
  104317. * @param axis The axis to reset
  104318. */
  104319. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  104320. var _this = this;
  104321. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  104322. //can only work if this camera has a rotation quaternion already.
  104323. if (!this.rotationQuaternion) {
  104324. return;
  104325. }
  104326. if (!this._initialQuaternion) {
  104327. this._initialQuaternion = new BABYLON.Quaternion();
  104328. }
  104329. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  104330. ['x', 'y', 'z'].forEach(function (axisName) {
  104331. if (!axis[axisName]) {
  104332. _this._initialQuaternion[axisName] = 0;
  104333. }
  104334. else {
  104335. _this._initialQuaternion[axisName] *= -1;
  104336. }
  104337. });
  104338. this._initialQuaternion.normalize();
  104339. //force rotation update
  104340. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  104341. };
  104342. return DeviceOrientationCamera;
  104343. }(BABYLON.FreeCamera));
  104344. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  104345. })(BABYLON || (BABYLON = {}));
  104346. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  104347. var BABYLON;
  104348. (function (BABYLON) {
  104349. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  104350. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  104351. });
  104352. /**
  104353. * Camera used to simulate VR rendering (based on FreeCamera)
  104354. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  104355. */
  104356. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  104357. __extends(VRDeviceOrientationFreeCamera, _super);
  104358. /**
  104359. * Creates a new VRDeviceOrientationFreeCamera
  104360. * @param name defines camera name
  104361. * @param position defines the start position of the camera
  104362. * @param scene defines the scene the camera belongs to
  104363. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  104364. * @param vrCameraMetrics defines the vr metrics associated to the camera
  104365. */
  104366. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  104367. if (compensateDistortion === void 0) { compensateDistortion = true; }
  104368. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  104369. var _this = _super.call(this, name, position, scene) || this;
  104370. vrCameraMetrics.compensateDistortion = compensateDistortion;
  104371. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  104372. return _this;
  104373. }
  104374. /**
  104375. * Gets camera class name
  104376. * @returns VRDeviceOrientationFreeCamera
  104377. */
  104378. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  104379. return "VRDeviceOrientationFreeCamera";
  104380. };
  104381. return VRDeviceOrientationFreeCamera;
  104382. }(BABYLON.DeviceOrientationCamera));
  104383. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  104384. })(BABYLON || (BABYLON = {}));
  104385. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  104386. var BABYLON;
  104387. (function (BABYLON) {
  104388. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  104389. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  104390. });
  104391. /**
  104392. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  104393. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  104394. */
  104395. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  104396. __extends(VRDeviceOrientationArcRotateCamera, _super);
  104397. /**
  104398. * Creates a new VRDeviceOrientationArcRotateCamera
  104399. * @param name defines camera name
  104400. * @param alpha defines the camera rotation along the logitudinal axis
  104401. * @param beta defines the camera rotation along the latitudinal axis
  104402. * @param radius defines the camera distance from its target
  104403. * @param target defines the camera target
  104404. * @param scene defines the scene the camera belongs to
  104405. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  104406. * @param vrCameraMetrics defines the vr metrics associated to the camera
  104407. */
  104408. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  104409. if (compensateDistortion === void 0) { compensateDistortion = true; }
  104410. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  104411. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  104412. vrCameraMetrics.compensateDistortion = compensateDistortion;
  104413. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  104414. _this.inputs.addVRDeviceOrientation();
  104415. return _this;
  104416. }
  104417. /**
  104418. * Gets camera class name
  104419. * @returns VRDeviceOrientationArcRotateCamera
  104420. */
  104421. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  104422. return "VRDeviceOrientationArcRotateCamera";
  104423. };
  104424. return VRDeviceOrientationArcRotateCamera;
  104425. }(BABYLON.ArcRotateCamera));
  104426. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  104427. })(BABYLON || (BABYLON = {}));
  104428. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  104429. var BABYLON;
  104430. (function (BABYLON) {
  104431. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  104432. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  104433. });
  104434. /**
  104435. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  104436. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  104437. */
  104438. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  104439. __extends(VRDeviceOrientationGamepadCamera, _super);
  104440. /**
  104441. * Creates a new VRDeviceOrientationGamepadCamera
  104442. * @param name defines camera name
  104443. * @param position defines the start position of the camera
  104444. * @param scene defines the scene the camera belongs to
  104445. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  104446. * @param vrCameraMetrics defines the vr metrics associated to the camera
  104447. */
  104448. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  104449. if (compensateDistortion === void 0) { compensateDistortion = true; }
  104450. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  104451. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  104452. _this.inputs.addGamepad();
  104453. return _this;
  104454. }
  104455. /**
  104456. * Gets camera class name
  104457. * @returns VRDeviceOrientationGamepadCamera
  104458. */
  104459. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  104460. return "VRDeviceOrientationGamepadCamera";
  104461. };
  104462. return VRDeviceOrientationGamepadCamera;
  104463. }(BABYLON.VRDeviceOrientationFreeCamera));
  104464. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  104465. })(BABYLON || (BABYLON = {}));
  104466. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  104467. var BABYLON;
  104468. (function (BABYLON) {
  104469. var VRExperienceHelperGazer = /** @class */ (function () {
  104470. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  104471. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  104472. this.scene = scene;
  104473. /** @hidden */
  104474. this._pointerDownOnMeshAsked = false;
  104475. /** @hidden */
  104476. this._isActionableMesh = false;
  104477. /** @hidden */
  104478. this._teleportationRequestInitiated = false;
  104479. /** @hidden */
  104480. this._teleportationBackRequestInitiated = false;
  104481. /** @hidden */
  104482. this._rotationRightAsked = false;
  104483. /** @hidden */
  104484. this._rotationLeftAsked = false;
  104485. /** @hidden */
  104486. this._dpadPressed = true;
  104487. /** @hidden */
  104488. this._activePointer = false;
  104489. this._id = VRExperienceHelperGazer._idCounter++;
  104490. // Gaze tracker
  104491. if (!gazeTrackerToClone) {
  104492. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  104493. this._gazeTracker.bakeCurrentTransformIntoVertices();
  104494. this._gazeTracker.isPickable = false;
  104495. this._gazeTracker.isVisible = false;
  104496. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  104497. targetMat.specularColor = BABYLON.Color3.Black();
  104498. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  104499. targetMat.backFaceCulling = false;
  104500. this._gazeTracker.material = targetMat;
  104501. }
  104502. else {
  104503. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  104504. }
  104505. }
  104506. /** @hidden */
  104507. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  104508. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  104509. };
  104510. /** @hidden */
  104511. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  104512. this._pointerDownOnMeshAsked = true;
  104513. if (this._currentHit) {
  104514. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  104515. }
  104516. };
  104517. /** @hidden */
  104518. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  104519. if (this._currentHit) {
  104520. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  104521. }
  104522. this._pointerDownOnMeshAsked = false;
  104523. };
  104524. /** @hidden */
  104525. VRExperienceHelperGazer.prototype._activatePointer = function () {
  104526. this._activePointer = true;
  104527. };
  104528. /** @hidden */
  104529. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  104530. this._activePointer = false;
  104531. };
  104532. /** @hidden */
  104533. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  104534. if (distance === void 0) { distance = 100; }
  104535. };
  104536. VRExperienceHelperGazer.prototype.dispose = function () {
  104537. this._interactionsEnabled = false;
  104538. this._teleportationEnabled = false;
  104539. if (this._gazeTracker) {
  104540. this._gazeTracker.dispose();
  104541. }
  104542. };
  104543. VRExperienceHelperGazer._idCounter = 0;
  104544. return VRExperienceHelperGazer;
  104545. }());
  104546. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  104547. __extends(VRExperienceHelperControllerGazer, _super);
  104548. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  104549. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  104550. _this.webVRController = webVRController;
  104551. // Laser pointer
  104552. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  104553. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  104554. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  104555. laserPointerMaterial.alpha = 0.6;
  104556. _this._laserPointer.material = laserPointerMaterial;
  104557. _this._laserPointer.rotation.x = Math.PI / 2;
  104558. _this._laserPointer.position.z = -0.5;
  104559. _this._laserPointer.isVisible = false;
  104560. _this._laserPointer.isPickable = false;
  104561. if (!webVRController.mesh) {
  104562. // Create an empty mesh that is used prior to loading the high quality model
  104563. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  104564. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  104565. preloadPointerPose.rotation.x = -0.7;
  104566. preloadMesh.addChild(preloadPointerPose);
  104567. webVRController.attachToMesh(preloadMesh);
  104568. }
  104569. _this._setLaserPointerParent(webVRController.mesh);
  104570. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  104571. _this._setLaserPointerParent(mesh);
  104572. });
  104573. return _this;
  104574. }
  104575. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  104576. return this.webVRController.getForwardRay(length);
  104577. };
  104578. /** @hidden */
  104579. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  104580. _super.prototype._activatePointer.call(this);
  104581. this._laserPointer.isVisible = true;
  104582. };
  104583. /** @hidden */
  104584. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  104585. _super.prototype._deactivatePointer.call(this);
  104586. this._laserPointer.isVisible = false;
  104587. };
  104588. /** @hidden */
  104589. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  104590. this._laserPointer.material.emissiveColor = color;
  104591. };
  104592. /** @hidden */
  104593. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  104594. var makeNotPick = function (root) {
  104595. root.isPickable = false;
  104596. root.getChildMeshes().forEach(function (c) {
  104597. makeNotPick(c);
  104598. });
  104599. };
  104600. makeNotPick(mesh);
  104601. var childMeshes = mesh.getChildMeshes();
  104602. this.webVRController._pointingPoseNode = null;
  104603. for (var i = 0; i < childMeshes.length; i++) {
  104604. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  104605. mesh = childMeshes[i];
  104606. this.webVRController._pointingPoseNode = mesh;
  104607. break;
  104608. }
  104609. }
  104610. this._laserPointer.parent = mesh;
  104611. };
  104612. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  104613. if (distance === void 0) { distance = 100; }
  104614. this._laserPointer.scaling.y = distance;
  104615. this._laserPointer.position.z = -distance / 2;
  104616. };
  104617. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  104618. _super.prototype.dispose.call(this);
  104619. this._laserPointer.dispose();
  104620. if (this._meshAttachedObserver) {
  104621. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  104622. }
  104623. };
  104624. return VRExperienceHelperControllerGazer;
  104625. }(VRExperienceHelperGazer));
  104626. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  104627. __extends(VRExperienceHelperCameraGazer, _super);
  104628. function VRExperienceHelperCameraGazer(getCamera, scene) {
  104629. var _this = _super.call(this, scene) || this;
  104630. _this.getCamera = getCamera;
  104631. return _this;
  104632. }
  104633. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  104634. var camera = this.getCamera();
  104635. if (camera) {
  104636. return camera.getForwardRay(length);
  104637. }
  104638. else {
  104639. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  104640. }
  104641. };
  104642. return VRExperienceHelperCameraGazer;
  104643. }(VRExperienceHelperGazer));
  104644. /**
  104645. * Helps to quickly add VR support to an existing scene.
  104646. * See http://doc.babylonjs.com/how_to/webvr_helper
  104647. */
  104648. var VRExperienceHelper = /** @class */ (function () {
  104649. /**
  104650. * Instantiates a VRExperienceHelper.
  104651. * Helps to quickly add VR support to an existing scene.
  104652. * @param scene The scene the VRExperienceHelper belongs to.
  104653. * @param webVROptions Options to modify the vr experience helper's behavior.
  104654. */
  104655. function VRExperienceHelper(scene,
  104656. /** Options to modify the vr experience helper's behavior. */
  104657. webVROptions) {
  104658. if (webVROptions === void 0) { webVROptions = {}; }
  104659. var _this = this;
  104660. this.webVROptions = webVROptions;
  104661. // Can the system support WebVR, even if a headset isn't plugged in?
  104662. this._webVRsupported = false;
  104663. // If WebVR is supported, is a headset plugged in and are we ready to present?
  104664. this._webVRready = false;
  104665. // Are we waiting for the requestPresent callback to complete?
  104666. this._webVRrequesting = false;
  104667. // Are we presenting to the headset right now? (this is the vrDevice state)
  104668. this._webVRpresenting = false;
  104669. // Are we presenting in the fullscreen fallback?
  104670. this._fullscreenVRpresenting = false;
  104671. /**
  104672. * Observable raised when entering VR.
  104673. */
  104674. this.onEnteringVRObservable = new BABYLON.Observable();
  104675. /**
  104676. * Observable raised when exiting VR.
  104677. */
  104678. this.onExitingVRObservable = new BABYLON.Observable();
  104679. /**
  104680. * Observable raised when controller mesh is loaded.
  104681. */
  104682. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  104683. this._useCustomVRButton = false;
  104684. this._teleportationRequested = false;
  104685. this._teleportActive = false;
  104686. this._floorMeshesCollection = [];
  104687. this._rotationAllowed = true;
  104688. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  104689. this._isDefaultTeleportationTarget = true;
  104690. this._teleportationFillColor = "#444444";
  104691. this._teleportationBorderColor = "#FFFFFF";
  104692. this._rotationAngle = 0;
  104693. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  104694. this._padSensibilityUp = 0.65;
  104695. this._padSensibilityDown = 0.35;
  104696. this._leftController = null;
  104697. this._rightController = null;
  104698. /**
  104699. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  104700. */
  104701. this.onNewMeshSelected = new BABYLON.Observable();
  104702. /**
  104703. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  104704. */
  104705. this.onNewMeshPicked = new BABYLON.Observable();
  104706. /**
  104707. * Observable raised before camera teleportation
  104708. */
  104709. this.onBeforeCameraTeleport = new BABYLON.Observable();
  104710. /**
  104711. * Observable raised after camera teleportation
  104712. */
  104713. this.onAfterCameraTeleport = new BABYLON.Observable();
  104714. /**
  104715. * Observable raised when current selected mesh gets unselected
  104716. */
  104717. this.onSelectedMeshUnselected = new BABYLON.Observable();
  104718. /**
  104719. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  104720. */
  104721. this.teleportationEnabled = true;
  104722. this._teleportationInitialized = false;
  104723. this._interactionsEnabled = false;
  104724. this._interactionsRequested = false;
  104725. this._displayGaze = true;
  104726. this._displayLaserPointer = true;
  104727. /**
  104728. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  104729. */
  104730. this.updateGazeTrackerScale = true;
  104731. this._onResize = function () {
  104732. _this.moveButtonToBottomRight();
  104733. if (_this._fullscreenVRpresenting && _this._webVRready) {
  104734. _this.exitVR();
  104735. }
  104736. };
  104737. this._onFullscreenChange = function () {
  104738. if (document.fullscreen !== undefined) {
  104739. _this._fullscreenVRpresenting = document.fullscreen;
  104740. }
  104741. else if (document.mozFullScreen !== undefined) {
  104742. _this._fullscreenVRpresenting = document.mozFullScreen;
  104743. }
  104744. else if (document.webkitIsFullScreen !== undefined) {
  104745. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  104746. }
  104747. else if (document.msIsFullScreen !== undefined) {
  104748. _this._fullscreenVRpresenting = document.msIsFullScreen;
  104749. }
  104750. else if (document.msFullscreenElement !== undefined) {
  104751. _this._fullscreenVRpresenting = document.msFullscreenElement;
  104752. }
  104753. if (!_this._fullscreenVRpresenting && _this._canvas) {
  104754. _this.exitVR();
  104755. if (!_this._useCustomVRButton) {
  104756. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  104757. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  104758. }
  104759. }
  104760. };
  104761. this.beforeRender = function () {
  104762. if (_this._leftController && _this._leftController._activePointer) {
  104763. _this._castRayAndSelectObject(_this._leftController);
  104764. }
  104765. if (_this._rightController && _this._rightController._activePointer) {
  104766. _this._castRayAndSelectObject(_this._rightController);
  104767. }
  104768. if (_this._noControllerIsActive) {
  104769. _this._castRayAndSelectObject(_this._cameraGazer);
  104770. }
  104771. else {
  104772. _this._cameraGazer._gazeTracker.isVisible = false;
  104773. }
  104774. };
  104775. this._onNewGamepadConnected = function (gamepad) {
  104776. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  104777. if (gamepad.leftStick) {
  104778. gamepad.onleftstickchanged(function (stickValues) {
  104779. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  104780. // Listening to classic/xbox gamepad only if no VR controller is active
  104781. if ((!_this._leftController && !_this._rightController) ||
  104782. ((_this._leftController && !_this._leftController._activePointer) &&
  104783. (_this._rightController && !_this._rightController._activePointer))) {
  104784. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  104785. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  104786. }
  104787. }
  104788. });
  104789. }
  104790. if (gamepad.rightStick) {
  104791. gamepad.onrightstickchanged(function (stickValues) {
  104792. if (_this._teleportationInitialized) {
  104793. _this._checkRotate(stickValues, _this._cameraGazer);
  104794. }
  104795. });
  104796. }
  104797. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  104798. gamepad.onbuttondown(function (buttonPressed) {
  104799. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  104800. _this._cameraGazer._selectionPointerDown();
  104801. }
  104802. });
  104803. gamepad.onbuttonup(function (buttonPressed) {
  104804. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  104805. _this._cameraGazer._selectionPointerUp();
  104806. }
  104807. });
  104808. }
  104809. }
  104810. else {
  104811. var webVRController = gamepad;
  104812. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  104813. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  104814. _this._rightController = controller;
  104815. }
  104816. else {
  104817. _this._leftController = controller;
  104818. }
  104819. _this._tryEnableInteractionOnController(controller);
  104820. }
  104821. };
  104822. // 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
  104823. this._tryEnableInteractionOnController = function (controller) {
  104824. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  104825. _this._enableInteractionOnController(controller);
  104826. }
  104827. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  104828. _this._enableTeleportationOnController(controller);
  104829. }
  104830. };
  104831. this._onNewGamepadDisconnected = function (gamepad) {
  104832. if (gamepad instanceof BABYLON.WebVRController) {
  104833. if (gamepad.hand === "left" && _this._leftController != null) {
  104834. _this._leftController.dispose();
  104835. _this._leftController = null;
  104836. }
  104837. if (gamepad.hand === "right" && _this._rightController != null) {
  104838. _this._rightController.dispose();
  104839. _this._rightController = null;
  104840. }
  104841. }
  104842. };
  104843. this._workingVector = BABYLON.Vector3.Zero();
  104844. this._workingQuaternion = BABYLON.Quaternion.Identity();
  104845. this._workingMatrix = BABYLON.Matrix.Identity();
  104846. this._scene = scene;
  104847. this._canvas = scene.getEngine().getRenderingCanvas();
  104848. // Parse options
  104849. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  104850. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  104851. }
  104852. if (webVROptions.createDeviceOrientationCamera === undefined) {
  104853. webVROptions.createDeviceOrientationCamera = true;
  104854. }
  104855. if (webVROptions.laserToggle === undefined) {
  104856. webVROptions.laserToggle = true;
  104857. }
  104858. if (webVROptions.defaultHeight === undefined) {
  104859. webVROptions.defaultHeight = 1.7;
  104860. }
  104861. if (webVROptions.useCustomVRButton) {
  104862. this._useCustomVRButton = true;
  104863. if (webVROptions.customVRButton) {
  104864. this._btnVR = webVROptions.customVRButton;
  104865. }
  104866. }
  104867. if (webVROptions.rayLength) {
  104868. this._rayLength = webVROptions.rayLength;
  104869. }
  104870. this._defaultHeight = webVROptions.defaultHeight;
  104871. if (webVROptions.positionScale) {
  104872. this._rayLength *= webVROptions.positionScale;
  104873. this._defaultHeight *= webVROptions.positionScale;
  104874. }
  104875. this._hasEnteredVR = false;
  104876. // Set position
  104877. if (this._scene.activeCamera) {
  104878. this._position = this._scene.activeCamera.position.clone();
  104879. }
  104880. else {
  104881. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  104882. }
  104883. // Set non-vr camera
  104884. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  104885. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  104886. // Copy data from existing camera
  104887. if (this._scene.activeCamera) {
  104888. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  104889. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  104890. // Set rotation from previous camera
  104891. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  104892. var targetCamera = this._scene.activeCamera;
  104893. if (targetCamera.rotationQuaternion) {
  104894. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  104895. }
  104896. else {
  104897. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  104898. }
  104899. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  104900. }
  104901. }
  104902. this._scene.activeCamera = this._deviceOrientationCamera;
  104903. if (this._canvas) {
  104904. this._scene.activeCamera.attachControl(this._canvas);
  104905. }
  104906. }
  104907. else {
  104908. this._existingCamera = this._scene.activeCamera;
  104909. }
  104910. // Create VR cameras
  104911. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  104912. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  104913. }
  104914. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  104915. this._webVRCamera.useStandingMatrix();
  104916. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  104917. // Create default button
  104918. if (!this._useCustomVRButton) {
  104919. this._btnVR = document.createElement("BUTTON");
  104920. this._btnVR.className = "babylonVRicon";
  104921. this._btnVR.id = "babylonVRiconbtn";
  104922. this._btnVR.title = "Click to switch to VR";
  104923. 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) }";
  104924. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  104925. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  104926. // css += ".babylonVRicon.vrdisplaysupported { }";
  104927. // css += ".babylonVRicon.vrdisplayready { }";
  104928. // css += ".babylonVRicon.vrdisplayrequesting { }";
  104929. var style = document.createElement('style');
  104930. style.appendChild(document.createTextNode(css));
  104931. document.getElementsByTagName('head')[0].appendChild(style);
  104932. this.moveButtonToBottomRight();
  104933. }
  104934. // VR button click event
  104935. if (this._btnVR) {
  104936. this._btnVR.addEventListener("click", function () {
  104937. if (!_this.isInVRMode) {
  104938. _this.enterVR();
  104939. }
  104940. else {
  104941. _this.exitVR();
  104942. }
  104943. });
  104944. }
  104945. // Window events
  104946. window.addEventListener("resize", this._onResize);
  104947. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  104948. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  104949. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  104950. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  104951. document.onmsfullscreenchange = this._onFullscreenChange;
  104952. // Display vr button when headset is connected
  104953. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  104954. this.displayVRButton();
  104955. }
  104956. else {
  104957. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  104958. if (e.vrDisplay) {
  104959. _this.displayVRButton();
  104960. }
  104961. });
  104962. }
  104963. // Exiting VR mode using 'ESC' key on desktop
  104964. this._onKeyDown = function (event) {
  104965. if (event.keyCode === 27 && _this.isInVRMode) {
  104966. _this.exitVR();
  104967. }
  104968. };
  104969. document.addEventListener("keydown", this._onKeyDown);
  104970. // Exiting VR mode double tapping the touch screen
  104971. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  104972. if (_this.isInVRMode) {
  104973. _this.exitVR();
  104974. if (_this._fullscreenVRpresenting) {
  104975. _this._scene.getEngine().switchFullscreen(true);
  104976. }
  104977. }
  104978. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  104979. // Listen for WebVR display changes
  104980. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  104981. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  104982. this._onVRRequestPresentStart = function () {
  104983. _this._webVRrequesting = true;
  104984. _this.updateButtonVisibility();
  104985. };
  104986. this._onVRRequestPresentComplete = function (success) {
  104987. _this._webVRrequesting = false;
  104988. _this.updateButtonVisibility();
  104989. };
  104990. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  104991. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  104992. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  104993. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  104994. scene.onDisposeObservable.add(function () {
  104995. _this.dispose();
  104996. });
  104997. // Gamepad connection events
  104998. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  104999. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  105000. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  105001. this.updateButtonVisibility();
  105002. //create easing functions
  105003. this._circleEase = new BABYLON.CircleEase();
  105004. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  105005. if (this.webVROptions.floorMeshes) {
  105006. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  105007. }
  105008. }
  105009. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  105010. /** Return this.onEnteringVRObservable
  105011. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  105012. */
  105013. get: function () {
  105014. return this.onEnteringVRObservable;
  105015. },
  105016. enumerable: true,
  105017. configurable: true
  105018. });
  105019. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  105020. /** Return this.onExitingVRObservable
  105021. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  105022. */
  105023. get: function () {
  105024. return this.onExitingVRObservable;
  105025. },
  105026. enumerable: true,
  105027. configurable: true
  105028. });
  105029. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  105030. /** Return this.onControllerMeshLoadedObservable
  105031. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  105032. */
  105033. get: function () {
  105034. return this.onControllerMeshLoadedObservable;
  105035. },
  105036. enumerable: true,
  105037. configurable: true
  105038. });
  105039. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  105040. /**
  105041. * The mesh used to display where the user is going to teleport.
  105042. */
  105043. get: function () {
  105044. return this._teleportationTarget;
  105045. },
  105046. /**
  105047. * Sets the mesh to be used to display where the user is going to teleport.
  105048. */
  105049. set: function (value) {
  105050. if (value) {
  105051. value.name = "teleportationTarget";
  105052. this._isDefaultTeleportationTarget = false;
  105053. this._teleportationTarget = value;
  105054. }
  105055. },
  105056. enumerable: true,
  105057. configurable: true
  105058. });
  105059. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  105060. /**
  105061. * 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
  105062. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  105063. * See http://doc.babylonjs.com/resources/baking_transformations
  105064. */
  105065. get: function () {
  105066. return this._cameraGazer._gazeTracker;
  105067. },
  105068. set: function (value) {
  105069. if (value) {
  105070. // Dispose of existing meshes
  105071. if (this._cameraGazer._gazeTracker) {
  105072. this._cameraGazer._gazeTracker.dispose();
  105073. }
  105074. if (this._leftController && this._leftController._gazeTracker) {
  105075. this._leftController._gazeTracker.dispose();
  105076. }
  105077. if (this._rightController && this._rightController._gazeTracker) {
  105078. this._rightController._gazeTracker.dispose();
  105079. }
  105080. // Set and create gaze trackers on head and controllers
  105081. this._cameraGazer._gazeTracker = value;
  105082. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  105083. this._cameraGazer._gazeTracker.isPickable = false;
  105084. this._cameraGazer._gazeTracker.isVisible = false;
  105085. this._cameraGazer._gazeTracker.name = "gazeTracker";
  105086. if (this._leftController) {
  105087. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  105088. }
  105089. if (this._rightController) {
  105090. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  105091. }
  105092. }
  105093. },
  105094. enumerable: true,
  105095. configurable: true
  105096. });
  105097. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  105098. /**
  105099. * The gaze tracking mesh corresponding to the left controller
  105100. */
  105101. get: function () {
  105102. if (this._leftController) {
  105103. return this._leftController._gazeTracker;
  105104. }
  105105. return null;
  105106. },
  105107. enumerable: true,
  105108. configurable: true
  105109. });
  105110. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  105111. /**
  105112. * The gaze tracking mesh corresponding to the right controller
  105113. */
  105114. get: function () {
  105115. if (this._rightController) {
  105116. return this._rightController._gazeTracker;
  105117. }
  105118. return null;
  105119. },
  105120. enumerable: true,
  105121. configurable: true
  105122. });
  105123. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  105124. /**
  105125. * If the ray of the gaze should be displayed.
  105126. */
  105127. get: function () {
  105128. return this._displayGaze;
  105129. },
  105130. /**
  105131. * Sets if the ray of the gaze should be displayed.
  105132. */
  105133. set: function (value) {
  105134. this._displayGaze = value;
  105135. if (!value) {
  105136. this._cameraGazer._gazeTracker.isVisible = false;
  105137. if (this._leftController) {
  105138. this._leftController._gazeTracker.isVisible = false;
  105139. }
  105140. if (this._rightController) {
  105141. this._rightController._gazeTracker.isVisible = false;
  105142. }
  105143. }
  105144. },
  105145. enumerable: true,
  105146. configurable: true
  105147. });
  105148. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  105149. /**
  105150. * If the ray of the LaserPointer should be displayed.
  105151. */
  105152. get: function () {
  105153. return this._displayLaserPointer;
  105154. },
  105155. /**
  105156. * Sets if the ray of the LaserPointer should be displayed.
  105157. */
  105158. set: function (value) {
  105159. this._displayLaserPointer = value;
  105160. if (!value) {
  105161. if (this._rightController) {
  105162. this._rightController._deactivatePointer();
  105163. this._rightController._gazeTracker.isVisible = false;
  105164. }
  105165. if (this._leftController) {
  105166. this._leftController._deactivatePointer();
  105167. this._leftController._gazeTracker.isVisible = false;
  105168. }
  105169. }
  105170. else {
  105171. if (this._rightController) {
  105172. this._rightController._activatePointer();
  105173. }
  105174. if (this._leftController) {
  105175. this._leftController._activatePointer();
  105176. }
  105177. }
  105178. },
  105179. enumerable: true,
  105180. configurable: true
  105181. });
  105182. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  105183. /**
  105184. * The deviceOrientationCamera used as the camera when not in VR.
  105185. */
  105186. get: function () {
  105187. return this._deviceOrientationCamera;
  105188. },
  105189. enumerable: true,
  105190. configurable: true
  105191. });
  105192. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  105193. /**
  105194. * Based on the current WebVR support, returns the current VR camera used.
  105195. */
  105196. get: function () {
  105197. if (this._webVRready) {
  105198. return this._webVRCamera;
  105199. }
  105200. else {
  105201. return this._scene.activeCamera;
  105202. }
  105203. },
  105204. enumerable: true,
  105205. configurable: true
  105206. });
  105207. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  105208. /**
  105209. * The webVRCamera which is used when in VR.
  105210. */
  105211. get: function () {
  105212. return this._webVRCamera;
  105213. },
  105214. enumerable: true,
  105215. configurable: true
  105216. });
  105217. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  105218. /**
  105219. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  105220. */
  105221. get: function () {
  105222. return this._vrDeviceOrientationCamera;
  105223. },
  105224. enumerable: true,
  105225. configurable: true
  105226. });
  105227. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  105228. get: function () {
  105229. var result = this._cameraGazer._teleportationRequestInitiated
  105230. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  105231. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  105232. return result;
  105233. },
  105234. enumerable: true,
  105235. configurable: true
  105236. });
  105237. // Raised when one of the controller has loaded successfully its associated default mesh
  105238. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  105239. if (this._leftController && this._leftController.webVRController == webVRController) {
  105240. if (webVRController.mesh) {
  105241. this._leftController._setLaserPointerParent(webVRController.mesh);
  105242. }
  105243. }
  105244. if (this._rightController && this._rightController.webVRController == webVRController) {
  105245. if (webVRController.mesh) {
  105246. this._rightController._setLaserPointerParent(webVRController.mesh);
  105247. }
  105248. }
  105249. try {
  105250. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  105251. }
  105252. catch (err) {
  105253. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  105254. }
  105255. };
  105256. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  105257. /**
  105258. * Gets a value indicating if we are currently in VR mode.
  105259. */
  105260. get: function () {
  105261. return this._webVRpresenting || this._fullscreenVRpresenting;
  105262. },
  105263. enumerable: true,
  105264. configurable: true
  105265. });
  105266. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  105267. var vrDisplay = this._scene.getEngine().getVRDevice();
  105268. if (vrDisplay) {
  105269. var wasPresenting = this._webVRpresenting;
  105270. this._webVRpresenting = vrDisplay.isPresenting;
  105271. if (wasPresenting && !this._webVRpresenting) {
  105272. this.exitVR();
  105273. }
  105274. }
  105275. else {
  105276. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  105277. }
  105278. this.updateButtonVisibility();
  105279. };
  105280. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  105281. this._webVRsupported = eventArgs.vrSupported;
  105282. this._webVRready = !!eventArgs.vrDisplay;
  105283. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  105284. this.updateButtonVisibility();
  105285. };
  105286. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  105287. if (this._canvas && !this._useCustomVRButton) {
  105288. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  105289. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  105290. }
  105291. };
  105292. VRExperienceHelper.prototype.displayVRButton = function () {
  105293. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  105294. document.body.appendChild(this._btnVR);
  105295. this._btnVRDisplayed = true;
  105296. }
  105297. };
  105298. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  105299. if (!this._btnVR || this._useCustomVRButton) {
  105300. return;
  105301. }
  105302. this._btnVR.className = "babylonVRicon";
  105303. if (this.isInVRMode) {
  105304. this._btnVR.className += " vrdisplaypresenting";
  105305. }
  105306. else {
  105307. if (this._webVRready) {
  105308. this._btnVR.className += " vrdisplayready";
  105309. }
  105310. if (this._webVRsupported) {
  105311. this._btnVR.className += " vrdisplaysupported";
  105312. }
  105313. if (this._webVRrequesting) {
  105314. this._btnVR.className += " vrdisplayrequesting";
  105315. }
  105316. }
  105317. };
  105318. /**
  105319. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  105320. * Otherwise, will use the fullscreen API.
  105321. */
  105322. VRExperienceHelper.prototype.enterVR = function () {
  105323. if (this.onEnteringVRObservable) {
  105324. try {
  105325. this.onEnteringVRObservable.notifyObservers(this);
  105326. }
  105327. catch (err) {
  105328. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  105329. }
  105330. }
  105331. if (this._scene.activeCamera) {
  105332. this._position = this._scene.activeCamera.position.clone();
  105333. // make sure that we return to the last active camera
  105334. this._existingCamera = this._scene.activeCamera;
  105335. }
  105336. if (this._webVRrequesting) {
  105337. return;
  105338. }
  105339. // If WebVR is supported and a headset is connected
  105340. if (this._webVRready) {
  105341. if (!this._webVRpresenting) {
  105342. this._webVRCamera.position = this._position;
  105343. this._scene.activeCamera = this._webVRCamera;
  105344. }
  105345. }
  105346. else if (this._vrDeviceOrientationCamera) {
  105347. this._vrDeviceOrientationCamera.position = this._position;
  105348. if (this._scene.activeCamera) {
  105349. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  105350. }
  105351. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  105352. this._scene.getEngine().switchFullscreen(true);
  105353. this.updateButtonVisibility();
  105354. }
  105355. if (this._scene.activeCamera && this._canvas) {
  105356. this._scene.activeCamera.attachControl(this._canvas);
  105357. }
  105358. if (this._interactionsEnabled) {
  105359. this._scene.registerBeforeRender(this.beforeRender);
  105360. }
  105361. this._hasEnteredVR = true;
  105362. };
  105363. /**
  105364. * Attempt to exit VR, or fullscreen.
  105365. */
  105366. VRExperienceHelper.prototype.exitVR = function () {
  105367. if (this._hasEnteredVR) {
  105368. if (this.onExitingVRObservable) {
  105369. try {
  105370. this.onExitingVRObservable.notifyObservers(this);
  105371. }
  105372. catch (err) {
  105373. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  105374. }
  105375. }
  105376. if (this._webVRpresenting) {
  105377. this._scene.getEngine().disableVR();
  105378. }
  105379. if (this._scene.activeCamera) {
  105380. this._position = this._scene.activeCamera.position.clone();
  105381. }
  105382. if (this._deviceOrientationCamera) {
  105383. this._deviceOrientationCamera.position = this._position;
  105384. this._scene.activeCamera = this._deviceOrientationCamera;
  105385. if (this._canvas) {
  105386. this._scene.activeCamera.attachControl(this._canvas);
  105387. }
  105388. }
  105389. else if (this._existingCamera) {
  105390. this._existingCamera.position = this._position;
  105391. this._scene.activeCamera = this._existingCamera;
  105392. }
  105393. this.updateButtonVisibility();
  105394. if (this._interactionsEnabled) {
  105395. this._scene.unregisterBeforeRender(this.beforeRender);
  105396. this._cameraGazer._gazeTracker.isVisible = false;
  105397. if (this._leftController) {
  105398. this._leftController._gazeTracker.isVisible = false;
  105399. }
  105400. if (this._rightController) {
  105401. this._rightController._gazeTracker.isVisible = false;
  105402. }
  105403. }
  105404. // resize to update width and height when exiting vr exits fullscreen
  105405. this._scene.getEngine().resize();
  105406. this._hasEnteredVR = false;
  105407. }
  105408. };
  105409. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  105410. /**
  105411. * The position of the vr experience helper.
  105412. */
  105413. get: function () {
  105414. return this._position;
  105415. },
  105416. /**
  105417. * Sets the position of the vr experience helper.
  105418. */
  105419. set: function (value) {
  105420. this._position = value;
  105421. if (this._scene.activeCamera) {
  105422. this._scene.activeCamera.position = value;
  105423. }
  105424. },
  105425. enumerable: true,
  105426. configurable: true
  105427. });
  105428. /**
  105429. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  105430. */
  105431. VRExperienceHelper.prototype.enableInteractions = function () {
  105432. var _this = this;
  105433. if (!this._interactionsEnabled) {
  105434. this._interactionsRequested = true;
  105435. if (this._leftController) {
  105436. this._enableInteractionOnController(this._leftController);
  105437. }
  105438. if (this._rightController) {
  105439. this._enableInteractionOnController(this._rightController);
  105440. }
  105441. this.raySelectionPredicate = function (mesh) {
  105442. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  105443. };
  105444. this.meshSelectionPredicate = function (mesh) {
  105445. return true;
  105446. };
  105447. this._raySelectionPredicate = function (mesh) {
  105448. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  105449. && mesh.name.indexOf("teleportationTarget") === -1
  105450. && mesh.name.indexOf("torusTeleportation") === -1)) {
  105451. return _this.raySelectionPredicate(mesh);
  105452. }
  105453. return false;
  105454. };
  105455. this._interactionsEnabled = true;
  105456. }
  105457. };
  105458. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  105459. get: function () {
  105460. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  105461. },
  105462. enumerable: true,
  105463. configurable: true
  105464. });
  105465. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  105466. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  105467. if (this._floorMeshesCollection[i].id === mesh.id) {
  105468. return true;
  105469. }
  105470. }
  105471. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  105472. return true;
  105473. }
  105474. return false;
  105475. };
  105476. /**
  105477. * Adds a floor mesh to be used for teleportation.
  105478. * @param floorMesh the mesh to be used for teleportation.
  105479. */
  105480. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  105481. if (!this._floorMeshesCollection) {
  105482. return;
  105483. }
  105484. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  105485. return;
  105486. }
  105487. this._floorMeshesCollection.push(floorMesh);
  105488. };
  105489. /**
  105490. * Removes a floor mesh from being used for teleportation.
  105491. * @param floorMesh the mesh to be removed.
  105492. */
  105493. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  105494. if (!this._floorMeshesCollection) {
  105495. return;
  105496. }
  105497. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  105498. if (meshIndex !== -1) {
  105499. this._floorMeshesCollection.splice(meshIndex, 1);
  105500. }
  105501. };
  105502. /**
  105503. * Enables interactions and teleportation using the VR controllers and gaze.
  105504. * @param vrTeleportationOptions options to modify teleportation behavior.
  105505. */
  105506. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  105507. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  105508. if (!this._teleportationInitialized) {
  105509. this._teleportationRequested = true;
  105510. this.enableInteractions();
  105511. if (vrTeleportationOptions.floorMeshName) {
  105512. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  105513. }
  105514. if (vrTeleportationOptions.floorMeshes) {
  105515. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  105516. }
  105517. if (this._leftController != null) {
  105518. this._enableTeleportationOnController(this._leftController);
  105519. }
  105520. if (this._rightController != null) {
  105521. this._enableTeleportationOnController(this._rightController);
  105522. }
  105523. // Creates an image processing post process for the vignette not relying
  105524. // on the main scene configuration for image processing to reduce setup and spaces
  105525. // (gamma/linear) conflicts.
  105526. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  105527. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  105528. imageProcessingConfiguration.vignetteEnabled = true;
  105529. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  105530. this._webVRCamera.detachPostProcess(this._postProcessMove);
  105531. this._teleportationInitialized = true;
  105532. if (this._isDefaultTeleportationTarget) {
  105533. this._createTeleportationCircles();
  105534. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  105535. }
  105536. }
  105537. };
  105538. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  105539. var _this = this;
  105540. var controllerMesh = controller.webVRController.mesh;
  105541. if (controllerMesh) {
  105542. controller._interactionsEnabled = true;
  105543. controller._activatePointer();
  105544. if (this.webVROptions.laserToggle) {
  105545. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  105546. // Enabling / disabling laserPointer
  105547. if (_this._displayLaserPointer && stateObject.value === 1) {
  105548. if (controller._activePointer) {
  105549. controller._deactivatePointer();
  105550. }
  105551. else {
  105552. controller._activatePointer();
  105553. }
  105554. if (_this.displayGaze) {
  105555. controller._gazeTracker.isVisible = controller._activePointer;
  105556. }
  105557. }
  105558. });
  105559. }
  105560. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  105561. var gazer = controller;
  105562. if (_this._noControllerIsActive) {
  105563. gazer = _this._cameraGazer;
  105564. }
  105565. if (!gazer._pointerDownOnMeshAsked) {
  105566. if (stateObject.value > _this._padSensibilityUp) {
  105567. gazer._selectionPointerDown();
  105568. }
  105569. }
  105570. else if (stateObject.value < _this._padSensibilityDown) {
  105571. gazer._selectionPointerUp();
  105572. }
  105573. });
  105574. }
  105575. };
  105576. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  105577. // Dont teleport if another gaze already requested teleportation
  105578. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  105579. return;
  105580. }
  105581. if (!gazer._teleportationRequestInitiated) {
  105582. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  105583. gazer._activatePointer();
  105584. gazer._teleportationRequestInitiated = true;
  105585. }
  105586. }
  105587. else {
  105588. // Listening to the proper controller values changes to confirm teleportation
  105589. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  105590. if (this._teleportActive) {
  105591. this.teleportCamera(this._haloCenter);
  105592. }
  105593. gazer._teleportationRequestInitiated = false;
  105594. }
  105595. }
  105596. };
  105597. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  105598. // Only rotate when user is not currently selecting a teleportation location
  105599. if (gazer._teleportationRequestInitiated) {
  105600. return;
  105601. }
  105602. if (!gazer._rotationLeftAsked) {
  105603. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  105604. gazer._rotationLeftAsked = true;
  105605. if (this._rotationAllowed) {
  105606. this._rotateCamera(false);
  105607. }
  105608. }
  105609. }
  105610. else {
  105611. if (stateObject.x > -this._padSensibilityDown) {
  105612. gazer._rotationLeftAsked = false;
  105613. }
  105614. }
  105615. if (!gazer._rotationRightAsked) {
  105616. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  105617. gazer._rotationRightAsked = true;
  105618. if (this._rotationAllowed) {
  105619. this._rotateCamera(true);
  105620. }
  105621. }
  105622. }
  105623. else {
  105624. if (stateObject.x < this._padSensibilityDown) {
  105625. gazer._rotationRightAsked = false;
  105626. }
  105627. }
  105628. };
  105629. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  105630. // Only teleport backwards when user is not currently selecting a teleportation location
  105631. if (gazer._teleportationRequestInitiated) {
  105632. return;
  105633. }
  105634. // Teleport backwards
  105635. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  105636. if (!gazer._teleportationBackRequestInitiated) {
  105637. if (!this.currentVRCamera) {
  105638. return;
  105639. }
  105640. // Get rotation and position of the current camera
  105641. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  105642. var position = this.currentVRCamera.position;
  105643. // If the camera has device position, use that instead
  105644. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  105645. rotation = this.currentVRCamera.deviceRotationQuaternion;
  105646. position = this.currentVRCamera.devicePosition;
  105647. }
  105648. // Get matrix with only the y rotation of the device rotation
  105649. rotation.toEulerAnglesToRef(this._workingVector);
  105650. this._workingVector.z = 0;
  105651. this._workingVector.x = 0;
  105652. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  105653. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  105654. // Rotate backwards ray by device rotation to cast at the ground behind the user
  105655. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  105656. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  105657. var ray = new BABYLON.Ray(position, this._workingVector);
  105658. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  105659. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  105660. this.teleportCamera(hit.pickedPoint);
  105661. }
  105662. gazer._teleportationBackRequestInitiated = true;
  105663. }
  105664. }
  105665. else {
  105666. gazer._teleportationBackRequestInitiated = false;
  105667. }
  105668. };
  105669. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  105670. var _this = this;
  105671. var controllerMesh = controller.webVRController.mesh;
  105672. if (controllerMesh) {
  105673. if (!controller._interactionsEnabled) {
  105674. this._enableInteractionOnController(controller);
  105675. }
  105676. controller._interactionsEnabled = true;
  105677. controller._teleportationEnabled = true;
  105678. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  105679. controller._dpadPressed = false;
  105680. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  105681. controller._dpadPressed = stateObject.pressed;
  105682. if (!controller._dpadPressed) {
  105683. controller._rotationLeftAsked = false;
  105684. controller._rotationRightAsked = false;
  105685. controller._teleportationBackRequestInitiated = false;
  105686. }
  105687. });
  105688. }
  105689. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  105690. if (_this.teleportationEnabled) {
  105691. _this._checkTeleportBackwards(stateObject, controller);
  105692. _this._checkTeleportWithRay(stateObject, controller);
  105693. }
  105694. _this._checkRotate(stateObject, controller);
  105695. });
  105696. }
  105697. };
  105698. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  105699. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  105700. this._teleportationTarget.isPickable = false;
  105701. var length = 512;
  105702. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  105703. dynamicTexture.hasAlpha = true;
  105704. var context = dynamicTexture.getContext();
  105705. var centerX = length / 2;
  105706. var centerY = length / 2;
  105707. var radius = 200;
  105708. context.beginPath();
  105709. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  105710. context.fillStyle = this._teleportationFillColor;
  105711. context.fill();
  105712. context.lineWidth = 10;
  105713. context.strokeStyle = this._teleportationBorderColor;
  105714. context.stroke();
  105715. context.closePath();
  105716. dynamicTexture.update();
  105717. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  105718. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  105719. this._teleportationTarget.material = teleportationCircleMaterial;
  105720. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  105721. torus.isPickable = false;
  105722. torus.parent = this._teleportationTarget;
  105723. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  105724. var keys = [];
  105725. keys.push({
  105726. frame: 0,
  105727. value: 0
  105728. });
  105729. keys.push({
  105730. frame: 30,
  105731. value: 0.4
  105732. });
  105733. keys.push({
  105734. frame: 60,
  105735. value: 0
  105736. });
  105737. animationInnerCircle.setKeys(keys);
  105738. var easingFunction = new BABYLON.SineEase();
  105739. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  105740. animationInnerCircle.setEasingFunction(easingFunction);
  105741. torus.animations = [];
  105742. torus.animations.push(animationInnerCircle);
  105743. this._scene.beginAnimation(torus, 0, 60, true);
  105744. this._hideTeleportationTarget();
  105745. };
  105746. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  105747. this._teleportActive = true;
  105748. if (this._teleportationInitialized) {
  105749. this._teleportationTarget.isVisible = true;
  105750. if (this._isDefaultTeleportationTarget) {
  105751. this._teleportationTarget.getChildren()[0].isVisible = true;
  105752. }
  105753. }
  105754. };
  105755. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  105756. this._teleportActive = false;
  105757. if (this._teleportationInitialized) {
  105758. this._teleportationTarget.isVisible = false;
  105759. if (this._isDefaultTeleportationTarget) {
  105760. this._teleportationTarget.getChildren()[0].isVisible = false;
  105761. }
  105762. }
  105763. };
  105764. VRExperienceHelper.prototype._rotateCamera = function (right) {
  105765. var _this = this;
  105766. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  105767. return;
  105768. }
  105769. if (right) {
  105770. this._rotationAngle++;
  105771. }
  105772. else {
  105773. this._rotationAngle--;
  105774. }
  105775. this.currentVRCamera.animations = [];
  105776. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  105777. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105778. var animationRotationKeys = [];
  105779. animationRotationKeys.push({
  105780. frame: 0,
  105781. value: this.currentVRCamera.rotationQuaternion
  105782. });
  105783. animationRotationKeys.push({
  105784. frame: 6,
  105785. value: target
  105786. });
  105787. animationRotation.setKeys(animationRotationKeys);
  105788. animationRotation.setEasingFunction(this._circleEase);
  105789. this.currentVRCamera.animations.push(animationRotation);
  105790. this._postProcessMove.animations = [];
  105791. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105792. var vignetteWeightKeys = [];
  105793. vignetteWeightKeys.push({
  105794. frame: 0,
  105795. value: 0
  105796. });
  105797. vignetteWeightKeys.push({
  105798. frame: 3,
  105799. value: 4
  105800. });
  105801. vignetteWeightKeys.push({
  105802. frame: 6,
  105803. value: 0
  105804. });
  105805. animationPP.setKeys(vignetteWeightKeys);
  105806. animationPP.setEasingFunction(this._circleEase);
  105807. this._postProcessMove.animations.push(animationPP);
  105808. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105809. var vignetteStretchKeys = [];
  105810. vignetteStretchKeys.push({
  105811. frame: 0,
  105812. value: 0
  105813. });
  105814. vignetteStretchKeys.push({
  105815. frame: 3,
  105816. value: 10
  105817. });
  105818. vignetteStretchKeys.push({
  105819. frame: 6,
  105820. value: 0
  105821. });
  105822. animationPP2.setKeys(vignetteStretchKeys);
  105823. animationPP2.setEasingFunction(this._circleEase);
  105824. this._postProcessMove.animations.push(animationPP2);
  105825. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  105826. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  105827. this._postProcessMove.samples = 4;
  105828. this._webVRCamera.attachPostProcess(this._postProcessMove);
  105829. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  105830. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  105831. });
  105832. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  105833. };
  105834. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  105835. if (hit.pickedPoint) {
  105836. if (gazer._teleportationRequestInitiated) {
  105837. this._displayTeleportationTarget();
  105838. this._haloCenter.copyFrom(hit.pickedPoint);
  105839. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  105840. }
  105841. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  105842. if (pickNormal) {
  105843. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  105844. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  105845. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  105846. }
  105847. this._teleportationTarget.position.y += 0.1;
  105848. }
  105849. };
  105850. /**
  105851. * Teleports the users feet to the desired location
  105852. * @param location The location where the user's feet should be placed
  105853. */
  105854. VRExperienceHelper.prototype.teleportCamera = function (location) {
  105855. var _this = this;
  105856. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  105857. return;
  105858. }
  105859. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  105860. // offset of the headset from the anchor.
  105861. if (this.webVRCamera.leftCamera) {
  105862. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  105863. this._workingVector.subtractInPlace(this.webVRCamera.position);
  105864. location.subtractToRef(this._workingVector, this._workingVector);
  105865. }
  105866. else {
  105867. this._workingVector.copyFrom(location);
  105868. }
  105869. // Add height to account for user's height offset
  105870. if (this.isInVRMode) {
  105871. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  105872. }
  105873. else {
  105874. this._workingVector.y += this._defaultHeight;
  105875. }
  105876. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  105877. // Create animation from the camera's position to the new location
  105878. this.currentVRCamera.animations = [];
  105879. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105880. var animationCameraTeleportationKeys = [{
  105881. frame: 0,
  105882. value: this.currentVRCamera.position
  105883. },
  105884. {
  105885. frame: 11,
  105886. value: this._workingVector
  105887. }
  105888. ];
  105889. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  105890. animationCameraTeleportation.setEasingFunction(this._circleEase);
  105891. this.currentVRCamera.animations.push(animationCameraTeleportation);
  105892. this._postProcessMove.animations = [];
  105893. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105894. var vignetteWeightKeys = [];
  105895. vignetteWeightKeys.push({
  105896. frame: 0,
  105897. value: 0
  105898. });
  105899. vignetteWeightKeys.push({
  105900. frame: 5,
  105901. value: 8
  105902. });
  105903. vignetteWeightKeys.push({
  105904. frame: 11,
  105905. value: 0
  105906. });
  105907. animationPP.setKeys(vignetteWeightKeys);
  105908. this._postProcessMove.animations.push(animationPP);
  105909. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105910. var vignetteStretchKeys = [];
  105911. vignetteStretchKeys.push({
  105912. frame: 0,
  105913. value: 0
  105914. });
  105915. vignetteStretchKeys.push({
  105916. frame: 5,
  105917. value: 10
  105918. });
  105919. vignetteStretchKeys.push({
  105920. frame: 11,
  105921. value: 0
  105922. });
  105923. animationPP2.setKeys(vignetteStretchKeys);
  105924. this._postProcessMove.animations.push(animationPP2);
  105925. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  105926. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  105927. this._webVRCamera.attachPostProcess(this._postProcessMove);
  105928. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  105929. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  105930. });
  105931. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  105932. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  105933. });
  105934. this._hideTeleportationTarget();
  105935. };
  105936. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  105937. if (normal) {
  105938. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  105939. if (angle < Math.PI / 2) {
  105940. normal.scaleInPlace(-1);
  105941. }
  105942. }
  105943. return normal;
  105944. };
  105945. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  105946. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  105947. return;
  105948. }
  105949. var ray = gazer._getForwardRay(this._rayLength);
  105950. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  105951. if (hit) {
  105952. // Populate the contrllers mesh that can be used for drag/drop
  105953. if (gazer._laserPointer) {
  105954. hit.originMesh = gazer._laserPointer.parent;
  105955. }
  105956. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  105957. }
  105958. gazer._currentHit = hit;
  105959. // Moving the gazeTracker on the mesh face targetted
  105960. if (hit && hit.pickedPoint) {
  105961. if (this._displayGaze) {
  105962. var multiplier = 1;
  105963. gazer._gazeTracker.isVisible = true;
  105964. if (gazer._isActionableMesh) {
  105965. multiplier = 3;
  105966. }
  105967. if (this.updateGazeTrackerScale) {
  105968. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  105969. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  105970. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  105971. }
  105972. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  105973. // To avoid z-fighting
  105974. var deltaFighting = 0.002;
  105975. if (pickNormal) {
  105976. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  105977. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  105978. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  105979. }
  105980. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  105981. if (gazer._gazeTracker.position.x < 0) {
  105982. gazer._gazeTracker.position.x += deltaFighting;
  105983. }
  105984. else {
  105985. gazer._gazeTracker.position.x -= deltaFighting;
  105986. }
  105987. if (gazer._gazeTracker.position.y < 0) {
  105988. gazer._gazeTracker.position.y += deltaFighting;
  105989. }
  105990. else {
  105991. gazer._gazeTracker.position.y -= deltaFighting;
  105992. }
  105993. if (gazer._gazeTracker.position.z < 0) {
  105994. gazer._gazeTracker.position.z += deltaFighting;
  105995. }
  105996. else {
  105997. gazer._gazeTracker.position.z -= deltaFighting;
  105998. }
  105999. }
  106000. // Changing the size of the laser pointer based on the distance from the targetted point
  106001. gazer._updatePointerDistance(hit.distance);
  106002. }
  106003. else {
  106004. gazer._updatePointerDistance();
  106005. gazer._gazeTracker.isVisible = false;
  106006. }
  106007. if (hit && hit.pickedMesh) {
  106008. // The object selected is the floor, we're in a teleportation scenario
  106009. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  106010. // Moving the teleportation area to this targetted point
  106011. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  106012. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  106013. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  106014. }
  106015. gazer._currentMeshSelected = null;
  106016. if (gazer._teleportationRequestInitiated) {
  106017. this._moveTeleportationSelectorTo(hit, gazer, ray);
  106018. }
  106019. return;
  106020. }
  106021. // If not, we're in a selection scenario
  106022. //this._teleportationAllowed = false;
  106023. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  106024. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  106025. this.onNewMeshPicked.notifyObservers(hit);
  106026. gazer._currentMeshSelected = hit.pickedMesh;
  106027. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  106028. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  106029. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  106030. gazer._isActionableMesh = true;
  106031. }
  106032. else {
  106033. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  106034. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  106035. gazer._isActionableMesh = false;
  106036. }
  106037. try {
  106038. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  106039. }
  106040. catch (err) {
  106041. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  106042. }
  106043. }
  106044. else {
  106045. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  106046. gazer._currentMeshSelected = null;
  106047. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  106048. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  106049. }
  106050. }
  106051. }
  106052. else {
  106053. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  106054. gazer._currentMeshSelected = null;
  106055. //this._teleportationAllowed = false;
  106056. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  106057. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  106058. }
  106059. };
  106060. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  106061. if (mesh) {
  106062. this.onSelectedMeshUnselected.notifyObservers(mesh);
  106063. }
  106064. };
  106065. /**
  106066. * Sets the color of the laser ray from the vr controllers.
  106067. * @param color new color for the ray.
  106068. */
  106069. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  106070. if (this._leftController) {
  106071. this._leftController._setLaserPointerColor(color);
  106072. }
  106073. if (this._rightController) {
  106074. this._rightController._setLaserPointerColor(color);
  106075. }
  106076. };
  106077. /**
  106078. * Sets the color of the ray from the vr headsets gaze.
  106079. * @param color new color for the ray.
  106080. */
  106081. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  106082. if (!this._cameraGazer._gazeTracker.material) {
  106083. return;
  106084. }
  106085. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  106086. if (this._leftController) {
  106087. this._leftController._gazeTracker.material.emissiveColor = color;
  106088. }
  106089. if (this._rightController) {
  106090. this._rightController._gazeTracker.material.emissiveColor = color;
  106091. }
  106092. };
  106093. /**
  106094. * Exits VR and disposes of the vr experience helper
  106095. */
  106096. VRExperienceHelper.prototype.dispose = function () {
  106097. if (this.isInVRMode) {
  106098. this.exitVR();
  106099. }
  106100. if (this._postProcessMove) {
  106101. this._postProcessMove.dispose();
  106102. }
  106103. if (this._webVRCamera) {
  106104. this._webVRCamera.dispose();
  106105. }
  106106. if (this._vrDeviceOrientationCamera) {
  106107. this._vrDeviceOrientationCamera.dispose();
  106108. }
  106109. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  106110. document.body.removeChild(this._btnVR);
  106111. }
  106112. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  106113. this._deviceOrientationCamera.dispose();
  106114. }
  106115. if (this._cameraGazer) {
  106116. this._cameraGazer.dispose();
  106117. }
  106118. if (this._leftController) {
  106119. this._leftController.dispose();
  106120. }
  106121. if (this._rightController) {
  106122. this._rightController.dispose();
  106123. }
  106124. if (this._teleportationTarget) {
  106125. this._teleportationTarget.dispose();
  106126. }
  106127. this._floorMeshesCollection = [];
  106128. document.removeEventListener("keydown", this._onKeyDown);
  106129. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  106130. window.removeEventListener("resize", this._onResize);
  106131. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  106132. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  106133. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  106134. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  106135. document.onmsfullscreenchange = null;
  106136. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  106137. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  106138. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  106139. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  106140. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  106141. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  106142. this._scene.unregisterBeforeRender(this.beforeRender);
  106143. };
  106144. /**
  106145. * Gets the name of the VRExperienceHelper class
  106146. * @returns "VRExperienceHelper"
  106147. */
  106148. VRExperienceHelper.prototype.getClassName = function () {
  106149. return "VRExperienceHelper";
  106150. };
  106151. return VRExperienceHelper;
  106152. }());
  106153. BABYLON.VRExperienceHelper = VRExperienceHelper;
  106154. })(BABYLON || (BABYLON = {}));
  106155. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  106156. // Mainly based on these 2 articles :
  106157. // 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
  106158. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  106159. var BABYLON;
  106160. (function (BABYLON) {
  106161. /**
  106162. * Defines the potential axis of a Joystick
  106163. */
  106164. var JoystickAxis;
  106165. (function (JoystickAxis) {
  106166. /** X axis */
  106167. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  106168. /** Y axis */
  106169. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  106170. /** Z axis */
  106171. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  106172. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  106173. /**
  106174. * Class used to define virtual joystick (used in touch mode)
  106175. */
  106176. var VirtualJoystick = /** @class */ (function () {
  106177. /**
  106178. * Creates a new virtual joystick
  106179. * @param leftJoystick defines that the joystick is for left hand (false by default)
  106180. */
  106181. function VirtualJoystick(leftJoystick) {
  106182. var _this = this;
  106183. if (leftJoystick) {
  106184. this._leftJoystick = true;
  106185. }
  106186. else {
  106187. this._leftJoystick = false;
  106188. }
  106189. VirtualJoystick._globalJoystickIndex++;
  106190. // By default left & right arrow keys are moving the X
  106191. // and up & down keys are moving the Y
  106192. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  106193. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  106194. this.reverseLeftRight = false;
  106195. this.reverseUpDown = false;
  106196. // collections of pointers
  106197. this._touches = new BABYLON.StringDictionary();
  106198. this.deltaPosition = BABYLON.Vector3.Zero();
  106199. this._joystickSensibility = 25;
  106200. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  106201. this._onResize = function (evt) {
  106202. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  106203. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  106204. if (VirtualJoystick.vjCanvas) {
  106205. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  106206. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  106207. }
  106208. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  106209. };
  106210. // injecting a canvas element on top of the canvas 3D game
  106211. if (!VirtualJoystick.vjCanvas) {
  106212. window.addEventListener("resize", this._onResize, false);
  106213. VirtualJoystick.vjCanvas = document.createElement("canvas");
  106214. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  106215. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  106216. VirtualJoystick.vjCanvas.width = window.innerWidth;
  106217. VirtualJoystick.vjCanvas.height = window.innerHeight;
  106218. VirtualJoystick.vjCanvas.style.width = "100%";
  106219. VirtualJoystick.vjCanvas.style.height = "100%";
  106220. VirtualJoystick.vjCanvas.style.position = "absolute";
  106221. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  106222. VirtualJoystick.vjCanvas.style.top = "0px";
  106223. VirtualJoystick.vjCanvas.style.left = "0px";
  106224. VirtualJoystick.vjCanvas.style.zIndex = "5";
  106225. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  106226. // Support for jQuery PEP polyfill
  106227. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  106228. var context = VirtualJoystick.vjCanvas.getContext('2d');
  106229. if (!context) {
  106230. throw new Error("Unable to create canvas for virtual joystick");
  106231. }
  106232. VirtualJoystick.vjCanvasContext = context;
  106233. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  106234. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  106235. document.body.appendChild(VirtualJoystick.vjCanvas);
  106236. }
  106237. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  106238. this.pressed = false;
  106239. // default joystick color
  106240. this._joystickColor = "cyan";
  106241. this._joystickPointerID = -1;
  106242. // current joystick position
  106243. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  106244. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  106245. // origin joystick position
  106246. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  106247. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  106248. this._onPointerDownHandlerRef = function (evt) {
  106249. _this._onPointerDown(evt);
  106250. };
  106251. this._onPointerMoveHandlerRef = function (evt) {
  106252. _this._onPointerMove(evt);
  106253. };
  106254. this._onPointerUpHandlerRef = function (evt) {
  106255. _this._onPointerUp(evt);
  106256. };
  106257. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  106258. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  106259. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  106260. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  106261. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  106262. evt.preventDefault(); // Disables system menu
  106263. }, false);
  106264. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  106265. }
  106266. /**
  106267. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  106268. * @param newJoystickSensibility defines the new sensibility
  106269. */
  106270. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  106271. this._joystickSensibility = newJoystickSensibility;
  106272. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  106273. };
  106274. VirtualJoystick.prototype._onPointerDown = function (e) {
  106275. var positionOnScreenCondition;
  106276. e.preventDefault();
  106277. if (this._leftJoystick === true) {
  106278. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  106279. }
  106280. else {
  106281. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  106282. }
  106283. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  106284. // First contact will be dedicated to the virtual joystick
  106285. this._joystickPointerID = e.pointerId;
  106286. this._joystickPointerStartPos.x = e.clientX;
  106287. this._joystickPointerStartPos.y = e.clientY;
  106288. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  106289. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  106290. this._deltaJoystickVector.x = 0;
  106291. this._deltaJoystickVector.y = 0;
  106292. this.pressed = true;
  106293. this._touches.add(e.pointerId.toString(), e);
  106294. }
  106295. else {
  106296. // You can only trigger the action buttons with a joystick declared
  106297. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  106298. this._action();
  106299. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  106300. }
  106301. }
  106302. };
  106303. VirtualJoystick.prototype._onPointerMove = function (e) {
  106304. // If the current pointer is the one associated to the joystick (first touch contact)
  106305. if (this._joystickPointerID == e.pointerId) {
  106306. this._joystickPointerPos.x = e.clientX;
  106307. this._joystickPointerPos.y = e.clientY;
  106308. this._deltaJoystickVector = this._joystickPointerPos.clone();
  106309. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  106310. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  106311. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  106312. switch (this._axisTargetedByLeftAndRight) {
  106313. case JoystickAxis.X:
  106314. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  106315. break;
  106316. case JoystickAxis.Y:
  106317. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  106318. break;
  106319. case JoystickAxis.Z:
  106320. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  106321. break;
  106322. }
  106323. var directionUpDown = this.reverseUpDown ? 1 : -1;
  106324. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  106325. switch (this._axisTargetedByUpAndDown) {
  106326. case JoystickAxis.X:
  106327. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  106328. break;
  106329. case JoystickAxis.Y:
  106330. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  106331. break;
  106332. case JoystickAxis.Z:
  106333. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  106334. break;
  106335. }
  106336. }
  106337. else {
  106338. var data = this._touches.get(e.pointerId.toString());
  106339. if (data) {
  106340. data.x = e.clientX;
  106341. data.y = e.clientY;
  106342. }
  106343. }
  106344. };
  106345. VirtualJoystick.prototype._onPointerUp = function (e) {
  106346. if (this._joystickPointerID == e.pointerId) {
  106347. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  106348. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  106349. this._joystickPointerID = -1;
  106350. this.pressed = false;
  106351. }
  106352. else {
  106353. var touch = this._touches.get(e.pointerId.toString());
  106354. if (touch) {
  106355. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  106356. }
  106357. }
  106358. this._deltaJoystickVector.x = 0;
  106359. this._deltaJoystickVector.y = 0;
  106360. this._touches.remove(e.pointerId.toString());
  106361. };
  106362. /**
  106363. * Change the color of the virtual joystick
  106364. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  106365. */
  106366. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  106367. this._joystickColor = newColor;
  106368. };
  106369. /**
  106370. * Defines a callback to call when the joystick is touched
  106371. * @param action defines the callback
  106372. */
  106373. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  106374. this._action = action;
  106375. };
  106376. /**
  106377. * Defines which axis you'd like to control for left & right
  106378. * @param axis defines the axis to use
  106379. */
  106380. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  106381. switch (axis) {
  106382. case JoystickAxis.X:
  106383. case JoystickAxis.Y:
  106384. case JoystickAxis.Z:
  106385. this._axisTargetedByLeftAndRight = axis;
  106386. break;
  106387. default:
  106388. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  106389. break;
  106390. }
  106391. };
  106392. /**
  106393. * Defines which axis you'd like to control for up & down
  106394. * @param axis defines the axis to use
  106395. */
  106396. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  106397. switch (axis) {
  106398. case JoystickAxis.X:
  106399. case JoystickAxis.Y:
  106400. case JoystickAxis.Z:
  106401. this._axisTargetedByUpAndDown = axis;
  106402. break;
  106403. default:
  106404. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  106405. break;
  106406. }
  106407. };
  106408. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  106409. var _this = this;
  106410. if (this.pressed) {
  106411. this._touches.forEach(function (key, touch) {
  106412. if (touch.pointerId === _this._joystickPointerID) {
  106413. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  106414. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  106415. VirtualJoystick.vjCanvasContext.beginPath();
  106416. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  106417. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  106418. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  106419. VirtualJoystick.vjCanvasContext.stroke();
  106420. VirtualJoystick.vjCanvasContext.closePath();
  106421. VirtualJoystick.vjCanvasContext.beginPath();
  106422. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  106423. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  106424. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  106425. VirtualJoystick.vjCanvasContext.stroke();
  106426. VirtualJoystick.vjCanvasContext.closePath();
  106427. VirtualJoystick.vjCanvasContext.beginPath();
  106428. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  106429. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  106430. VirtualJoystick.vjCanvasContext.stroke();
  106431. VirtualJoystick.vjCanvasContext.closePath();
  106432. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  106433. }
  106434. else {
  106435. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  106436. VirtualJoystick.vjCanvasContext.beginPath();
  106437. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  106438. VirtualJoystick.vjCanvasContext.beginPath();
  106439. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  106440. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  106441. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  106442. VirtualJoystick.vjCanvasContext.stroke();
  106443. VirtualJoystick.vjCanvasContext.closePath();
  106444. touch.prevX = touch.x;
  106445. touch.prevY = touch.y;
  106446. }
  106447. });
  106448. }
  106449. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  106450. };
  106451. /**
  106452. * Release internal HTML canvas
  106453. */
  106454. VirtualJoystick.prototype.releaseCanvas = function () {
  106455. if (VirtualJoystick.vjCanvas) {
  106456. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  106457. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  106458. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  106459. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  106460. window.removeEventListener("resize", this._onResize);
  106461. document.body.removeChild(VirtualJoystick.vjCanvas);
  106462. VirtualJoystick.vjCanvas = null;
  106463. }
  106464. };
  106465. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  106466. VirtualJoystick._globalJoystickIndex = 0;
  106467. return VirtualJoystick;
  106468. }());
  106469. BABYLON.VirtualJoystick = VirtualJoystick;
  106470. })(BABYLON || (BABYLON = {}));
  106471. //# sourceMappingURL=babylon.virtualJoystick.js.map
  106472. var BABYLON;
  106473. (function (BABYLON) {
  106474. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  106475. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  106476. });
  106477. /**
  106478. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  106479. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  106480. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  106481. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  106482. */
  106483. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  106484. __extends(VirtualJoysticksCamera, _super);
  106485. /**
  106486. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  106487. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  106488. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  106489. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  106490. * @param name Define the name of the camera in the scene
  106491. * @param position Define the start position of the camera in the scene
  106492. * @param scene Define the scene the camera belongs to
  106493. */
  106494. function VirtualJoysticksCamera(name, position, scene) {
  106495. var _this = _super.call(this, name, position, scene) || this;
  106496. _this.inputs.addVirtualJoystick();
  106497. return _this;
  106498. }
  106499. /**
  106500. * Gets the current object class name.
  106501. * @return the class name
  106502. */
  106503. VirtualJoysticksCamera.prototype.getClassName = function () {
  106504. return "VirtualJoysticksCamera";
  106505. };
  106506. return VirtualJoysticksCamera;
  106507. }(BABYLON.FreeCamera));
  106508. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  106509. })(BABYLON || (BABYLON = {}));
  106510. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  106511. var BABYLON;
  106512. (function (BABYLON) {
  106513. /**
  106514. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  106515. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  106516. */
  106517. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  106518. function FreeCameraVirtualJoystickInput() {
  106519. }
  106520. /**
  106521. * Gets the left stick of the virtual joystick.
  106522. * @returns The virtual Joystick
  106523. */
  106524. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  106525. return this._leftjoystick;
  106526. };
  106527. /**
  106528. * Gets the right stick of the virtual joystick.
  106529. * @returns The virtual Joystick
  106530. */
  106531. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  106532. return this._rightjoystick;
  106533. };
  106534. /**
  106535. * Update the current camera state depending on the inputs that have been used this frame.
  106536. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  106537. */
  106538. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  106539. if (this._leftjoystick) {
  106540. var camera = this.camera;
  106541. var speed = camera._computeLocalCameraSpeed() * 50;
  106542. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  106543. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  106544. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  106545. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  106546. if (!this._leftjoystick.pressed) {
  106547. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  106548. }
  106549. if (!this._rightjoystick.pressed) {
  106550. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  106551. }
  106552. }
  106553. };
  106554. /**
  106555. * Attach the input controls to a specific dom element to get the input from.
  106556. * @param element Defines the element the controls should be listened from
  106557. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  106558. */
  106559. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  106560. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  106561. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  106562. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  106563. this._leftjoystick.setJoystickSensibility(0.15);
  106564. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  106565. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  106566. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  106567. this._rightjoystick.reverseUpDown = true;
  106568. this._rightjoystick.setJoystickSensibility(0.05);
  106569. this._rightjoystick.setJoystickColor("yellow");
  106570. };
  106571. /**
  106572. * Detach the current controls from the specified dom element.
  106573. * @param element Defines the element to stop listening the inputs from
  106574. */
  106575. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  106576. this._leftjoystick.releaseCanvas();
  106577. this._rightjoystick.releaseCanvas();
  106578. };
  106579. /**
  106580. * Gets the class name of the current intput.
  106581. * @returns the class name
  106582. */
  106583. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  106584. return "FreeCameraVirtualJoystickInput";
  106585. };
  106586. /**
  106587. * Get the friendly name associated with the input class.
  106588. * @returns the input friendly name
  106589. */
  106590. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  106591. return "virtualJoystick";
  106592. };
  106593. return FreeCameraVirtualJoystickInput;
  106594. }());
  106595. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  106596. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  106597. })(BABYLON || (BABYLON = {}));
  106598. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  106599. var BABYLON;
  106600. (function (BABYLON) {
  106601. /**
  106602. * Class used to specify simplification options
  106603. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106604. */
  106605. var SimplificationSettings = /** @class */ (function () {
  106606. /**
  106607. * Creates a SimplificationSettings
  106608. * @param quality expected quality
  106609. * @param distance distance when this optimized version should be used
  106610. * @param optimizeMesh already optimized mesh
  106611. */
  106612. function SimplificationSettings(
  106613. /** expected quality */
  106614. quality,
  106615. /** distance when this optimized version should be used */
  106616. distance,
  106617. /** already optimized mesh */
  106618. optimizeMesh) {
  106619. this.quality = quality;
  106620. this.distance = distance;
  106621. this.optimizeMesh = optimizeMesh;
  106622. }
  106623. return SimplificationSettings;
  106624. }());
  106625. BABYLON.SimplificationSettings = SimplificationSettings;
  106626. /**
  106627. * Queue used to order the simplification tasks
  106628. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106629. */
  106630. var SimplificationQueue = /** @class */ (function () {
  106631. /**
  106632. * Creates a new queue
  106633. */
  106634. function SimplificationQueue() {
  106635. this.running = false;
  106636. this._simplificationArray = [];
  106637. }
  106638. /**
  106639. * Adds a new simplification task
  106640. * @param task defines a task to add
  106641. */
  106642. SimplificationQueue.prototype.addTask = function (task) {
  106643. this._simplificationArray.push(task);
  106644. };
  106645. /**
  106646. * Execute next task
  106647. */
  106648. SimplificationQueue.prototype.executeNext = function () {
  106649. var task = this._simplificationArray.pop();
  106650. if (task) {
  106651. this.running = true;
  106652. this.runSimplification(task);
  106653. }
  106654. else {
  106655. this.running = false;
  106656. }
  106657. };
  106658. /**
  106659. * Execute a simplification task
  106660. * @param task defines the task to run
  106661. */
  106662. SimplificationQueue.prototype.runSimplification = function (task) {
  106663. var _this = this;
  106664. if (task.parallelProcessing) {
  106665. //parallel simplifier
  106666. task.settings.forEach(function (setting) {
  106667. var simplifier = _this.getSimplifier(task);
  106668. simplifier.simplify(setting, function (newMesh) {
  106669. task.mesh.addLODLevel(setting.distance, newMesh);
  106670. newMesh.isVisible = true;
  106671. //check if it is the last
  106672. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  106673. //all done, run the success callback.
  106674. task.successCallback();
  106675. }
  106676. _this.executeNext();
  106677. });
  106678. });
  106679. }
  106680. else {
  106681. //single simplifier.
  106682. var simplifier = this.getSimplifier(task);
  106683. var runDecimation = function (setting, callback) {
  106684. simplifier.simplify(setting, function (newMesh) {
  106685. task.mesh.addLODLevel(setting.distance, newMesh);
  106686. newMesh.isVisible = true;
  106687. //run the next quality level
  106688. callback();
  106689. });
  106690. };
  106691. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  106692. runDecimation(task.settings[loop.index], function () {
  106693. loop.executeNext();
  106694. });
  106695. }, function () {
  106696. //execution ended, run the success callback.
  106697. if (task.successCallback) {
  106698. task.successCallback();
  106699. }
  106700. _this.executeNext();
  106701. });
  106702. }
  106703. };
  106704. SimplificationQueue.prototype.getSimplifier = function (task) {
  106705. switch (task.simplificationType) {
  106706. case SimplificationType.QUADRATIC:
  106707. default:
  106708. return new QuadraticErrorSimplification(task.mesh);
  106709. }
  106710. };
  106711. return SimplificationQueue;
  106712. }());
  106713. BABYLON.SimplificationQueue = SimplificationQueue;
  106714. /**
  106715. * The implemented types of simplification
  106716. * At the moment only Quadratic Error Decimation is implemented
  106717. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106718. */
  106719. var SimplificationType;
  106720. (function (SimplificationType) {
  106721. /** Quadratic error decimation */
  106722. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  106723. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  106724. var DecimationTriangle = /** @class */ (function () {
  106725. function DecimationTriangle(vertices) {
  106726. this.vertices = vertices;
  106727. this.error = new Array(4);
  106728. this.deleted = false;
  106729. this.isDirty = false;
  106730. this.deletePending = false;
  106731. this.borderFactor = 0;
  106732. }
  106733. return DecimationTriangle;
  106734. }());
  106735. var DecimationVertex = /** @class */ (function () {
  106736. function DecimationVertex(position, id) {
  106737. this.position = position;
  106738. this.id = id;
  106739. this.isBorder = true;
  106740. this.q = new QuadraticMatrix();
  106741. this.triangleCount = 0;
  106742. this.triangleStart = 0;
  106743. this.originalOffsets = [];
  106744. }
  106745. DecimationVertex.prototype.updatePosition = function (newPosition) {
  106746. this.position.copyFrom(newPosition);
  106747. };
  106748. return DecimationVertex;
  106749. }());
  106750. var QuadraticMatrix = /** @class */ (function () {
  106751. function QuadraticMatrix(data) {
  106752. this.data = new Array(10);
  106753. for (var i = 0; i < 10; ++i) {
  106754. if (data && data[i]) {
  106755. this.data[i] = data[i];
  106756. }
  106757. else {
  106758. this.data[i] = 0;
  106759. }
  106760. }
  106761. }
  106762. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  106763. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  106764. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  106765. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  106766. return det;
  106767. };
  106768. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  106769. for (var i = 0; i < 10; ++i) {
  106770. this.data[i] += matrix.data[i];
  106771. }
  106772. };
  106773. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  106774. for (var i = 0; i < 10; ++i) {
  106775. this.data[i] += data[i];
  106776. }
  106777. };
  106778. QuadraticMatrix.prototype.add = function (matrix) {
  106779. var m = new QuadraticMatrix();
  106780. for (var i = 0; i < 10; ++i) {
  106781. m.data[i] = this.data[i] + matrix.data[i];
  106782. }
  106783. return m;
  106784. };
  106785. QuadraticMatrix.FromData = function (a, b, c, d) {
  106786. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  106787. };
  106788. //returning an array to avoid garbage collection
  106789. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  106790. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  106791. };
  106792. return QuadraticMatrix;
  106793. }());
  106794. var Reference = /** @class */ (function () {
  106795. function Reference(vertexId, triangleId) {
  106796. this.vertexId = vertexId;
  106797. this.triangleId = triangleId;
  106798. }
  106799. return Reference;
  106800. }());
  106801. /**
  106802. * An implementation of the Quadratic Error simplification algorithm.
  106803. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  106804. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  106805. * @author RaananW
  106806. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106807. */
  106808. var QuadraticErrorSimplification = /** @class */ (function () {
  106809. function QuadraticErrorSimplification(_mesh) {
  106810. this._mesh = _mesh;
  106811. this.syncIterations = 5000;
  106812. this.aggressiveness = 7;
  106813. this.decimationIterations = 100;
  106814. this.boundingBoxEpsilon = BABYLON.Epsilon;
  106815. }
  106816. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  106817. var _this = this;
  106818. this.initDecimatedMesh();
  106819. //iterating through the submeshes array, one after the other.
  106820. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  106821. _this.initWithMesh(loop.index, function () {
  106822. _this.runDecimation(settings, loop.index, function () {
  106823. loop.executeNext();
  106824. });
  106825. }, settings.optimizeMesh);
  106826. }, function () {
  106827. setTimeout(function () {
  106828. successCallback(_this._reconstructedMesh);
  106829. }, 0);
  106830. });
  106831. };
  106832. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  106833. var _this = this;
  106834. var targetCount = ~~(this.triangles.length * settings.quality);
  106835. var deletedTriangles = 0;
  106836. var triangleCount = this.triangles.length;
  106837. var iterationFunction = function (iteration, callback) {
  106838. setTimeout(function () {
  106839. if (iteration % 5 === 0) {
  106840. _this.updateMesh(iteration === 0);
  106841. }
  106842. for (var i = 0; i < _this.triangles.length; ++i) {
  106843. _this.triangles[i].isDirty = false;
  106844. }
  106845. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  106846. var trianglesIterator = function (i) {
  106847. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  106848. var t = _this.triangles[tIdx];
  106849. if (!t) {
  106850. return;
  106851. }
  106852. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  106853. return;
  106854. }
  106855. for (var j = 0; j < 3; ++j) {
  106856. if (t.error[j] < threshold) {
  106857. var deleted0 = [];
  106858. var deleted1 = [];
  106859. var v0 = t.vertices[j];
  106860. var v1 = t.vertices[(j + 1) % 3];
  106861. if (v0.isBorder || v1.isBorder) {
  106862. continue;
  106863. }
  106864. var p = BABYLON.Vector3.Zero();
  106865. var n = BABYLON.Vector3.Zero();
  106866. var uv = BABYLON.Vector2.Zero();
  106867. var color = new BABYLON.Color4(0, 0, 0, 1);
  106868. _this.calculateError(v0, v1, p, n, uv, color);
  106869. var delTr = new Array();
  106870. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr)) {
  106871. continue;
  106872. }
  106873. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr)) {
  106874. continue;
  106875. }
  106876. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0) {
  106877. continue;
  106878. }
  106879. var uniqueArray = new Array();
  106880. delTr.forEach(function (deletedT) {
  106881. if (uniqueArray.indexOf(deletedT) === -1) {
  106882. deletedT.deletePending = true;
  106883. uniqueArray.push(deletedT);
  106884. }
  106885. });
  106886. if (uniqueArray.length % 2 !== 0) {
  106887. continue;
  106888. }
  106889. v0.q = v1.q.add(v0.q);
  106890. v0.updatePosition(p);
  106891. var tStart = _this.references.length;
  106892. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  106893. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  106894. var tCount = _this.references.length - tStart;
  106895. if (tCount <= v0.triangleCount) {
  106896. if (tCount) {
  106897. for (var c = 0; c < tCount; c++) {
  106898. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  106899. }
  106900. }
  106901. }
  106902. else {
  106903. v0.triangleStart = tStart;
  106904. }
  106905. v0.triangleCount = tCount;
  106906. break;
  106907. }
  106908. }
  106909. };
  106910. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  106911. }, 0);
  106912. };
  106913. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  106914. if (triangleCount - deletedTriangles <= targetCount) {
  106915. loop.breakLoop();
  106916. }
  106917. else {
  106918. iterationFunction(loop.index, function () {
  106919. loop.executeNext();
  106920. });
  106921. }
  106922. }, function () {
  106923. setTimeout(function () {
  106924. //reconstruct this part of the mesh
  106925. _this.reconstructMesh(submeshIndex);
  106926. successCallback();
  106927. }, 0);
  106928. });
  106929. };
  106930. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  106931. var _this = this;
  106932. this.vertices = [];
  106933. this.triangles = [];
  106934. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  106935. var indices = this._mesh.getIndices();
  106936. var submesh = this._mesh.subMeshes[submeshIndex];
  106937. var findInVertices = function (positionToSearch) {
  106938. if (optimizeMesh) {
  106939. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  106940. if (_this.vertices[ii].position.equals(positionToSearch)) {
  106941. return _this.vertices[ii];
  106942. }
  106943. }
  106944. }
  106945. return null;
  106946. };
  106947. var vertexReferences = [];
  106948. var vertexInit = function (i) {
  106949. if (!positionData) {
  106950. return;
  106951. }
  106952. var offset = i + submesh.verticesStart;
  106953. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  106954. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  106955. vertex.originalOffsets.push(offset);
  106956. if (vertex.id === _this.vertices.length) {
  106957. _this.vertices.push(vertex);
  106958. }
  106959. vertexReferences.push(vertex.id);
  106960. };
  106961. //var totalVertices = mesh.getTotalVertices();
  106962. var totalVertices = submesh.verticesCount;
  106963. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  106964. var indicesInit = function (i) {
  106965. if (!indices) {
  106966. return;
  106967. }
  106968. var offset = (submesh.indexStart / 3) + i;
  106969. var pos = (offset * 3);
  106970. var i0 = indices[pos + 0];
  106971. var i1 = indices[pos + 1];
  106972. var i2 = indices[pos + 2];
  106973. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  106974. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  106975. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  106976. var triangle = new DecimationTriangle([v0, v1, v2]);
  106977. triangle.originalOffset = pos;
  106978. _this.triangles.push(triangle);
  106979. };
  106980. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  106981. _this.init(callback);
  106982. });
  106983. });
  106984. };
  106985. QuadraticErrorSimplification.prototype.init = function (callback) {
  106986. var _this = this;
  106987. var triangleInit1 = function (i) {
  106988. var t = _this.triangles[i];
  106989. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  106990. for (var j = 0; j < 3; j++) {
  106991. 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))));
  106992. }
  106993. };
  106994. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  106995. var triangleInit2 = function (i) {
  106996. var t = _this.triangles[i];
  106997. for (var j = 0; j < 3; ++j) {
  106998. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  106999. }
  107000. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  107001. };
  107002. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  107003. callback();
  107004. });
  107005. });
  107006. };
  107007. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  107008. var newTriangles = [];
  107009. var i;
  107010. for (i = 0; i < this.vertices.length; ++i) {
  107011. this.vertices[i].triangleCount = 0;
  107012. }
  107013. var t;
  107014. var j;
  107015. for (i = 0; i < this.triangles.length; ++i) {
  107016. if (!this.triangles[i].deleted) {
  107017. t = this.triangles[i];
  107018. for (j = 0; j < 3; ++j) {
  107019. t.vertices[j].triangleCount = 1;
  107020. }
  107021. newTriangles.push(t);
  107022. }
  107023. }
  107024. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  107025. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  107026. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  107027. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  107028. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  107029. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  107030. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  107031. var vertexCount = 0;
  107032. for (i = 0; i < this.vertices.length; ++i) {
  107033. var vertex = this.vertices[i];
  107034. vertex.id = vertexCount;
  107035. if (vertex.triangleCount) {
  107036. vertex.originalOffsets.forEach(function (originalOffset) {
  107037. if (!normalData) {
  107038. return;
  107039. }
  107040. newPositionData.push(vertex.position.x);
  107041. newPositionData.push(vertex.position.y);
  107042. newPositionData.push(vertex.position.z);
  107043. newNormalData.push(normalData[originalOffset * 3]);
  107044. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  107045. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  107046. if (uvs && uvs.length) {
  107047. newUVsData.push(uvs[(originalOffset * 2)]);
  107048. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  107049. }
  107050. else if (colorsData && colorsData.length) {
  107051. newColorsData.push(colorsData[(originalOffset * 4)]);
  107052. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  107053. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  107054. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  107055. }
  107056. ++vertexCount;
  107057. });
  107058. }
  107059. }
  107060. var startingIndex = this._reconstructedMesh.getTotalIndices();
  107061. var startingVertex = this._reconstructedMesh.getTotalVertices();
  107062. var submeshesArray = this._reconstructedMesh.subMeshes;
  107063. this._reconstructedMesh.subMeshes = [];
  107064. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  107065. var originalIndices = this._mesh.getIndices();
  107066. for (i = 0; i < newTriangles.length; ++i) {
  107067. t = newTriangles[i]; //now get the new referencing point for each vertex
  107068. [0, 1, 2].forEach(function (idx) {
  107069. var id = originalIndices[t.originalOffset + idx];
  107070. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  107071. if (offset < 0) {
  107072. offset = 0;
  107073. }
  107074. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  107075. });
  107076. }
  107077. //overwriting the old vertex buffers and indices.
  107078. this._reconstructedMesh.setIndices(newIndicesArray);
  107079. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  107080. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  107081. if (newUVsData.length > 0) {
  107082. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  107083. }
  107084. if (newColorsData.length > 0) {
  107085. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  107086. }
  107087. //create submesh
  107088. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  107089. if (submeshIndex > 0) {
  107090. this._reconstructedMesh.subMeshes = [];
  107091. submeshesArray.forEach(function (submesh) {
  107092. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  107093. });
  107094. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  107095. }
  107096. };
  107097. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  107098. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  107099. this._reconstructedMesh.material = this._mesh.material;
  107100. this._reconstructedMesh.parent = this._mesh.parent;
  107101. this._reconstructedMesh.isVisible = false;
  107102. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  107103. };
  107104. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  107105. for (var i = 0; i < vertex1.triangleCount; ++i) {
  107106. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  107107. if (t.deleted) {
  107108. continue;
  107109. }
  107110. var s = this.references[vertex1.triangleStart + i].vertexId;
  107111. var v1 = t.vertices[(s + 1) % 3];
  107112. var v2 = t.vertices[(s + 2) % 3];
  107113. if ((v1 === vertex2 || v2 === vertex2)) {
  107114. deletedArray[i] = true;
  107115. delTr.push(t);
  107116. continue;
  107117. }
  107118. var d1 = v1.position.subtract(point);
  107119. d1 = d1.normalize();
  107120. var d2 = v2.position.subtract(point);
  107121. d2 = d2.normalize();
  107122. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999) {
  107123. return true;
  107124. }
  107125. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  107126. deletedArray[i] = false;
  107127. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2) {
  107128. return true;
  107129. }
  107130. }
  107131. return false;
  107132. };
  107133. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  107134. var newDeleted = deletedTriangles;
  107135. for (var i = 0; i < vertex.triangleCount; ++i) {
  107136. var ref = this.references[vertex.triangleStart + i];
  107137. var t = this.triangles[ref.triangleId];
  107138. if (t.deleted) {
  107139. continue;
  107140. }
  107141. if (deletedArray[i] && t.deletePending) {
  107142. t.deleted = true;
  107143. newDeleted++;
  107144. continue;
  107145. }
  107146. t.vertices[ref.vertexId] = origVertex;
  107147. t.isDirty = true;
  107148. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  107149. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  107150. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  107151. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  107152. this.references.push(ref);
  107153. }
  107154. return newDeleted;
  107155. };
  107156. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  107157. for (var i = 0; i < this.vertices.length; ++i) {
  107158. var vCount = [];
  107159. var vId = [];
  107160. var v = this.vertices[i];
  107161. var j;
  107162. for (j = 0; j < v.triangleCount; ++j) {
  107163. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  107164. for (var ii = 0; ii < 3; ii++) {
  107165. var ofs = 0;
  107166. var vv = triangle.vertices[ii];
  107167. while (ofs < vCount.length) {
  107168. if (vId[ofs] === vv.id) {
  107169. break;
  107170. }
  107171. ++ofs;
  107172. }
  107173. if (ofs === vCount.length) {
  107174. vCount.push(1);
  107175. vId.push(vv.id);
  107176. }
  107177. else {
  107178. vCount[ofs]++;
  107179. }
  107180. }
  107181. }
  107182. for (j = 0; j < vCount.length; ++j) {
  107183. if (vCount[j] === 1) {
  107184. this.vertices[vId[j]].isBorder = true;
  107185. }
  107186. else {
  107187. this.vertices[vId[j]].isBorder = false;
  107188. }
  107189. }
  107190. }
  107191. };
  107192. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  107193. if (identifyBorders === void 0) { identifyBorders = false; }
  107194. var i;
  107195. if (!identifyBorders) {
  107196. var newTrianglesVector = [];
  107197. for (i = 0; i < this.triangles.length; ++i) {
  107198. if (!this.triangles[i].deleted) {
  107199. newTrianglesVector.push(this.triangles[i]);
  107200. }
  107201. }
  107202. this.triangles = newTrianglesVector;
  107203. }
  107204. for (i = 0; i < this.vertices.length; ++i) {
  107205. this.vertices[i].triangleCount = 0;
  107206. this.vertices[i].triangleStart = 0;
  107207. }
  107208. var t;
  107209. var j;
  107210. var v;
  107211. for (i = 0; i < this.triangles.length; ++i) {
  107212. t = this.triangles[i];
  107213. for (j = 0; j < 3; ++j) {
  107214. v = t.vertices[j];
  107215. v.triangleCount++;
  107216. }
  107217. }
  107218. var tStart = 0;
  107219. for (i = 0; i < this.vertices.length; ++i) {
  107220. this.vertices[i].triangleStart = tStart;
  107221. tStart += this.vertices[i].triangleCount;
  107222. this.vertices[i].triangleCount = 0;
  107223. }
  107224. var newReferences = new Array(this.triangles.length * 3);
  107225. for (i = 0; i < this.triangles.length; ++i) {
  107226. t = this.triangles[i];
  107227. for (j = 0; j < 3; ++j) {
  107228. v = t.vertices[j];
  107229. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  107230. v.triangleCount++;
  107231. }
  107232. }
  107233. this.references = newReferences;
  107234. if (identifyBorders) {
  107235. this.identifyBorder();
  107236. }
  107237. };
  107238. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  107239. var x = point.x;
  107240. var y = point.y;
  107241. var z = point.z;
  107242. 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
  107243. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  107244. };
  107245. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  107246. var q = vertex1.q.add(vertex2.q);
  107247. var border = vertex1.isBorder && vertex2.isBorder;
  107248. var error = 0;
  107249. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  107250. if (qDet !== 0 && !border) {
  107251. if (!pointResult) {
  107252. pointResult = BABYLON.Vector3.Zero();
  107253. }
  107254. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  107255. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  107256. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  107257. error = this.vertexError(q, pointResult);
  107258. }
  107259. else {
  107260. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  107261. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  107262. var error1 = this.vertexError(q, vertex1.position);
  107263. var error2 = this.vertexError(q, vertex2.position);
  107264. var error3 = this.vertexError(q, p3);
  107265. error = Math.min(error1, error2, error3);
  107266. if (error === error1) {
  107267. if (pointResult) {
  107268. pointResult.copyFrom(vertex1.position);
  107269. }
  107270. }
  107271. else if (error === error2) {
  107272. if (pointResult) {
  107273. pointResult.copyFrom(vertex2.position);
  107274. }
  107275. }
  107276. else {
  107277. if (pointResult) {
  107278. pointResult.copyFrom(p3);
  107279. }
  107280. }
  107281. }
  107282. return error;
  107283. };
  107284. return QuadraticErrorSimplification;
  107285. }());
  107286. })(BABYLON || (BABYLON = {}));
  107287. //# sourceMappingURL=babylon.meshSimplification.js.map
  107288. var BABYLON;
  107289. (function (BABYLON) {
  107290. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  107291. get: function () {
  107292. if (!this._simplificationQueue) {
  107293. this._simplificationQueue = new BABYLON.SimplificationQueue();
  107294. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  107295. if (!component) {
  107296. component = new SimplicationQueueSceneComponent(this);
  107297. this._addComponent(component);
  107298. }
  107299. }
  107300. return this._simplificationQueue;
  107301. },
  107302. set: function (value) {
  107303. this._simplificationQueue = value;
  107304. },
  107305. enumerable: true,
  107306. configurable: true
  107307. });
  107308. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  107309. if (parallelProcessing === void 0) { parallelProcessing = true; }
  107310. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  107311. this.getScene().simplificationQueue.addTask({
  107312. settings: settings,
  107313. parallelProcessing: parallelProcessing,
  107314. mesh: this,
  107315. simplificationType: simplificationType,
  107316. successCallback: successCallback
  107317. });
  107318. return this;
  107319. };
  107320. /**
  107321. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  107322. * created in a scene
  107323. */
  107324. var SimplicationQueueSceneComponent = /** @class */ (function () {
  107325. /**
  107326. * Creates a new instance of the component for the given scene
  107327. * @param scene Defines the scene to register the component in
  107328. */
  107329. function SimplicationQueueSceneComponent(scene) {
  107330. /**
  107331. * The component name helpfull to identify the component in the list of scene components.
  107332. */
  107333. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  107334. this.scene = scene;
  107335. }
  107336. /**
  107337. * Registers the component in a given scene
  107338. */
  107339. SimplicationQueueSceneComponent.prototype.register = function () {
  107340. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  107341. };
  107342. /**
  107343. * Rebuilds the elements related to this component in case of
  107344. * context lost for instance.
  107345. */
  107346. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  107347. // Nothing to do for this component
  107348. };
  107349. /**
  107350. * Disposes the component and the associated ressources
  107351. */
  107352. SimplicationQueueSceneComponent.prototype.dispose = function () {
  107353. // Nothing to do for this component
  107354. };
  107355. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  107356. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  107357. this.scene._simplificationQueue.executeNext();
  107358. }
  107359. };
  107360. return SimplicationQueueSceneComponent;
  107361. }());
  107362. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  107363. })(BABYLON || (BABYLON = {}));
  107364. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  107365. var BABYLON;
  107366. (function (BABYLON) {
  107367. /**
  107368. * Class used to represent a specific level of detail of a mesh
  107369. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  107370. */
  107371. var MeshLODLevel = /** @class */ (function () {
  107372. /**
  107373. * Creates a new LOD level
  107374. * @param distance defines the distance where this level should star being displayed
  107375. * @param mesh defines the mesh to use to render this level
  107376. */
  107377. function MeshLODLevel(
  107378. /** Defines the distance where this level should star being displayed */
  107379. distance,
  107380. /** Defines the mesh to use to render this level */
  107381. mesh) {
  107382. this.distance = distance;
  107383. this.mesh = mesh;
  107384. }
  107385. return MeshLODLevel;
  107386. }());
  107387. BABYLON.MeshLODLevel = MeshLODLevel;
  107388. })(BABYLON || (BABYLON = {}));
  107389. //# sourceMappingURL=babylon.meshLODLevel.js.map
  107390. var BABYLON;
  107391. (function (BABYLON) {
  107392. /**
  107393. * Defines the root class used to create scene optimization to use with SceneOptimizer
  107394. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107395. */
  107396. var SceneOptimization = /** @class */ (function () {
  107397. /**
  107398. * Creates the SceneOptimization object
  107399. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107400. * @param desc defines the description associated with the optimization
  107401. */
  107402. function SceneOptimization(
  107403. /**
  107404. * Defines the priority of this optimization (0 by default which means first in the list)
  107405. */
  107406. priority) {
  107407. if (priority === void 0) { priority = 0; }
  107408. this.priority = priority;
  107409. }
  107410. /**
  107411. * Gets a string describing the action executed by the current optimization
  107412. * @returns description string
  107413. */
  107414. SceneOptimization.prototype.getDescription = function () {
  107415. return "";
  107416. };
  107417. /**
  107418. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107419. * @param scene defines the current scene where to apply this optimization
  107420. * @param optimizer defines the current optimizer
  107421. * @returns true if everything that can be done was applied
  107422. */
  107423. SceneOptimization.prototype.apply = function (scene, optimizer) {
  107424. return true;
  107425. };
  107426. return SceneOptimization;
  107427. }());
  107428. BABYLON.SceneOptimization = SceneOptimization;
  107429. /**
  107430. * Defines an optimization used to reduce the size of render target textures
  107431. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107432. */
  107433. var TextureOptimization = /** @class */ (function (_super) {
  107434. __extends(TextureOptimization, _super);
  107435. /**
  107436. * Creates the TextureOptimization object
  107437. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107438. * @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
  107439. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  107440. */
  107441. function TextureOptimization(
  107442. /**
  107443. * Defines the priority of this optimization (0 by default which means first in the list)
  107444. */
  107445. priority,
  107446. /**
  107447. * 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
  107448. */
  107449. maximumSize,
  107450. /**
  107451. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  107452. */
  107453. step) {
  107454. if (priority === void 0) { priority = 0; }
  107455. if (maximumSize === void 0) { maximumSize = 1024; }
  107456. if (step === void 0) { step = 0.5; }
  107457. var _this = _super.call(this, priority) || this;
  107458. _this.priority = priority;
  107459. _this.maximumSize = maximumSize;
  107460. _this.step = step;
  107461. return _this;
  107462. }
  107463. /**
  107464. * Gets a string describing the action executed by the current optimization
  107465. * @returns description string
  107466. */
  107467. TextureOptimization.prototype.getDescription = function () {
  107468. return "Reducing render target texture size to " + this.maximumSize;
  107469. };
  107470. /**
  107471. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107472. * @param scene defines the current scene where to apply this optimization
  107473. * @param optimizer defines the current optimizer
  107474. * @returns true if everything that can be done was applied
  107475. */
  107476. TextureOptimization.prototype.apply = function (scene, optimizer) {
  107477. var allDone = true;
  107478. for (var index = 0; index < scene.textures.length; index++) {
  107479. var texture = scene.textures[index];
  107480. if (!texture.canRescale || texture.getContext) {
  107481. continue;
  107482. }
  107483. var currentSize = texture.getSize();
  107484. var maxDimension = Math.max(currentSize.width, currentSize.height);
  107485. if (maxDimension > this.maximumSize) {
  107486. texture.scale(this.step);
  107487. allDone = false;
  107488. }
  107489. }
  107490. return allDone;
  107491. };
  107492. return TextureOptimization;
  107493. }(SceneOptimization));
  107494. BABYLON.TextureOptimization = TextureOptimization;
  107495. /**
  107496. * Defines an optimization used to increase or decrease the rendering resolution
  107497. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107498. */
  107499. var HardwareScalingOptimization = /** @class */ (function (_super) {
  107500. __extends(HardwareScalingOptimization, _super);
  107501. /**
  107502. * Creates the HardwareScalingOptimization object
  107503. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107504. * @param maximumScale defines the maximum scale to use (2 by default)
  107505. * @param step defines the step to use between two passes (0.5 by default)
  107506. */
  107507. function HardwareScalingOptimization(
  107508. /**
  107509. * Defines the priority of this optimization (0 by default which means first in the list)
  107510. */
  107511. priority,
  107512. /**
  107513. * Defines the maximum scale to use (2 by default)
  107514. */
  107515. maximumScale,
  107516. /**
  107517. * Defines the step to use between two passes (0.5 by default)
  107518. */
  107519. step) {
  107520. if (priority === void 0) { priority = 0; }
  107521. if (maximumScale === void 0) { maximumScale = 2; }
  107522. if (step === void 0) { step = 0.25; }
  107523. var _this = _super.call(this, priority) || this;
  107524. _this.priority = priority;
  107525. _this.maximumScale = maximumScale;
  107526. _this.step = step;
  107527. _this._currentScale = -1;
  107528. _this._directionOffset = 1;
  107529. return _this;
  107530. }
  107531. /**
  107532. * Gets a string describing the action executed by the current optimization
  107533. * @return description string
  107534. */
  107535. HardwareScalingOptimization.prototype.getDescription = function () {
  107536. return "Setting hardware scaling level to " + this._currentScale;
  107537. };
  107538. /**
  107539. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107540. * @param scene defines the current scene where to apply this optimization
  107541. * @param optimizer defines the current optimizer
  107542. * @returns true if everything that can be done was applied
  107543. */
  107544. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  107545. if (this._currentScale === -1) {
  107546. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  107547. if (this._currentScale > this.maximumScale) {
  107548. this._directionOffset = -1;
  107549. }
  107550. }
  107551. this._currentScale += this._directionOffset * this.step;
  107552. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  107553. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  107554. };
  107555. return HardwareScalingOptimization;
  107556. }(SceneOptimization));
  107557. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  107558. /**
  107559. * Defines an optimization used to remove shadows
  107560. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107561. */
  107562. var ShadowsOptimization = /** @class */ (function (_super) {
  107563. __extends(ShadowsOptimization, _super);
  107564. function ShadowsOptimization() {
  107565. return _super !== null && _super.apply(this, arguments) || this;
  107566. }
  107567. /**
  107568. * Gets a string describing the action executed by the current optimization
  107569. * @return description string
  107570. */
  107571. ShadowsOptimization.prototype.getDescription = function () {
  107572. return "Turning shadows on/off";
  107573. };
  107574. /**
  107575. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107576. * @param scene defines the current scene where to apply this optimization
  107577. * @param optimizer defines the current optimizer
  107578. * @returns true if everything that can be done was applied
  107579. */
  107580. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  107581. scene.shadowsEnabled = optimizer.isInImprovementMode;
  107582. return true;
  107583. };
  107584. return ShadowsOptimization;
  107585. }(SceneOptimization));
  107586. BABYLON.ShadowsOptimization = ShadowsOptimization;
  107587. /**
  107588. * Defines an optimization used to turn post-processes off
  107589. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107590. */
  107591. var PostProcessesOptimization = /** @class */ (function (_super) {
  107592. __extends(PostProcessesOptimization, _super);
  107593. function PostProcessesOptimization() {
  107594. return _super !== null && _super.apply(this, arguments) || this;
  107595. }
  107596. /**
  107597. * Gets a string describing the action executed by the current optimization
  107598. * @return description string
  107599. */
  107600. PostProcessesOptimization.prototype.getDescription = function () {
  107601. return "Turning post-processes on/off";
  107602. };
  107603. /**
  107604. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107605. * @param scene defines the current scene where to apply this optimization
  107606. * @param optimizer defines the current optimizer
  107607. * @returns true if everything that can be done was applied
  107608. */
  107609. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  107610. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  107611. return true;
  107612. };
  107613. return PostProcessesOptimization;
  107614. }(SceneOptimization));
  107615. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  107616. /**
  107617. * Defines an optimization used to turn lens flares off
  107618. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107619. */
  107620. var LensFlaresOptimization = /** @class */ (function (_super) {
  107621. __extends(LensFlaresOptimization, _super);
  107622. function LensFlaresOptimization() {
  107623. return _super !== null && _super.apply(this, arguments) || this;
  107624. }
  107625. /**
  107626. * Gets a string describing the action executed by the current optimization
  107627. * @return description string
  107628. */
  107629. LensFlaresOptimization.prototype.getDescription = function () {
  107630. return "Turning lens flares on/off";
  107631. };
  107632. /**
  107633. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107634. * @param scene defines the current scene where to apply this optimization
  107635. * @param optimizer defines the current optimizer
  107636. * @returns true if everything that can be done was applied
  107637. */
  107638. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  107639. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  107640. return true;
  107641. };
  107642. return LensFlaresOptimization;
  107643. }(SceneOptimization));
  107644. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  107645. /**
  107646. * Defines an optimization based on user defined callback.
  107647. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107648. */
  107649. var CustomOptimization = /** @class */ (function (_super) {
  107650. __extends(CustomOptimization, _super);
  107651. function CustomOptimization() {
  107652. return _super !== null && _super.apply(this, arguments) || this;
  107653. }
  107654. /**
  107655. * Gets a string describing the action executed by the current optimization
  107656. * @returns description string
  107657. */
  107658. CustomOptimization.prototype.getDescription = function () {
  107659. if (this.onGetDescription) {
  107660. return this.onGetDescription();
  107661. }
  107662. return "Running user defined callback";
  107663. };
  107664. /**
  107665. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107666. * @param scene defines the current scene where to apply this optimization
  107667. * @param optimizer defines the current optimizer
  107668. * @returns true if everything that can be done was applied
  107669. */
  107670. CustomOptimization.prototype.apply = function (scene, optimizer) {
  107671. if (this.onApply) {
  107672. return this.onApply(scene, optimizer);
  107673. }
  107674. return true;
  107675. };
  107676. return CustomOptimization;
  107677. }(SceneOptimization));
  107678. BABYLON.CustomOptimization = CustomOptimization;
  107679. /**
  107680. * Defines an optimization used to turn particles off
  107681. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107682. */
  107683. var ParticlesOptimization = /** @class */ (function (_super) {
  107684. __extends(ParticlesOptimization, _super);
  107685. function ParticlesOptimization() {
  107686. return _super !== null && _super.apply(this, arguments) || this;
  107687. }
  107688. /**
  107689. * Gets a string describing the action executed by the current optimization
  107690. * @return description string
  107691. */
  107692. ParticlesOptimization.prototype.getDescription = function () {
  107693. return "Turning particles on/off";
  107694. };
  107695. /**
  107696. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107697. * @param scene defines the current scene where to apply this optimization
  107698. * @param optimizer defines the current optimizer
  107699. * @returns true if everything that can be done was applied
  107700. */
  107701. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  107702. scene.particlesEnabled = optimizer.isInImprovementMode;
  107703. return true;
  107704. };
  107705. return ParticlesOptimization;
  107706. }(SceneOptimization));
  107707. BABYLON.ParticlesOptimization = ParticlesOptimization;
  107708. /**
  107709. * Defines an optimization used to turn render targets off
  107710. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107711. */
  107712. var RenderTargetsOptimization = /** @class */ (function (_super) {
  107713. __extends(RenderTargetsOptimization, _super);
  107714. function RenderTargetsOptimization() {
  107715. return _super !== null && _super.apply(this, arguments) || this;
  107716. }
  107717. /**
  107718. * Gets a string describing the action executed by the current optimization
  107719. * @return description string
  107720. */
  107721. RenderTargetsOptimization.prototype.getDescription = function () {
  107722. return "Turning render targets off";
  107723. };
  107724. /**
  107725. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107726. * @param scene defines the current scene where to apply this optimization
  107727. * @param optimizer defines the current optimizer
  107728. * @returns true if everything that can be done was applied
  107729. */
  107730. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  107731. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  107732. return true;
  107733. };
  107734. return RenderTargetsOptimization;
  107735. }(SceneOptimization));
  107736. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  107737. /**
  107738. * Defines an optimization used to merge meshes with compatible materials
  107739. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107740. */
  107741. var MergeMeshesOptimization = /** @class */ (function (_super) {
  107742. __extends(MergeMeshesOptimization, _super);
  107743. function MergeMeshesOptimization() {
  107744. var _this = _super !== null && _super.apply(this, arguments) || this;
  107745. _this._canBeMerged = function (abstractMesh) {
  107746. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  107747. return false;
  107748. }
  107749. var mesh = abstractMesh;
  107750. if (mesh.isDisposed()) {
  107751. return false;
  107752. }
  107753. if (!mesh.isVisible || !mesh.isEnabled()) {
  107754. return false;
  107755. }
  107756. if (mesh.instances.length > 0) {
  107757. return false;
  107758. }
  107759. if (mesh.skeleton || mesh.hasLODLevels) {
  107760. return false;
  107761. }
  107762. return true;
  107763. };
  107764. return _this;
  107765. }
  107766. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  107767. /**
  107768. * Gets or sets a boolean which defines if optimization octree has to be updated
  107769. */
  107770. get: function () {
  107771. return MergeMeshesOptimization._UpdateSelectionTree;
  107772. },
  107773. /**
  107774. * Gets or sets a boolean which defines if optimization octree has to be updated
  107775. */
  107776. set: function (value) {
  107777. MergeMeshesOptimization._UpdateSelectionTree = value;
  107778. },
  107779. enumerable: true,
  107780. configurable: true
  107781. });
  107782. /**
  107783. * Gets a string describing the action executed by the current optimization
  107784. * @return description string
  107785. */
  107786. MergeMeshesOptimization.prototype.getDescription = function () {
  107787. return "Merging similar meshes together";
  107788. };
  107789. /**
  107790. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107791. * @param scene defines the current scene where to apply this optimization
  107792. * @param optimizer defines the current optimizer
  107793. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  107794. * @returns true if everything that can be done was applied
  107795. */
  107796. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  107797. var globalPool = scene.meshes.slice(0);
  107798. var globalLength = globalPool.length;
  107799. for (var index = 0; index < globalLength; index++) {
  107800. var currentPool = new Array();
  107801. var current = globalPool[index];
  107802. // Checks
  107803. if (!this._canBeMerged(current)) {
  107804. continue;
  107805. }
  107806. currentPool.push(current);
  107807. // Find compatible meshes
  107808. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  107809. var otherMesh = globalPool[subIndex];
  107810. if (!this._canBeMerged(otherMesh)) {
  107811. continue;
  107812. }
  107813. if (otherMesh.material !== current.material) {
  107814. continue;
  107815. }
  107816. if (otherMesh.checkCollisions !== current.checkCollisions) {
  107817. continue;
  107818. }
  107819. currentPool.push(otherMesh);
  107820. globalLength--;
  107821. globalPool.splice(subIndex, 1);
  107822. subIndex--;
  107823. }
  107824. if (currentPool.length < 2) {
  107825. continue;
  107826. }
  107827. // Merge meshes
  107828. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  107829. }
  107830. // Call the octree system optimization if it is defined.
  107831. var sceneAsAny = scene;
  107832. if (sceneAsAny.createOrUpdateSelectionOctree) {
  107833. if (updateSelectionTree != undefined) {
  107834. if (updateSelectionTree) {
  107835. sceneAsAny.createOrUpdateSelectionOctree();
  107836. }
  107837. }
  107838. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  107839. sceneAsAny.createOrUpdateSelectionOctree();
  107840. }
  107841. }
  107842. return true;
  107843. };
  107844. MergeMeshesOptimization._UpdateSelectionTree = false;
  107845. return MergeMeshesOptimization;
  107846. }(SceneOptimization));
  107847. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  107848. /**
  107849. * Defines a list of options used by SceneOptimizer
  107850. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107851. */
  107852. var SceneOptimizerOptions = /** @class */ (function () {
  107853. /**
  107854. * Creates a new list of options used by SceneOptimizer
  107855. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  107856. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  107857. */
  107858. function SceneOptimizerOptions(
  107859. /**
  107860. * Defines the target frame rate to reach (60 by default)
  107861. */
  107862. targetFrameRate,
  107863. /**
  107864. * Defines the interval between two checkes (2000ms by default)
  107865. */
  107866. trackerDuration) {
  107867. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  107868. if (trackerDuration === void 0) { trackerDuration = 2000; }
  107869. this.targetFrameRate = targetFrameRate;
  107870. this.trackerDuration = trackerDuration;
  107871. /**
  107872. * Gets the list of optimizations to apply
  107873. */
  107874. this.optimizations = new Array();
  107875. }
  107876. /**
  107877. * Add a new optimization
  107878. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  107879. * @returns the current SceneOptimizerOptions
  107880. */
  107881. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  107882. this.optimizations.push(optimization);
  107883. return this;
  107884. };
  107885. /**
  107886. * Add a new custom optimization
  107887. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  107888. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  107889. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107890. * @returns the current SceneOptimizerOptions
  107891. */
  107892. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  107893. if (priority === void 0) { priority = 0; }
  107894. var optimization = new CustomOptimization(priority);
  107895. optimization.onApply = onApply;
  107896. optimization.onGetDescription = onGetDescription;
  107897. this.optimizations.push(optimization);
  107898. return this;
  107899. };
  107900. /**
  107901. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  107902. * @param targetFrameRate defines the target frame rate (60 by default)
  107903. * @returns a SceneOptimizerOptions object
  107904. */
  107905. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  107906. var result = new SceneOptimizerOptions(targetFrameRate);
  107907. var priority = 0;
  107908. result.addOptimization(new MergeMeshesOptimization(priority));
  107909. result.addOptimization(new ShadowsOptimization(priority));
  107910. result.addOptimization(new LensFlaresOptimization(priority));
  107911. // Next priority
  107912. priority++;
  107913. result.addOptimization(new PostProcessesOptimization(priority));
  107914. result.addOptimization(new ParticlesOptimization(priority));
  107915. // Next priority
  107916. priority++;
  107917. result.addOptimization(new TextureOptimization(priority, 1024));
  107918. return result;
  107919. };
  107920. /**
  107921. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  107922. * @param targetFrameRate defines the target frame rate (60 by default)
  107923. * @returns a SceneOptimizerOptions object
  107924. */
  107925. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  107926. var result = new SceneOptimizerOptions(targetFrameRate);
  107927. var priority = 0;
  107928. result.addOptimization(new MergeMeshesOptimization(priority));
  107929. result.addOptimization(new ShadowsOptimization(priority));
  107930. result.addOptimization(new LensFlaresOptimization(priority));
  107931. // Next priority
  107932. priority++;
  107933. result.addOptimization(new PostProcessesOptimization(priority));
  107934. result.addOptimization(new ParticlesOptimization(priority));
  107935. // Next priority
  107936. priority++;
  107937. result.addOptimization(new TextureOptimization(priority, 512));
  107938. // Next priority
  107939. priority++;
  107940. result.addOptimization(new RenderTargetsOptimization(priority));
  107941. // Next priority
  107942. priority++;
  107943. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  107944. return result;
  107945. };
  107946. /**
  107947. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  107948. * @param targetFrameRate defines the target frame rate (60 by default)
  107949. * @returns a SceneOptimizerOptions object
  107950. */
  107951. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  107952. var result = new SceneOptimizerOptions(targetFrameRate);
  107953. var priority = 0;
  107954. result.addOptimization(new MergeMeshesOptimization(priority));
  107955. result.addOptimization(new ShadowsOptimization(priority));
  107956. result.addOptimization(new LensFlaresOptimization(priority));
  107957. // Next priority
  107958. priority++;
  107959. result.addOptimization(new PostProcessesOptimization(priority));
  107960. result.addOptimization(new ParticlesOptimization(priority));
  107961. // Next priority
  107962. priority++;
  107963. result.addOptimization(new TextureOptimization(priority, 256));
  107964. // Next priority
  107965. priority++;
  107966. result.addOptimization(new RenderTargetsOptimization(priority));
  107967. // Next priority
  107968. priority++;
  107969. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  107970. return result;
  107971. };
  107972. return SceneOptimizerOptions;
  107973. }());
  107974. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  107975. /**
  107976. * Class used to run optimizations in order to reach a target frame rate
  107977. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107978. */
  107979. var SceneOptimizer = /** @class */ (function () {
  107980. /**
  107981. * Creates a new SceneOptimizer
  107982. * @param scene defines the scene to work on
  107983. * @param options defines the options to use with the SceneOptimizer
  107984. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  107985. * @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)
  107986. */
  107987. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  107988. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  107989. if (improvementMode === void 0) { improvementMode = false; }
  107990. var _this = this;
  107991. this._isRunning = false;
  107992. this._currentPriorityLevel = 0;
  107993. this._targetFrameRate = 60;
  107994. this._trackerDuration = 2000;
  107995. this._currentFrameRate = 0;
  107996. this._improvementMode = false;
  107997. /**
  107998. * Defines an observable called when the optimizer reaches the target frame rate
  107999. */
  108000. this.onSuccessObservable = new BABYLON.Observable();
  108001. /**
  108002. * Defines an observable called when the optimizer enables an optimization
  108003. */
  108004. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  108005. /**
  108006. * Defines an observable called when the optimizer is not able to reach the target frame rate
  108007. */
  108008. this.onFailureObservable = new BABYLON.Observable();
  108009. if (!options) {
  108010. this._options = new SceneOptimizerOptions();
  108011. }
  108012. else {
  108013. this._options = options;
  108014. }
  108015. if (this._options.targetFrameRate) {
  108016. this._targetFrameRate = this._options.targetFrameRate;
  108017. }
  108018. if (this._options.trackerDuration) {
  108019. this._trackerDuration = this._options.trackerDuration;
  108020. }
  108021. if (autoGeneratePriorities) {
  108022. var priority = 0;
  108023. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  108024. var optim = _a[_i];
  108025. optim.priority = priority++;
  108026. }
  108027. }
  108028. this._improvementMode = improvementMode;
  108029. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  108030. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  108031. _this._sceneDisposeObserver = null;
  108032. _this.dispose();
  108033. });
  108034. }
  108035. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  108036. /**
  108037. * Gets a boolean indicating if the optimizer is in improvement mode
  108038. */
  108039. get: function () {
  108040. return this._improvementMode;
  108041. },
  108042. enumerable: true,
  108043. configurable: true
  108044. });
  108045. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  108046. /**
  108047. * Gets the current priority level (0 at start)
  108048. */
  108049. get: function () {
  108050. return this._currentPriorityLevel;
  108051. },
  108052. enumerable: true,
  108053. configurable: true
  108054. });
  108055. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  108056. /**
  108057. * Gets the current frame rate checked by the SceneOptimizer
  108058. */
  108059. get: function () {
  108060. return this._currentFrameRate;
  108061. },
  108062. enumerable: true,
  108063. configurable: true
  108064. });
  108065. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  108066. /**
  108067. * Gets or sets the current target frame rate (60 by default)
  108068. */
  108069. get: function () {
  108070. return this._targetFrameRate;
  108071. },
  108072. /**
  108073. * Gets or sets the current target frame rate (60 by default)
  108074. */
  108075. set: function (value) {
  108076. this._targetFrameRate = value;
  108077. },
  108078. enumerable: true,
  108079. configurable: true
  108080. });
  108081. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  108082. /**
  108083. * Gets or sets the current interval between two checks (every 2000ms by default)
  108084. */
  108085. get: function () {
  108086. return this._trackerDuration;
  108087. },
  108088. /**
  108089. * Gets or sets the current interval between two checks (every 2000ms by default)
  108090. */
  108091. set: function (value) {
  108092. this._trackerDuration = value;
  108093. },
  108094. enumerable: true,
  108095. configurable: true
  108096. });
  108097. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  108098. /**
  108099. * Gets the list of active optimizations
  108100. */
  108101. get: function () {
  108102. return this._options.optimizations;
  108103. },
  108104. enumerable: true,
  108105. configurable: true
  108106. });
  108107. /**
  108108. * Stops the current optimizer
  108109. */
  108110. SceneOptimizer.prototype.stop = function () {
  108111. this._isRunning = false;
  108112. };
  108113. /**
  108114. * Reset the optimizer to initial step (current priority level = 0)
  108115. */
  108116. SceneOptimizer.prototype.reset = function () {
  108117. this._currentPriorityLevel = 0;
  108118. };
  108119. /**
  108120. * Start the optimizer. By default it will try to reach a specific framerate
  108121. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  108122. */
  108123. SceneOptimizer.prototype.start = function () {
  108124. var _this = this;
  108125. if (this._isRunning) {
  108126. return;
  108127. }
  108128. this._isRunning = true;
  108129. // Let's wait for the scene to be ready before running our check
  108130. this._scene.executeWhenReady(function () {
  108131. setTimeout(function () {
  108132. _this._checkCurrentState();
  108133. }, _this._trackerDuration);
  108134. });
  108135. };
  108136. SceneOptimizer.prototype._checkCurrentState = function () {
  108137. var _this = this;
  108138. if (!this._isRunning) {
  108139. return;
  108140. }
  108141. var scene = this._scene;
  108142. var options = this._options;
  108143. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  108144. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  108145. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  108146. this._isRunning = false;
  108147. this.onSuccessObservable.notifyObservers(this);
  108148. return;
  108149. }
  108150. // Apply current level of optimizations
  108151. var allDone = true;
  108152. var noOptimizationApplied = true;
  108153. for (var index = 0; index < options.optimizations.length; index++) {
  108154. var optimization = options.optimizations[index];
  108155. if (optimization.priority === this._currentPriorityLevel) {
  108156. noOptimizationApplied = false;
  108157. allDone = allDone && optimization.apply(scene, this);
  108158. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  108159. }
  108160. }
  108161. // If no optimization was applied, this is a failure :(
  108162. if (noOptimizationApplied) {
  108163. this._isRunning = false;
  108164. this.onFailureObservable.notifyObservers(this);
  108165. return;
  108166. }
  108167. // If all optimizations were done, move to next level
  108168. if (allDone) {
  108169. this._currentPriorityLevel++;
  108170. }
  108171. // Let's the system running for a specific amount of time before checking FPS
  108172. scene.executeWhenReady(function () {
  108173. setTimeout(function () {
  108174. _this._checkCurrentState();
  108175. }, _this._trackerDuration);
  108176. });
  108177. };
  108178. /**
  108179. * Release all resources
  108180. */
  108181. SceneOptimizer.prototype.dispose = function () {
  108182. this.stop();
  108183. this.onSuccessObservable.clear();
  108184. this.onFailureObservable.clear();
  108185. this.onNewOptimizationAppliedObservable.clear();
  108186. if (this._sceneDisposeObserver) {
  108187. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  108188. }
  108189. };
  108190. /**
  108191. * Helper function to create a SceneOptimizer with one single line of code
  108192. * @param scene defines the scene to work on
  108193. * @param options defines the options to use with the SceneOptimizer
  108194. * @param onSuccess defines a callback to call on success
  108195. * @param onFailure defines a callback to call on failure
  108196. * @returns the new SceneOptimizer object
  108197. */
  108198. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  108199. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  108200. if (onSuccess) {
  108201. optimizer.onSuccessObservable.add(function () {
  108202. onSuccess();
  108203. });
  108204. }
  108205. if (onFailure) {
  108206. optimizer.onFailureObservable.add(function () {
  108207. onFailure();
  108208. });
  108209. }
  108210. optimizer.start();
  108211. return optimizer;
  108212. };
  108213. return SceneOptimizer;
  108214. }());
  108215. BABYLON.SceneOptimizer = SceneOptimizer;
  108216. })(BABYLON || (BABYLON = {}));
  108217. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  108218. var BABYLON;
  108219. (function (BABYLON) {
  108220. /**
  108221. * Gets the outline renderer associated with the scene
  108222. * @returns a OutlineRenderer
  108223. */
  108224. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  108225. if (!this._outlineRenderer) {
  108226. this._outlineRenderer = new OutlineRenderer(this);
  108227. }
  108228. return this._outlineRenderer;
  108229. };
  108230. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  108231. get: function () {
  108232. return this._renderOutline;
  108233. },
  108234. set: function (value) {
  108235. if (value) {
  108236. // Lazy Load the component.
  108237. this.getScene().getOutlineRenderer();
  108238. }
  108239. this._renderOutline = value;
  108240. },
  108241. enumerable: true,
  108242. configurable: true
  108243. });
  108244. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  108245. get: function () {
  108246. return this._renderOverlay;
  108247. },
  108248. set: function (value) {
  108249. if (value) {
  108250. // Lazy Load the component.
  108251. this.getScene().getOutlineRenderer();
  108252. }
  108253. this._renderOverlay = value;
  108254. },
  108255. enumerable: true,
  108256. configurable: true
  108257. });
  108258. /**
  108259. * This class is responsible to draw bothe outline/overlay of meshes.
  108260. * It should not be used directly but through the available method on mesh.
  108261. */
  108262. var OutlineRenderer = /** @class */ (function () {
  108263. /**
  108264. * Instantiates a new outline renderer. (There could be only one per scene).
  108265. * @param scene Defines the scene it belongs to
  108266. */
  108267. function OutlineRenderer(scene) {
  108268. /**
  108269. * The name of the component. Each component must have a unique name.
  108270. */
  108271. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  108272. /**
  108273. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  108274. */
  108275. this.zOffset = 1;
  108276. this.scene = scene;
  108277. this._engine = scene.getEngine();
  108278. this.scene._addComponent(this);
  108279. }
  108280. /**
  108281. * Register the component to one instance of a scene.
  108282. */
  108283. OutlineRenderer.prototype.register = function () {
  108284. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  108285. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  108286. };
  108287. /**
  108288. * Rebuilds the elements related to this component in case of
  108289. * context lost for instance.
  108290. */
  108291. OutlineRenderer.prototype.rebuild = function () {
  108292. // Nothing to do here.
  108293. };
  108294. /**
  108295. * Disposes the component and the associated ressources.
  108296. */
  108297. OutlineRenderer.prototype.dispose = function () {
  108298. // Nothing to do here.
  108299. };
  108300. /**
  108301. * Renders the outline in the canvas.
  108302. * @param subMesh Defines the sumesh to render
  108303. * @param batch Defines the batch of meshes in case of instances
  108304. * @param useOverlay Defines if the rendering is for the overlay or the outline
  108305. */
  108306. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  108307. var _this = this;
  108308. if (useOverlay === void 0) { useOverlay = false; }
  108309. var scene = this.scene;
  108310. var engine = scene.getEngine();
  108311. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  108312. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  108313. return;
  108314. }
  108315. var mesh = subMesh.getRenderingMesh();
  108316. var material = subMesh.getMaterial();
  108317. if (!material || !scene.activeCamera) {
  108318. return;
  108319. }
  108320. engine.enableEffect(this._effect);
  108321. // Logarithmic depth
  108322. if (material.useLogarithmicDepth) {
  108323. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  108324. }
  108325. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  108326. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  108327. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  108328. // Bones
  108329. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  108330. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  108331. }
  108332. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  108333. // Alpha test
  108334. if (material && material.needAlphaTesting()) {
  108335. var alphaTexture = material.getAlphaTestTexture();
  108336. if (alphaTexture) {
  108337. this._effect.setTexture("diffuseSampler", alphaTexture);
  108338. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  108339. }
  108340. }
  108341. engine.setZOffset(-this.zOffset);
  108342. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  108343. engine.setZOffset(0);
  108344. };
  108345. /**
  108346. * Returns whether or not the outline renderer is ready for a given submesh.
  108347. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  108348. * @param subMesh Defines the submesh to check readyness for
  108349. * @param useInstances Defines wheter wee are trying to render instances or not
  108350. * @returns true if ready otherwise false
  108351. */
  108352. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  108353. var defines = [];
  108354. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  108355. var mesh = subMesh.getMesh();
  108356. var material = subMesh.getMaterial();
  108357. if (material) {
  108358. // Alpha test
  108359. if (material.needAlphaTesting()) {
  108360. defines.push("#define ALPHATEST");
  108361. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  108362. attribs.push(BABYLON.VertexBuffer.UVKind);
  108363. defines.push("#define UV1");
  108364. }
  108365. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  108366. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  108367. defines.push("#define UV2");
  108368. }
  108369. }
  108370. //Logarithmic depth
  108371. if (material.useLogarithmicDepth) {
  108372. defines.push("#define LOGARITHMICDEPTH");
  108373. }
  108374. }
  108375. // Bones
  108376. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  108377. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  108378. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  108379. if (mesh.numBoneInfluencers > 4) {
  108380. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  108381. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  108382. }
  108383. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  108384. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  108385. }
  108386. else {
  108387. defines.push("#define NUM_BONE_INFLUENCERS 0");
  108388. }
  108389. // Instances
  108390. if (useInstances) {
  108391. defines.push("#define INSTANCES");
  108392. attribs.push("world0");
  108393. attribs.push("world1");
  108394. attribs.push("world2");
  108395. attribs.push("world3");
  108396. }
  108397. // Get correct effect
  108398. var join = defines.join("\n");
  108399. if (this._cachedDefines !== join) {
  108400. this._cachedDefines = join;
  108401. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  108402. }
  108403. return this._effect.isReady();
  108404. };
  108405. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  108406. // Outline - step 1
  108407. this._savedDepthWrite = this._engine.getDepthWrite();
  108408. if (mesh.renderOutline) {
  108409. this._engine.setDepthWrite(false);
  108410. this.render(subMesh, batch);
  108411. this._engine.setDepthWrite(this._savedDepthWrite);
  108412. }
  108413. };
  108414. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  108415. // Outline - step 2
  108416. if (mesh.renderOutline && this._savedDepthWrite) {
  108417. this._engine.setDepthWrite(true);
  108418. this._engine.setColorWrite(false);
  108419. this.render(subMesh, batch);
  108420. this._engine.setColorWrite(true);
  108421. }
  108422. // Overlay
  108423. if (mesh.renderOverlay) {
  108424. var currentMode = this._engine.getAlphaMode();
  108425. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  108426. this.render(subMesh, batch, true);
  108427. this._engine.setAlphaMode(currentMode);
  108428. }
  108429. };
  108430. return OutlineRenderer;
  108431. }());
  108432. BABYLON.OutlineRenderer = OutlineRenderer;
  108433. })(BABYLON || (BABYLON = {}));
  108434. //# sourceMappingURL=babylon.outlineRenderer.js.map
  108435. var BABYLON;
  108436. (function (BABYLON) {
  108437. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  108438. if (this._edgesRenderer) {
  108439. this._edgesRenderer.dispose();
  108440. this._edgesRenderer = null;
  108441. }
  108442. return this;
  108443. };
  108444. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  108445. if (epsilon === void 0) { epsilon = 0.95; }
  108446. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108447. this.disableEdgesRendering();
  108448. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  108449. return this;
  108450. };
  108451. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  108452. get: function () {
  108453. return this._edgesRenderer;
  108454. },
  108455. enumerable: true,
  108456. configurable: true
  108457. });
  108458. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  108459. if (epsilon === void 0) { epsilon = 0.95; }
  108460. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108461. this.disableEdgesRendering();
  108462. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  108463. return this;
  108464. };
  108465. /**
  108466. * FaceAdjacencies Helper class to generate edges
  108467. */
  108468. var FaceAdjacencies = /** @class */ (function () {
  108469. function FaceAdjacencies() {
  108470. this.edges = new Array();
  108471. this.edgesConnectedCount = 0;
  108472. }
  108473. return FaceAdjacencies;
  108474. }());
  108475. /**
  108476. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  108477. */
  108478. var EdgesRenderer = /** @class */ (function () {
  108479. /**
  108480. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  108481. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  108482. * @param source Mesh used to create edges
  108483. * @param epsilon sum of angles in adjacency to check for edge
  108484. * @param checkVerticesInsteadOfIndices
  108485. * @param generateEdgesLines - should generate Lines or only prepare resources.
  108486. */
  108487. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  108488. if (epsilon === void 0) { epsilon = 0.95; }
  108489. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108490. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  108491. var _this = this;
  108492. /**
  108493. * Define the size of the edges with an orthographic camera
  108494. */
  108495. this.edgesWidthScalerForOrthographic = 1000.0;
  108496. /**
  108497. * Define the size of the edges with a perspective camera
  108498. */
  108499. this.edgesWidthScalerForPerspective = 50.0;
  108500. this._linesPositions = new Array();
  108501. this._linesNormals = new Array();
  108502. this._linesIndices = new Array();
  108503. this._buffers = {};
  108504. this._checkVerticesInsteadOfIndices = false;
  108505. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  108506. this.isEnabled = true;
  108507. this._source = source;
  108508. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  108509. this._epsilon = epsilon;
  108510. this._prepareRessources();
  108511. if (generateEdgesLines) {
  108512. this._generateEdgesLines();
  108513. }
  108514. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  108515. _this._rebuild();
  108516. });
  108517. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  108518. _this.dispose();
  108519. });
  108520. }
  108521. EdgesRenderer.prototype._prepareRessources = function () {
  108522. if (this._lineShader) {
  108523. return;
  108524. }
  108525. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  108526. attributes: ["position", "normal"],
  108527. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  108528. });
  108529. this._lineShader.disableDepthWrite = true;
  108530. this._lineShader.backFaceCulling = false;
  108531. };
  108532. /** @hidden */
  108533. EdgesRenderer.prototype._rebuild = function () {
  108534. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  108535. if (buffer) {
  108536. buffer._rebuild();
  108537. }
  108538. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  108539. if (buffer) {
  108540. buffer._rebuild();
  108541. }
  108542. var scene = this._source.getScene();
  108543. var engine = scene.getEngine();
  108544. this._ib = engine.createIndexBuffer(this._linesIndices);
  108545. };
  108546. /**
  108547. * Releases the required resources for the edges renderer
  108548. */
  108549. EdgesRenderer.prototype.dispose = function () {
  108550. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  108551. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  108552. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  108553. if (buffer) {
  108554. buffer.dispose();
  108555. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  108556. }
  108557. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  108558. if (buffer) {
  108559. buffer.dispose();
  108560. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  108561. }
  108562. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  108563. this._lineShader.dispose();
  108564. };
  108565. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  108566. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  108567. return 0;
  108568. }
  108569. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  108570. return 1;
  108571. }
  108572. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  108573. return 2;
  108574. }
  108575. return -1;
  108576. };
  108577. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  108578. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  108579. return 0;
  108580. }
  108581. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  108582. return 1;
  108583. }
  108584. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  108585. return 2;
  108586. }
  108587. return -1;
  108588. };
  108589. /**
  108590. * Checks if the pair of p0 and p1 is en edge
  108591. * @param faceIndex
  108592. * @param edge
  108593. * @param faceNormals
  108594. * @param p0
  108595. * @param p1
  108596. * @private
  108597. */
  108598. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  108599. var needToCreateLine;
  108600. if (edge === undefined) {
  108601. needToCreateLine = true;
  108602. }
  108603. else {
  108604. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  108605. needToCreateLine = dotProduct < this._epsilon;
  108606. }
  108607. if (needToCreateLine) {
  108608. var offset = this._linesPositions.length / 3;
  108609. var normal = p0.subtract(p1);
  108610. normal.normalize();
  108611. // Positions
  108612. this._linesPositions.push(p0.x);
  108613. this._linesPositions.push(p0.y);
  108614. this._linesPositions.push(p0.z);
  108615. this._linesPositions.push(p0.x);
  108616. this._linesPositions.push(p0.y);
  108617. this._linesPositions.push(p0.z);
  108618. this._linesPositions.push(p1.x);
  108619. this._linesPositions.push(p1.y);
  108620. this._linesPositions.push(p1.z);
  108621. this._linesPositions.push(p1.x);
  108622. this._linesPositions.push(p1.y);
  108623. this._linesPositions.push(p1.z);
  108624. // Normals
  108625. this._linesNormals.push(p1.x);
  108626. this._linesNormals.push(p1.y);
  108627. this._linesNormals.push(p1.z);
  108628. this._linesNormals.push(-1);
  108629. this._linesNormals.push(p1.x);
  108630. this._linesNormals.push(p1.y);
  108631. this._linesNormals.push(p1.z);
  108632. this._linesNormals.push(1);
  108633. this._linesNormals.push(p0.x);
  108634. this._linesNormals.push(p0.y);
  108635. this._linesNormals.push(p0.z);
  108636. this._linesNormals.push(-1);
  108637. this._linesNormals.push(p0.x);
  108638. this._linesNormals.push(p0.y);
  108639. this._linesNormals.push(p0.z);
  108640. this._linesNormals.push(1);
  108641. // Indices
  108642. this._linesIndices.push(offset);
  108643. this._linesIndices.push(offset + 1);
  108644. this._linesIndices.push(offset + 2);
  108645. this._linesIndices.push(offset);
  108646. this._linesIndices.push(offset + 2);
  108647. this._linesIndices.push(offset + 3);
  108648. }
  108649. };
  108650. /**
  108651. * Generates lines edges from adjacencjes
  108652. * @private
  108653. */
  108654. EdgesRenderer.prototype._generateEdgesLines = function () {
  108655. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  108656. var indices = this._source.getIndices();
  108657. if (!indices || !positions) {
  108658. return;
  108659. }
  108660. // First let's find adjacencies
  108661. var adjacencies = new Array();
  108662. var faceNormals = new Array();
  108663. var index;
  108664. var faceAdjacencies;
  108665. // Prepare faces
  108666. for (index = 0; index < indices.length; index += 3) {
  108667. faceAdjacencies = new FaceAdjacencies();
  108668. var p0Index = indices[index];
  108669. var p1Index = indices[index + 1];
  108670. var p2Index = indices[index + 2];
  108671. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  108672. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  108673. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  108674. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  108675. faceNormal.normalize();
  108676. faceNormals.push(faceNormal);
  108677. adjacencies.push(faceAdjacencies);
  108678. }
  108679. // Scan
  108680. for (index = 0; index < adjacencies.length; index++) {
  108681. faceAdjacencies = adjacencies[index];
  108682. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  108683. var otherFaceAdjacencies = adjacencies[otherIndex];
  108684. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  108685. break;
  108686. }
  108687. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  108688. continue;
  108689. }
  108690. var otherP0 = indices[otherIndex * 3];
  108691. var otherP1 = indices[otherIndex * 3 + 1];
  108692. var otherP2 = indices[otherIndex * 3 + 2];
  108693. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  108694. var otherEdgeIndex = 0;
  108695. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  108696. continue;
  108697. }
  108698. switch (edgeIndex) {
  108699. case 0:
  108700. if (this._checkVerticesInsteadOfIndices) {
  108701. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  108702. }
  108703. else {
  108704. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  108705. }
  108706. break;
  108707. case 1:
  108708. if (this._checkVerticesInsteadOfIndices) {
  108709. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  108710. }
  108711. else {
  108712. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  108713. }
  108714. break;
  108715. case 2:
  108716. if (this._checkVerticesInsteadOfIndices) {
  108717. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  108718. }
  108719. else {
  108720. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  108721. }
  108722. break;
  108723. }
  108724. if (otherEdgeIndex === -1) {
  108725. continue;
  108726. }
  108727. faceAdjacencies.edges[edgeIndex] = otherIndex;
  108728. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  108729. faceAdjacencies.edgesConnectedCount++;
  108730. otherFaceAdjacencies.edgesConnectedCount++;
  108731. if (faceAdjacencies.edgesConnectedCount === 3) {
  108732. break;
  108733. }
  108734. }
  108735. }
  108736. }
  108737. // Create lines
  108738. for (index = 0; index < adjacencies.length; index++) {
  108739. // 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
  108740. var current = adjacencies[index];
  108741. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  108742. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  108743. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  108744. }
  108745. // Merge into a single mesh
  108746. var engine = this._source.getScene().getEngine();
  108747. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  108748. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  108749. this._ib = engine.createIndexBuffer(this._linesIndices);
  108750. this._indicesCount = this._linesIndices.length;
  108751. };
  108752. /**
  108753. * Checks wether or not the edges renderer is ready to render.
  108754. * @return true if ready, otherwise false.
  108755. */
  108756. EdgesRenderer.prototype.isReady = function () {
  108757. return this._lineShader.isReady();
  108758. };
  108759. /**
  108760. * Renders the edges of the attached mesh,
  108761. */
  108762. EdgesRenderer.prototype.render = function () {
  108763. var scene = this._source.getScene();
  108764. if (!this.isReady() || !scene.activeCamera) {
  108765. return;
  108766. }
  108767. var engine = scene.getEngine();
  108768. this._lineShader._preBind();
  108769. if (this._source.edgesColor.a !== 1) {
  108770. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  108771. }
  108772. else {
  108773. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  108774. }
  108775. // VBOs
  108776. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  108777. scene.resetCachedMaterial();
  108778. this._lineShader.setColor4("color", this._source.edgesColor);
  108779. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  108780. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  108781. }
  108782. else {
  108783. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  108784. }
  108785. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  108786. this._lineShader.bind(this._source.getWorldMatrix());
  108787. // Draw order
  108788. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  108789. this._lineShader.unbind();
  108790. };
  108791. return EdgesRenderer;
  108792. }());
  108793. BABYLON.EdgesRenderer = EdgesRenderer;
  108794. })(BABYLON || (BABYLON = {}));
  108795. //# sourceMappingURL=babylon.edgesRenderer.js.map
  108796. var BABYLON;
  108797. (function (BABYLON) {
  108798. /**
  108799. * FaceAdjacencies Helper class to generate edges
  108800. */
  108801. var FaceAdjacencies = /** @class */ (function () {
  108802. function FaceAdjacencies() {
  108803. this.edges = new Array();
  108804. this.edgesConnectedCount = 0;
  108805. }
  108806. return FaceAdjacencies;
  108807. }());
  108808. /**
  108809. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  108810. */
  108811. var LineEdgesRenderer = /** @class */ (function (_super) {
  108812. __extends(LineEdgesRenderer, _super);
  108813. /**
  108814. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  108815. * @param source LineMesh used to generate edges
  108816. * @param epsilon not important (specified angle for edge detection)
  108817. * @param checkVerticesInsteadOfIndices not important for LineMesh
  108818. */
  108819. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  108820. if (epsilon === void 0) { epsilon = 0.95; }
  108821. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108822. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  108823. _this._generateEdgesLines();
  108824. return _this;
  108825. }
  108826. /**
  108827. * Always create the edge since its a line so only important things are p0 and p1
  108828. * @param faceIndex not important for LineMesh
  108829. * @param edge not important for LineMesh
  108830. * @param faceNormals not important for LineMesh
  108831. * @param p0 beginnig of line
  108832. * @param p1 end of line
  108833. */
  108834. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  108835. var offset = this._linesPositions.length / 3;
  108836. var normal = p0.subtract(p1);
  108837. normal.normalize();
  108838. // Positions
  108839. this._linesPositions.push(p0.x);
  108840. this._linesPositions.push(p0.y);
  108841. this._linesPositions.push(p0.z);
  108842. this._linesPositions.push(p0.x);
  108843. this._linesPositions.push(p0.y);
  108844. this._linesPositions.push(p0.z);
  108845. this._linesPositions.push(p1.x);
  108846. this._linesPositions.push(p1.y);
  108847. this._linesPositions.push(p1.z);
  108848. this._linesPositions.push(p1.x);
  108849. this._linesPositions.push(p1.y);
  108850. this._linesPositions.push(p1.z);
  108851. // Normals
  108852. this._linesNormals.push(p1.x);
  108853. this._linesNormals.push(p1.y);
  108854. this._linesNormals.push(p1.z);
  108855. this._linesNormals.push(-1);
  108856. this._linesNormals.push(p1.x);
  108857. this._linesNormals.push(p1.y);
  108858. this._linesNormals.push(p1.z);
  108859. this._linesNormals.push(1);
  108860. this._linesNormals.push(p0.x);
  108861. this._linesNormals.push(p0.y);
  108862. this._linesNormals.push(p0.z);
  108863. this._linesNormals.push(-1);
  108864. this._linesNormals.push(p0.x);
  108865. this._linesNormals.push(p0.y);
  108866. this._linesNormals.push(p0.z);
  108867. this._linesNormals.push(1);
  108868. // Indices
  108869. this._linesIndices.push(offset);
  108870. this._linesIndices.push(offset + 1);
  108871. this._linesIndices.push(offset + 2);
  108872. this._linesIndices.push(offset);
  108873. this._linesIndices.push(offset + 2);
  108874. this._linesIndices.push(offset + 3);
  108875. };
  108876. /**
  108877. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  108878. */
  108879. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  108880. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  108881. var indices = this._source.getIndices();
  108882. if (!indices || !positions) {
  108883. return;
  108884. }
  108885. // First let's find adjacencies
  108886. var adjacencies = new Array();
  108887. var faceNormals = new Array();
  108888. var index;
  108889. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  108890. var currentAdjecancy = new FaceAdjacencies();
  108891. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  108892. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  108893. adjacencies.push(currentAdjecancy);
  108894. }
  108895. // Create lines
  108896. for (index = 0; index < adjacencies.length; index++) {
  108897. // 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
  108898. var current = adjacencies[index];
  108899. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  108900. }
  108901. // Merge into a single mesh
  108902. var engine = this._source.getScene().getEngine();
  108903. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  108904. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  108905. this._ib = engine.createIndexBuffer(this._linesIndices);
  108906. this._indicesCount = this._linesIndices.length;
  108907. };
  108908. return LineEdgesRenderer;
  108909. }(BABYLON.EdgesRenderer));
  108910. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  108911. })(BABYLON || (BABYLON = {}));
  108912. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  108913. var BABYLON;
  108914. (function (BABYLON) {
  108915. // Adds the parser to the scene parsers.
  108916. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  108917. if (parsedData.effectLayers) {
  108918. if (!container.effectLayers) {
  108919. container.effectLayers = new Array();
  108920. }
  108921. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  108922. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  108923. container.effectLayers.push(effectLayer);
  108924. }
  108925. }
  108926. });
  108927. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  108928. var index = this.effectLayers.indexOf(toRemove);
  108929. if (index !== -1) {
  108930. this.effectLayers.splice(index, 1);
  108931. }
  108932. return index;
  108933. };
  108934. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  108935. this.effectLayers.push(newEffectLayer);
  108936. };
  108937. /**
  108938. * Defines the layer scene component responsible to manage any effect layers
  108939. * in a given scene.
  108940. */
  108941. var EffectLayerSceneComponent = /** @class */ (function () {
  108942. /**
  108943. * Creates a new instance of the component for the given scene
  108944. * @param scene Defines the scene to register the component in
  108945. */
  108946. function EffectLayerSceneComponent(scene) {
  108947. /**
  108948. * The component name helpfull to identify the component in the list of scene components.
  108949. */
  108950. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  108951. this._renderEffects = false;
  108952. this._needStencil = false;
  108953. this._previousStencilState = false;
  108954. this.scene = scene;
  108955. this._engine = scene.getEngine();
  108956. scene.effectLayers = new Array();
  108957. }
  108958. /**
  108959. * Registers the component in a given scene
  108960. */
  108961. EffectLayerSceneComponent.prototype.register = function () {
  108962. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  108963. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  108964. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  108965. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  108966. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  108967. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  108968. };
  108969. /**
  108970. * Rebuilds the elements related to this component in case of
  108971. * context lost for instance.
  108972. */
  108973. EffectLayerSceneComponent.prototype.rebuild = function () {
  108974. var layers = this.scene.effectLayers;
  108975. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  108976. var effectLayer = layers_1[_i];
  108977. effectLayer._rebuild();
  108978. }
  108979. };
  108980. /**
  108981. * Serializes the component data to the specified json object
  108982. * @param serializationObject The object to serialize to
  108983. */
  108984. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  108985. // Effect layers
  108986. serializationObject.effectLayers = [];
  108987. var layers = this.scene.effectLayers;
  108988. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  108989. var effectLayer = layers_2[_i];
  108990. if (effectLayer.serialize) {
  108991. serializationObject.effectLayers.push(effectLayer.serialize());
  108992. }
  108993. }
  108994. };
  108995. /**
  108996. * Adds all the element from the container to the scene
  108997. * @param container the container holding the elements
  108998. */
  108999. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  109000. var _this = this;
  109001. if (!container.effectLayers) {
  109002. return;
  109003. }
  109004. container.effectLayers.forEach(function (o) {
  109005. _this.scene.addEffectLayer(o);
  109006. });
  109007. };
  109008. /**
  109009. * Removes all the elements in the container from the scene
  109010. * @param container contains the elements to remove
  109011. */
  109012. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  109013. var _this = this;
  109014. if (!container.effectLayers) {
  109015. return;
  109016. }
  109017. container.effectLayers.forEach(function (o) {
  109018. _this.scene.removeEffectLayer(o);
  109019. });
  109020. };
  109021. /**
  109022. * Disposes the component and the associated ressources.
  109023. */
  109024. EffectLayerSceneComponent.prototype.dispose = function () {
  109025. var layers = this.scene.effectLayers;
  109026. while (layers.length) {
  109027. layers[0].dispose();
  109028. }
  109029. };
  109030. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  109031. var layers = this.scene.effectLayers;
  109032. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  109033. var layer = layers_3[_i];
  109034. if (!layer.hasMesh(mesh)) {
  109035. continue;
  109036. }
  109037. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  109038. var subMesh = _b[_a];
  109039. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  109040. return false;
  109041. }
  109042. }
  109043. }
  109044. return true;
  109045. };
  109046. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  109047. this._renderEffects = false;
  109048. this._needStencil = false;
  109049. var layers = this.scene.effectLayers;
  109050. if (layers && layers.length > 0) {
  109051. this._previousStencilState = this._engine.getStencilBuffer();
  109052. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  109053. var effectLayer = layers_4[_i];
  109054. if (effectLayer.shouldRender() &&
  109055. (!effectLayer.camera ||
  109056. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  109057. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  109058. this._renderEffects = true;
  109059. this._needStencil = this._needStencil || effectLayer.needStencil();
  109060. var renderTarget = effectLayer._mainTexture;
  109061. if (renderTarget._shouldRender()) {
  109062. this.scene.incrementRenderId();
  109063. renderTarget.render(false, false);
  109064. }
  109065. }
  109066. }
  109067. this.scene.incrementRenderId();
  109068. }
  109069. };
  109070. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  109071. // Activate effect Layer stencil
  109072. if (this._needStencil) {
  109073. this._engine.setStencilBuffer(true);
  109074. }
  109075. };
  109076. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  109077. // Restore effect Layer stencil
  109078. if (this._needStencil) {
  109079. this._engine.setStencilBuffer(this._previousStencilState);
  109080. }
  109081. };
  109082. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  109083. if (this._renderEffects) {
  109084. this._engine.setDepthBuffer(false);
  109085. var layers = this.scene.effectLayers;
  109086. for (var i = 0; i < layers.length; i++) {
  109087. var effectLayer = layers[i];
  109088. if (effectLayer.renderingGroupId === renderingGroupId) {
  109089. if (effectLayer.shouldRender()) {
  109090. effectLayer.render();
  109091. }
  109092. }
  109093. }
  109094. this._engine.setDepthBuffer(true);
  109095. }
  109096. };
  109097. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  109098. if (this._renderEffects) {
  109099. this._draw(-1);
  109100. }
  109101. };
  109102. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  109103. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  109104. this._draw(index);
  109105. }
  109106. };
  109107. return EffectLayerSceneComponent;
  109108. }());
  109109. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  109110. })(BABYLON || (BABYLON = {}));
  109111. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  109112. var __assign = (this && this.__assign) || function () {
  109113. __assign = Object.assign || function(t) {
  109114. for (var s, i = 1, n = arguments.length; i < n; i++) {
  109115. s = arguments[i];
  109116. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  109117. t[p] = s[p];
  109118. }
  109119. return t;
  109120. };
  109121. return __assign.apply(this, arguments);
  109122. };
  109123. var BABYLON;
  109124. (function (BABYLON) {
  109125. /**
  109126. * The effect layer Helps adding post process effect blended with the main pass.
  109127. *
  109128. * This can be for instance use to generate glow or higlight effects on the scene.
  109129. *
  109130. * The effect layer class can not be used directly and is intented to inherited from to be
  109131. * customized per effects.
  109132. */
  109133. var EffectLayer = /** @class */ (function () {
  109134. /**
  109135. * Instantiates a new effect Layer and references it in the scene.
  109136. * @param name The name of the layer
  109137. * @param scene The scene to use the layer in
  109138. */
  109139. function EffectLayer(
  109140. /** The Friendly of the effect in the scene */
  109141. name, scene) {
  109142. this._vertexBuffers = {};
  109143. this._maxSize = 0;
  109144. this._mainTextureDesiredSize = { width: 0, height: 0 };
  109145. this._shouldRender = true;
  109146. this._postProcesses = [];
  109147. this._textures = [];
  109148. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  109149. /**
  109150. * The clear color of the texture used to generate the glow map.
  109151. */
  109152. this.neutralColor = new BABYLON.Color4();
  109153. /**
  109154. * Specifies wether the highlight layer is enabled or not.
  109155. */
  109156. this.isEnabled = true;
  109157. /**
  109158. * An event triggered when the effect layer has been disposed.
  109159. */
  109160. this.onDisposeObservable = new BABYLON.Observable();
  109161. /**
  109162. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  109163. */
  109164. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  109165. /**
  109166. * An event triggered when the generated texture is being merged in the scene.
  109167. */
  109168. this.onBeforeComposeObservable = new BABYLON.Observable();
  109169. /**
  109170. * An event triggered when the generated texture has been merged in the scene.
  109171. */
  109172. this.onAfterComposeObservable = new BABYLON.Observable();
  109173. /**
  109174. * An event triggered when the efffect layer changes its size.
  109175. */
  109176. this.onSizeChangedObservable = new BABYLON.Observable();
  109177. this.name = name;
  109178. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  109179. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  109180. if (!component) {
  109181. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  109182. this._scene._addComponent(component);
  109183. }
  109184. this._engine = this._scene.getEngine();
  109185. this._maxSize = this._engine.getCaps().maxTextureSize;
  109186. this._scene.effectLayers.push(this);
  109187. // Generate Buffers
  109188. this._generateIndexBuffer();
  109189. this._genrateVertexBuffer();
  109190. }
  109191. Object.defineProperty(EffectLayer.prototype, "camera", {
  109192. /**
  109193. * Gets the camera attached to the layer.
  109194. */
  109195. get: function () {
  109196. return this._effectLayerOptions.camera;
  109197. },
  109198. enumerable: true,
  109199. configurable: true
  109200. });
  109201. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  109202. /**
  109203. * Gets the rendering group id the layer should render in.
  109204. */
  109205. get: function () {
  109206. return this._effectLayerOptions.renderingGroupId;
  109207. },
  109208. enumerable: true,
  109209. configurable: true
  109210. });
  109211. /**
  109212. * Initializes the effect layer with the required options.
  109213. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  109214. */
  109215. EffectLayer.prototype._init = function (options) {
  109216. // Adapt options
  109217. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  109218. this._setMainTextureSize();
  109219. this._createMainTexture();
  109220. this._createTextureAndPostProcesses();
  109221. this._mergeEffect = this._createMergeEffect();
  109222. };
  109223. /**
  109224. * Generates the index buffer of the full screen quad blending to the main canvas.
  109225. */
  109226. EffectLayer.prototype._generateIndexBuffer = function () {
  109227. // Indices
  109228. var indices = [];
  109229. indices.push(0);
  109230. indices.push(1);
  109231. indices.push(2);
  109232. indices.push(0);
  109233. indices.push(2);
  109234. indices.push(3);
  109235. this._indexBuffer = this._engine.createIndexBuffer(indices);
  109236. };
  109237. /**
  109238. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  109239. */
  109240. EffectLayer.prototype._genrateVertexBuffer = function () {
  109241. // VBO
  109242. var vertices = [];
  109243. vertices.push(1, 1);
  109244. vertices.push(-1, 1);
  109245. vertices.push(-1, -1);
  109246. vertices.push(1, -1);
  109247. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  109248. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  109249. };
  109250. /**
  109251. * Sets the main texture desired size which is the closest power of two
  109252. * of the engine canvas size.
  109253. */
  109254. EffectLayer.prototype._setMainTextureSize = function () {
  109255. if (this._effectLayerOptions.mainTextureFixedSize) {
  109256. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  109257. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  109258. }
  109259. else {
  109260. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  109261. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  109262. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  109263. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  109264. }
  109265. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  109266. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  109267. };
  109268. /**
  109269. * Creates the main texture for the effect layer.
  109270. */
  109271. EffectLayer.prototype._createMainTexture = function () {
  109272. var _this = this;
  109273. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  109274. width: this._mainTextureDesiredSize.width,
  109275. height: this._mainTextureDesiredSize.height
  109276. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  109277. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  109278. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109279. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109280. this._mainTexture.anisotropicFilteringLevel = 1;
  109281. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  109282. this._mainTexture.renderParticles = false;
  109283. this._mainTexture.renderList = null;
  109284. this._mainTexture.ignoreCameraViewport = true;
  109285. // Custom render function
  109286. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  109287. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  109288. var index;
  109289. var engine = _this._scene.getEngine();
  109290. if (depthOnlySubMeshes.length) {
  109291. engine.setColorWrite(false);
  109292. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  109293. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  109294. }
  109295. engine.setColorWrite(true);
  109296. }
  109297. for (index = 0; index < opaqueSubMeshes.length; index++) {
  109298. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  109299. }
  109300. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  109301. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  109302. }
  109303. for (index = 0; index < transparentSubMeshes.length; index++) {
  109304. _this._renderSubMesh(transparentSubMeshes.data[index]);
  109305. }
  109306. };
  109307. this._mainTexture.onClearObservable.add(function (engine) {
  109308. engine.clear(_this.neutralColor, true, true, true);
  109309. });
  109310. };
  109311. /**
  109312. * Checks for the readiness of the element composing the layer.
  109313. * @param subMesh the mesh to check for
  109314. * @param useInstances specify wether or not to use instances to render the mesh
  109315. * @param emissiveTexture the associated emissive texture used to generate the glow
  109316. * @return true if ready otherwise, false
  109317. */
  109318. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  109319. var material = subMesh.getMaterial();
  109320. if (!material) {
  109321. return false;
  109322. }
  109323. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  109324. return false;
  109325. }
  109326. var defines = [];
  109327. var attribs = [BABYLON.VertexBuffer.PositionKind];
  109328. var mesh = subMesh.getMesh();
  109329. var uv1 = false;
  109330. var uv2 = false;
  109331. // Alpha test
  109332. if (material && material.needAlphaTesting()) {
  109333. var alphaTexture = material.getAlphaTestTexture();
  109334. if (alphaTexture) {
  109335. defines.push("#define ALPHATEST");
  109336. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  109337. alphaTexture.coordinatesIndex === 1) {
  109338. defines.push("#define DIFFUSEUV2");
  109339. uv2 = true;
  109340. }
  109341. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  109342. defines.push("#define DIFFUSEUV1");
  109343. uv1 = true;
  109344. }
  109345. }
  109346. }
  109347. // Emissive
  109348. if (emissiveTexture) {
  109349. defines.push("#define EMISSIVE");
  109350. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  109351. emissiveTexture.coordinatesIndex === 1) {
  109352. defines.push("#define EMISSIVEUV2");
  109353. uv2 = true;
  109354. }
  109355. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  109356. defines.push("#define EMISSIVEUV1");
  109357. uv1 = true;
  109358. }
  109359. }
  109360. if (uv1) {
  109361. attribs.push(BABYLON.VertexBuffer.UVKind);
  109362. defines.push("#define UV1");
  109363. }
  109364. if (uv2) {
  109365. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  109366. defines.push("#define UV2");
  109367. }
  109368. // Bones
  109369. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  109370. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  109371. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  109372. if (mesh.numBoneInfluencers > 4) {
  109373. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  109374. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  109375. }
  109376. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  109377. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  109378. }
  109379. else {
  109380. defines.push("#define NUM_BONE_INFLUENCERS 0");
  109381. }
  109382. // Morph targets
  109383. var manager = mesh.morphTargetManager;
  109384. var morphInfluencers = 0;
  109385. if (manager) {
  109386. if (manager.numInfluencers > 0) {
  109387. defines.push("#define MORPHTARGETS");
  109388. morphInfluencers = manager.numInfluencers;
  109389. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  109390. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  109391. }
  109392. }
  109393. // Instances
  109394. if (useInstances) {
  109395. defines.push("#define INSTANCES");
  109396. attribs.push("world0");
  109397. attribs.push("world1");
  109398. attribs.push("world2");
  109399. attribs.push("world3");
  109400. }
  109401. // Get correct effect
  109402. var join = defines.join("\n");
  109403. if (this._cachedDefines !== join) {
  109404. this._cachedDefines = join;
  109405. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  109406. }
  109407. return this._effectLayerMapGenerationEffect.isReady();
  109408. };
  109409. /**
  109410. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  109411. */
  109412. EffectLayer.prototype.render = function () {
  109413. var currentEffect = this._mergeEffect;
  109414. // Check
  109415. if (!currentEffect.isReady()) {
  109416. return;
  109417. }
  109418. for (var i = 0; i < this._postProcesses.length; i++) {
  109419. if (!this._postProcesses[i].isReady()) {
  109420. return;
  109421. }
  109422. }
  109423. var engine = this._scene.getEngine();
  109424. this.onBeforeComposeObservable.notifyObservers(this);
  109425. // Render
  109426. engine.enableEffect(currentEffect);
  109427. engine.setState(false);
  109428. // VBOs
  109429. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  109430. // Cache
  109431. var previousAlphaMode = engine.getAlphaMode();
  109432. // Go Blend.
  109433. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  109434. // Blends the map on the main canvas.
  109435. this._internalRender(currentEffect);
  109436. // Restore Alpha
  109437. engine.setAlphaMode(previousAlphaMode);
  109438. this.onAfterComposeObservable.notifyObservers(this);
  109439. // Handle size changes.
  109440. var size = this._mainTexture.getSize();
  109441. this._setMainTextureSize();
  109442. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  109443. // Recreate RTT and post processes on size change.
  109444. this.onSizeChangedObservable.notifyObservers(this);
  109445. this._disposeTextureAndPostProcesses();
  109446. this._createMainTexture();
  109447. this._createTextureAndPostProcesses();
  109448. }
  109449. };
  109450. /**
  109451. * Determine if a given mesh will be used in the current effect.
  109452. * @param mesh mesh to test
  109453. * @returns true if the mesh will be used
  109454. */
  109455. EffectLayer.prototype.hasMesh = function (mesh) {
  109456. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  109457. return true;
  109458. }
  109459. return false;
  109460. };
  109461. /**
  109462. * Returns true if the layer contains information to display, otherwise false.
  109463. * @returns true if the glow layer should be rendered
  109464. */
  109465. EffectLayer.prototype.shouldRender = function () {
  109466. return this.isEnabled && this._shouldRender;
  109467. };
  109468. /**
  109469. * Returns true if the mesh should render, otherwise false.
  109470. * @param mesh The mesh to render
  109471. * @returns true if it should render otherwise false
  109472. */
  109473. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  109474. return true;
  109475. };
  109476. /**
  109477. * Returns true if the mesh should render, otherwise false.
  109478. * @param mesh The mesh to render
  109479. * @returns true if it should render otherwise false
  109480. */
  109481. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  109482. return true;
  109483. };
  109484. /**
  109485. * Renders the submesh passed in parameter to the generation map.
  109486. */
  109487. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  109488. var _this = this;
  109489. if (!this.shouldRender()) {
  109490. return;
  109491. }
  109492. var material = subMesh.getMaterial();
  109493. var mesh = subMesh.getRenderingMesh();
  109494. var scene = this._scene;
  109495. var engine = scene.getEngine();
  109496. if (!material) {
  109497. return;
  109498. }
  109499. // Do not block in blend mode.
  109500. if (material.needAlphaBlendingForMesh(mesh)) {
  109501. return;
  109502. }
  109503. // Culling
  109504. engine.setState(material.backFaceCulling);
  109505. // Managing instances
  109506. var batch = mesh._getInstancesRenderList(subMesh._id);
  109507. if (batch.mustReturn) {
  109508. return;
  109509. }
  109510. // Early Exit per mesh
  109511. if (!this._shouldRenderMesh(mesh)) {
  109512. return;
  109513. }
  109514. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  109515. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  109516. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  109517. engine.enableEffect(this._effectLayerMapGenerationEffect);
  109518. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  109519. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  109520. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  109521. // Alpha test
  109522. if (material && material.needAlphaTesting()) {
  109523. var alphaTexture = material.getAlphaTestTexture();
  109524. if (alphaTexture) {
  109525. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  109526. var textureMatrix = alphaTexture.getTextureMatrix();
  109527. if (textureMatrix) {
  109528. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  109529. }
  109530. }
  109531. }
  109532. // Glow emissive only
  109533. if (this._emissiveTextureAndColor.texture) {
  109534. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  109535. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  109536. }
  109537. // Bones
  109538. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  109539. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  109540. }
  109541. // Morph targets
  109542. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  109543. // Draw
  109544. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  109545. }
  109546. else {
  109547. // Need to reset refresh rate of the main map
  109548. this._mainTexture.resetRefreshCounter();
  109549. }
  109550. };
  109551. /**
  109552. * Rebuild the required buffers.
  109553. * @hidden Internal use only.
  109554. */
  109555. EffectLayer.prototype._rebuild = function () {
  109556. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  109557. if (vb) {
  109558. vb._rebuild();
  109559. }
  109560. this._generateIndexBuffer();
  109561. };
  109562. /**
  109563. * Dispose only the render target textures and post process.
  109564. */
  109565. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  109566. this._mainTexture.dispose();
  109567. for (var i = 0; i < this._postProcesses.length; i++) {
  109568. if (this._postProcesses[i]) {
  109569. this._postProcesses[i].dispose();
  109570. }
  109571. }
  109572. this._postProcesses = [];
  109573. for (var i = 0; i < this._textures.length; i++) {
  109574. if (this._textures[i]) {
  109575. this._textures[i].dispose();
  109576. }
  109577. }
  109578. this._textures = [];
  109579. };
  109580. /**
  109581. * Dispose the highlight layer and free resources.
  109582. */
  109583. EffectLayer.prototype.dispose = function () {
  109584. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  109585. if (vertexBuffer) {
  109586. vertexBuffer.dispose();
  109587. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  109588. }
  109589. if (this._indexBuffer) {
  109590. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  109591. this._indexBuffer = null;
  109592. }
  109593. // Clean textures and post processes
  109594. this._disposeTextureAndPostProcesses();
  109595. // Remove from scene
  109596. var index = this._scene.effectLayers.indexOf(this, 0);
  109597. if (index > -1) {
  109598. this._scene.effectLayers.splice(index, 1);
  109599. }
  109600. // Callback
  109601. this.onDisposeObservable.notifyObservers(this);
  109602. this.onDisposeObservable.clear();
  109603. this.onBeforeRenderMainTextureObservable.clear();
  109604. this.onBeforeComposeObservable.clear();
  109605. this.onAfterComposeObservable.clear();
  109606. this.onSizeChangedObservable.clear();
  109607. };
  109608. /**
  109609. * Gets the class name of the effect layer
  109610. * @returns the string with the class name of the effect layer
  109611. */
  109612. EffectLayer.prototype.getClassName = function () {
  109613. return "EffectLayer";
  109614. };
  109615. /**
  109616. * Creates an effect layer from parsed effect layer data
  109617. * @param parsedEffectLayer defines effect layer data
  109618. * @param scene defines the current scene
  109619. * @param rootUrl defines the root URL containing the effect layer information
  109620. * @returns a parsed effect Layer
  109621. */
  109622. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  109623. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  109624. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  109625. };
  109626. __decorate([
  109627. BABYLON.serialize()
  109628. ], EffectLayer.prototype, "name", void 0);
  109629. __decorate([
  109630. BABYLON.serializeAsColor4()
  109631. ], EffectLayer.prototype, "neutralColor", void 0);
  109632. __decorate([
  109633. BABYLON.serialize()
  109634. ], EffectLayer.prototype, "isEnabled", void 0);
  109635. __decorate([
  109636. BABYLON.serializeAsCameraReference()
  109637. ], EffectLayer.prototype, "camera", null);
  109638. __decorate([
  109639. BABYLON.serialize()
  109640. ], EffectLayer.prototype, "renderingGroupId", null);
  109641. return EffectLayer;
  109642. }());
  109643. BABYLON.EffectLayer = EffectLayer;
  109644. })(BABYLON || (BABYLON = {}));
  109645. //# sourceMappingURL=babylon.effectLayer.js.map
  109646. var BABYLON;
  109647. (function (BABYLON) {
  109648. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  109649. for (var index = 0; index < this.effectLayers.length; index++) {
  109650. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  109651. return this.effectLayers[index];
  109652. }
  109653. }
  109654. return null;
  109655. };
  109656. /**
  109657. * Special Glow Blur post process only blurring the alpha channel
  109658. * It enforces keeping the most luminous color in the color channel.
  109659. */
  109660. var GlowBlurPostProcess = /** @class */ (function (_super) {
  109661. __extends(GlowBlurPostProcess, _super);
  109662. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  109663. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  109664. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  109665. _this.direction = direction;
  109666. _this.kernel = kernel;
  109667. _this.onApplyObservable.add(function (effect) {
  109668. effect.setFloat2("screenSize", _this.width, _this.height);
  109669. effect.setVector2("direction", _this.direction);
  109670. effect.setFloat("blurWidth", _this.kernel);
  109671. });
  109672. return _this;
  109673. }
  109674. return GlowBlurPostProcess;
  109675. }(BABYLON.PostProcess));
  109676. /**
  109677. * The highlight layer Helps adding a glow effect around a mesh.
  109678. *
  109679. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  109680. * glowy meshes to your scene.
  109681. *
  109682. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  109683. */
  109684. var HighlightLayer = /** @class */ (function (_super) {
  109685. __extends(HighlightLayer, _super);
  109686. /**
  109687. * Instantiates a new highlight Layer and references it to the scene..
  109688. * @param name The name of the layer
  109689. * @param scene The scene to use the layer in
  109690. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  109691. */
  109692. function HighlightLayer(name, scene, options) {
  109693. var _this = _super.call(this, name, scene) || this;
  109694. _this.name = name;
  109695. /**
  109696. * Specifies whether or not the inner glow is ACTIVE in the layer.
  109697. */
  109698. _this.innerGlow = true;
  109699. /**
  109700. * Specifies whether or not the outer glow is ACTIVE in the layer.
  109701. */
  109702. _this.outerGlow = true;
  109703. /**
  109704. * An event triggered when the highlight layer is being blurred.
  109705. */
  109706. _this.onBeforeBlurObservable = new BABYLON.Observable();
  109707. /**
  109708. * An event triggered when the highlight layer has been blurred.
  109709. */
  109710. _this.onAfterBlurObservable = new BABYLON.Observable();
  109711. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  109712. _this._meshes = {};
  109713. _this._excludedMeshes = {};
  109714. _this.neutralColor = HighlightLayer.NeutralColor;
  109715. // Warn on stencil
  109716. if (!_this._engine.isStencilEnable) {
  109717. 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 }");
  109718. }
  109719. // Adapt options
  109720. _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);
  109721. // Initialize the layer
  109722. _this._init({
  109723. alphaBlendingMode: _this._options.alphaBlendingMode,
  109724. camera: _this._options.camera,
  109725. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  109726. mainTextureRatio: _this._options.mainTextureRatio,
  109727. renderingGroupId: _this._options.renderingGroupId
  109728. });
  109729. // Do not render as long as no meshes have been added
  109730. _this._shouldRender = false;
  109731. return _this;
  109732. }
  109733. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  109734. /**
  109735. * Gets the horizontal size of the blur.
  109736. */
  109737. get: function () {
  109738. return this._horizontalBlurPostprocess.kernel;
  109739. },
  109740. /**
  109741. * Specifies the horizontal size of the blur.
  109742. */
  109743. set: function (value) {
  109744. this._horizontalBlurPostprocess.kernel = value;
  109745. },
  109746. enumerable: true,
  109747. configurable: true
  109748. });
  109749. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  109750. /**
  109751. * Gets the vertical size of the blur.
  109752. */
  109753. get: function () {
  109754. return this._verticalBlurPostprocess.kernel;
  109755. },
  109756. /**
  109757. * Specifies the vertical size of the blur.
  109758. */
  109759. set: function (value) {
  109760. this._verticalBlurPostprocess.kernel = value;
  109761. },
  109762. enumerable: true,
  109763. configurable: true
  109764. });
  109765. /**
  109766. * Get the effect name of the layer.
  109767. * @return The effect name
  109768. */
  109769. HighlightLayer.prototype.getEffectName = function () {
  109770. return HighlightLayer.EffectName;
  109771. };
  109772. /**
  109773. * Create the merge effect. This is the shader use to blit the information back
  109774. * to the main canvas at the end of the scene rendering.
  109775. */
  109776. HighlightLayer.prototype._createMergeEffect = function () {
  109777. // Effect
  109778. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  109779. };
  109780. /**
  109781. * Creates the render target textures and post processes used in the highlight layer.
  109782. */
  109783. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  109784. var _this = this;
  109785. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  109786. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  109787. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  109788. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  109789. var textureType = 0;
  109790. if (this._engine.getCaps().textureHalfFloatRender) {
  109791. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  109792. }
  109793. else {
  109794. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  109795. }
  109796. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  109797. width: blurTextureWidth,
  109798. height: blurTextureHeight
  109799. }, this._scene, false, true, textureType);
  109800. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109801. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109802. this._blurTexture.anisotropicFilteringLevel = 16;
  109803. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  109804. this._blurTexture.renderParticles = false;
  109805. this._blurTexture.ignoreCameraViewport = true;
  109806. this._textures = [this._blurTexture];
  109807. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  109808. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  109809. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  109810. effect.setTexture("textureSampler", _this._mainTexture);
  109811. });
  109812. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  109813. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  109814. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  109815. });
  109816. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  109817. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  109818. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  109819. });
  109820. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  109821. }
  109822. else {
  109823. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  109824. width: blurTextureWidth,
  109825. height: blurTextureHeight
  109826. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  109827. this._horizontalBlurPostprocess.width = blurTextureWidth;
  109828. this._horizontalBlurPostprocess.height = blurTextureHeight;
  109829. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  109830. effect.setTexture("textureSampler", _this._mainTexture);
  109831. });
  109832. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  109833. width: blurTextureWidth,
  109834. height: blurTextureHeight
  109835. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  109836. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  109837. }
  109838. this._mainTexture.onAfterUnbindObservable.add(function () {
  109839. _this.onBeforeBlurObservable.notifyObservers(_this);
  109840. var internalTexture = _this._blurTexture.getInternalTexture();
  109841. if (internalTexture) {
  109842. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  109843. }
  109844. _this.onAfterBlurObservable.notifyObservers(_this);
  109845. });
  109846. // Prevent autoClear.
  109847. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  109848. };
  109849. /**
  109850. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  109851. */
  109852. HighlightLayer.prototype.needStencil = function () {
  109853. return true;
  109854. };
  109855. /**
  109856. * Checks for the readiness of the element composing the layer.
  109857. * @param subMesh the mesh to check for
  109858. * @param useInstances specify wether or not to use instances to render the mesh
  109859. * @param emissiveTexture the associated emissive texture used to generate the glow
  109860. * @return true if ready otherwise, false
  109861. */
  109862. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  109863. var material = subMesh.getMaterial();
  109864. var mesh = subMesh.getRenderingMesh();
  109865. if (!material || !mesh || !this._meshes) {
  109866. return false;
  109867. }
  109868. var emissiveTexture = null;
  109869. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  109870. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  109871. emissiveTexture = material.emissiveTexture;
  109872. }
  109873. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  109874. };
  109875. /**
  109876. * Implementation specific of rendering the generating effect on the main canvas.
  109877. * @param effect The effect used to render through
  109878. */
  109879. HighlightLayer.prototype._internalRender = function (effect) {
  109880. // Texture
  109881. effect.setTexture("textureSampler", this._blurTexture);
  109882. // Cache
  109883. var engine = this._engine;
  109884. var previousStencilBuffer = engine.getStencilBuffer();
  109885. var previousStencilFunction = engine.getStencilFunction();
  109886. var previousStencilMask = engine.getStencilMask();
  109887. var previousStencilOperationPass = engine.getStencilOperationPass();
  109888. var previousStencilOperationFail = engine.getStencilOperationFail();
  109889. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  109890. var previousStencilReference = engine.getStencilFunctionReference();
  109891. // Stencil operations
  109892. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  109893. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  109894. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  109895. // Draw order
  109896. engine.setStencilMask(0x00);
  109897. engine.setStencilBuffer(true);
  109898. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  109899. // 2 passes inner outer
  109900. if (this.outerGlow) {
  109901. effect.setFloat("offset", 0);
  109902. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  109903. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  109904. }
  109905. if (this.innerGlow) {
  109906. effect.setFloat("offset", 1);
  109907. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  109908. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  109909. }
  109910. // Restore Cache
  109911. engine.setStencilFunction(previousStencilFunction);
  109912. engine.setStencilMask(previousStencilMask);
  109913. engine.setStencilBuffer(previousStencilBuffer);
  109914. engine.setStencilOperationPass(previousStencilOperationPass);
  109915. engine.setStencilOperationFail(previousStencilOperationFail);
  109916. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  109917. engine.setStencilFunctionReference(previousStencilReference);
  109918. };
  109919. /**
  109920. * Returns true if the layer contains information to display, otherwise false.
  109921. */
  109922. HighlightLayer.prototype.shouldRender = function () {
  109923. if (_super.prototype.shouldRender.call(this)) {
  109924. return this._meshes ? true : false;
  109925. }
  109926. return false;
  109927. };
  109928. /**
  109929. * Returns true if the mesh should render, otherwise false.
  109930. * @param mesh The mesh to render
  109931. * @returns true if it should render otherwise false
  109932. */
  109933. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  109934. // Excluded Mesh
  109935. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  109936. return false;
  109937. }
  109938. if (!_super.prototype.hasMesh.call(this, mesh)) {
  109939. return false;
  109940. }
  109941. return true;
  109942. };
  109943. /**
  109944. * Sets the required values for both the emissive texture and and the main color.
  109945. */
  109946. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  109947. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  109948. if (highlightLayerMesh) {
  109949. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  109950. }
  109951. else {
  109952. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  109953. }
  109954. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  109955. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  109956. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  109957. }
  109958. else {
  109959. this._emissiveTextureAndColor.texture = null;
  109960. }
  109961. };
  109962. /**
  109963. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  109964. * @param mesh The mesh to exclude from the highlight layer
  109965. */
  109966. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  109967. if (!this._excludedMeshes) {
  109968. return;
  109969. }
  109970. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  109971. if (!meshExcluded) {
  109972. this._excludedMeshes[mesh.uniqueId] = {
  109973. mesh: mesh,
  109974. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  109975. mesh.getEngine().setStencilBuffer(false);
  109976. }),
  109977. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  109978. mesh.getEngine().setStencilBuffer(true);
  109979. }),
  109980. };
  109981. }
  109982. };
  109983. /**
  109984. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  109985. * @param mesh The mesh to highlight
  109986. */
  109987. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  109988. if (!this._excludedMeshes) {
  109989. return;
  109990. }
  109991. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  109992. if (meshExcluded) {
  109993. if (meshExcluded.beforeRender) {
  109994. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  109995. }
  109996. if (meshExcluded.afterRender) {
  109997. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  109998. }
  109999. }
  110000. this._excludedMeshes[mesh.uniqueId] = null;
  110001. };
  110002. /**
  110003. * Determine if a given mesh will be highlighted by the current HighlightLayer
  110004. * @param mesh mesh to test
  110005. * @returns true if the mesh will be highlighted by the current HighlightLayer
  110006. */
  110007. HighlightLayer.prototype.hasMesh = function (mesh) {
  110008. if (!this._meshes) {
  110009. return false;
  110010. }
  110011. if (!_super.prototype.hasMesh.call(this, mesh)) {
  110012. return false;
  110013. }
  110014. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  110015. };
  110016. /**
  110017. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  110018. * @param mesh The mesh to highlight
  110019. * @param color The color of the highlight
  110020. * @param glowEmissiveOnly Extract the glow from the emissive texture
  110021. */
  110022. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  110023. var _this = this;
  110024. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  110025. if (!this._meshes) {
  110026. return;
  110027. }
  110028. var meshHighlight = this._meshes[mesh.uniqueId];
  110029. if (meshHighlight) {
  110030. meshHighlight.color = color;
  110031. }
  110032. else {
  110033. this._meshes[mesh.uniqueId] = {
  110034. mesh: mesh,
  110035. color: color,
  110036. // Lambda required for capture due to Observable this context
  110037. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  110038. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  110039. _this._defaultStencilReference(mesh);
  110040. }
  110041. else {
  110042. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  110043. }
  110044. }),
  110045. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  110046. glowEmissiveOnly: glowEmissiveOnly
  110047. };
  110048. mesh.onDisposeObservable.add(function () {
  110049. _this._disposeMesh(mesh);
  110050. });
  110051. }
  110052. this._shouldRender = true;
  110053. };
  110054. /**
  110055. * Remove a mesh from the highlight layer in order to make it stop glowing.
  110056. * @param mesh The mesh to highlight
  110057. */
  110058. HighlightLayer.prototype.removeMesh = function (mesh) {
  110059. if (!this._meshes) {
  110060. return;
  110061. }
  110062. var meshHighlight = this._meshes[mesh.uniqueId];
  110063. if (meshHighlight) {
  110064. if (meshHighlight.observerHighlight) {
  110065. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  110066. }
  110067. if (meshHighlight.observerDefault) {
  110068. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  110069. }
  110070. delete this._meshes[mesh.uniqueId];
  110071. }
  110072. this._shouldRender = false;
  110073. for (var meshHighlightToCheck in this._meshes) {
  110074. if (this._meshes[meshHighlightToCheck]) {
  110075. this._shouldRender = true;
  110076. break;
  110077. }
  110078. }
  110079. };
  110080. /**
  110081. * Force the stencil to the normal expected value for none glowing parts
  110082. */
  110083. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  110084. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  110085. };
  110086. /**
  110087. * Free any resources and references associated to a mesh.
  110088. * Internal use
  110089. * @param mesh The mesh to free.
  110090. * @hidden
  110091. */
  110092. HighlightLayer.prototype._disposeMesh = function (mesh) {
  110093. this.removeMesh(mesh);
  110094. this.removeExcludedMesh(mesh);
  110095. };
  110096. /**
  110097. * Dispose the highlight layer and free resources.
  110098. */
  110099. HighlightLayer.prototype.dispose = function () {
  110100. if (this._meshes) {
  110101. // Clean mesh references
  110102. for (var id in this._meshes) {
  110103. var meshHighlight = this._meshes[id];
  110104. if (meshHighlight && meshHighlight.mesh) {
  110105. if (meshHighlight.observerHighlight) {
  110106. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  110107. }
  110108. if (meshHighlight.observerDefault) {
  110109. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  110110. }
  110111. }
  110112. }
  110113. this._meshes = null;
  110114. }
  110115. if (this._excludedMeshes) {
  110116. for (var id in this._excludedMeshes) {
  110117. var meshHighlight = this._excludedMeshes[id];
  110118. if (meshHighlight) {
  110119. if (meshHighlight.beforeRender) {
  110120. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  110121. }
  110122. if (meshHighlight.afterRender) {
  110123. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  110124. }
  110125. }
  110126. }
  110127. this._excludedMeshes = null;
  110128. }
  110129. _super.prototype.dispose.call(this);
  110130. };
  110131. /**
  110132. * Gets the class name of the effect layer
  110133. * @returns the string with the class name of the effect layer
  110134. */
  110135. HighlightLayer.prototype.getClassName = function () {
  110136. return "HighlightLayer";
  110137. };
  110138. /**
  110139. * Serializes this Highlight layer
  110140. * @returns a serialized Highlight layer object
  110141. */
  110142. HighlightLayer.prototype.serialize = function () {
  110143. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  110144. serializationObject.customType = "BABYLON.HighlightLayer";
  110145. // Highlighted meshes
  110146. serializationObject.meshes = [];
  110147. if (this._meshes) {
  110148. for (var m in this._meshes) {
  110149. var mesh = this._meshes[m];
  110150. if (mesh) {
  110151. serializationObject.meshes.push({
  110152. glowEmissiveOnly: mesh.glowEmissiveOnly,
  110153. color: mesh.color.asArray(),
  110154. meshId: mesh.mesh.id
  110155. });
  110156. }
  110157. }
  110158. }
  110159. // Excluded meshes
  110160. serializationObject.excludedMeshes = [];
  110161. if (this._excludedMeshes) {
  110162. for (var e in this._excludedMeshes) {
  110163. var excludedMesh = this._excludedMeshes[e];
  110164. if (excludedMesh) {
  110165. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  110166. }
  110167. }
  110168. }
  110169. return serializationObject;
  110170. };
  110171. /**
  110172. * Creates a Highlight layer from parsed Highlight layer data
  110173. * @param parsedHightlightLayer defines the Highlight layer data
  110174. * @param scene defines the current scene
  110175. * @param rootUrl defines the root URL containing the Highlight layer information
  110176. * @returns a parsed Highlight layer
  110177. */
  110178. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  110179. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  110180. var index;
  110181. // Excluded meshes
  110182. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  110183. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  110184. if (mesh) {
  110185. hl.addExcludedMesh(mesh);
  110186. }
  110187. }
  110188. // Included meshes
  110189. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  110190. var highlightedMesh = parsedHightlightLayer.meshes[index];
  110191. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  110192. if (mesh) {
  110193. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  110194. }
  110195. }
  110196. return hl;
  110197. };
  110198. /**
  110199. * Effect Name of the highlight layer.
  110200. */
  110201. HighlightLayer.EffectName = "HighlightLayer";
  110202. /**
  110203. * The neutral color used during the preparation of the glow effect.
  110204. * This is black by default as the blend operation is a blend operation.
  110205. */
  110206. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  110207. /**
  110208. * Stencil value used for glowing meshes.
  110209. */
  110210. HighlightLayer.GlowingMeshStencilReference = 0x02;
  110211. /**
  110212. * Stencil value used for the other meshes in the scene.
  110213. */
  110214. HighlightLayer.NormalMeshStencilReference = 0x01;
  110215. __decorate([
  110216. BABYLON.serialize()
  110217. ], HighlightLayer.prototype, "innerGlow", void 0);
  110218. __decorate([
  110219. BABYLON.serialize()
  110220. ], HighlightLayer.prototype, "outerGlow", void 0);
  110221. __decorate([
  110222. BABYLON.serialize()
  110223. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  110224. __decorate([
  110225. BABYLON.serialize()
  110226. ], HighlightLayer.prototype, "blurVerticalSize", null);
  110227. __decorate([
  110228. BABYLON.serialize("options")
  110229. ], HighlightLayer.prototype, "_options", void 0);
  110230. return HighlightLayer;
  110231. }(BABYLON.EffectLayer));
  110232. BABYLON.HighlightLayer = HighlightLayer;
  110233. })(BABYLON || (BABYLON = {}));
  110234. //# sourceMappingURL=babylon.highlightLayer.js.map
  110235. var BABYLON;
  110236. (function (BABYLON) {
  110237. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  110238. for (var index = 0; index < this.effectLayers.length; index++) {
  110239. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  110240. return this.effectLayers[index];
  110241. }
  110242. }
  110243. return null;
  110244. };
  110245. /**
  110246. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  110247. *
  110248. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  110249. * glowy meshes to your scene.
  110250. *
  110251. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  110252. */
  110253. var GlowLayer = /** @class */ (function (_super) {
  110254. __extends(GlowLayer, _super);
  110255. /**
  110256. * Instantiates a new glow Layer and references it to the scene.
  110257. * @param name The name of the layer
  110258. * @param scene The scene to use the layer in
  110259. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  110260. */
  110261. function GlowLayer(name, scene, options) {
  110262. var _this = _super.call(this, name, scene) || this;
  110263. _this._intensity = 1.0;
  110264. _this._includedOnlyMeshes = [];
  110265. _this._excludedMeshes = [];
  110266. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  110267. // Adapt options
  110268. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  110269. // Initialize the layer
  110270. _this._init({
  110271. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  110272. camera: _this._options.camera,
  110273. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  110274. mainTextureRatio: _this._options.mainTextureRatio,
  110275. renderingGroupId: _this._options.renderingGroupId
  110276. });
  110277. return _this;
  110278. }
  110279. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  110280. /**
  110281. * Gets the kernel size of the blur.
  110282. */
  110283. get: function () {
  110284. return this._horizontalBlurPostprocess1.kernel;
  110285. },
  110286. /**
  110287. * Sets the kernel size of the blur.
  110288. */
  110289. set: function (value) {
  110290. this._horizontalBlurPostprocess1.kernel = value;
  110291. this._verticalBlurPostprocess1.kernel = value;
  110292. this._horizontalBlurPostprocess2.kernel = value;
  110293. this._verticalBlurPostprocess2.kernel = value;
  110294. },
  110295. enumerable: true,
  110296. configurable: true
  110297. });
  110298. Object.defineProperty(GlowLayer.prototype, "intensity", {
  110299. /**
  110300. * Gets the glow intensity.
  110301. */
  110302. get: function () {
  110303. return this._intensity;
  110304. },
  110305. /**
  110306. * Sets the glow intensity.
  110307. */
  110308. set: function (value) {
  110309. this._intensity = value;
  110310. },
  110311. enumerable: true,
  110312. configurable: true
  110313. });
  110314. /**
  110315. * Get the effect name of the layer.
  110316. * @return The effect name
  110317. */
  110318. GlowLayer.prototype.getEffectName = function () {
  110319. return GlowLayer.EffectName;
  110320. };
  110321. /**
  110322. * Create the merge effect. This is the shader use to blit the information back
  110323. * to the main canvas at the end of the scene rendering.
  110324. */
  110325. GlowLayer.prototype._createMergeEffect = function () {
  110326. // Effect
  110327. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  110328. };
  110329. /**
  110330. * Creates the render target textures and post processes used in the glow layer.
  110331. */
  110332. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  110333. var _this = this;
  110334. var blurTextureWidth = this._mainTextureDesiredSize.width;
  110335. var blurTextureHeight = this._mainTextureDesiredSize.height;
  110336. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  110337. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  110338. var textureType = 0;
  110339. if (this._engine.getCaps().textureHalfFloatRender) {
  110340. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  110341. }
  110342. else {
  110343. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  110344. }
  110345. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  110346. width: blurTextureWidth,
  110347. height: blurTextureHeight
  110348. }, this._scene, false, true, textureType);
  110349. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110350. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110351. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  110352. this._blurTexture1.renderParticles = false;
  110353. this._blurTexture1.ignoreCameraViewport = true;
  110354. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  110355. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  110356. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  110357. width: blurTextureWidth2,
  110358. height: blurTextureHeight2
  110359. }, this._scene, false, true, textureType);
  110360. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110361. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110362. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  110363. this._blurTexture2.renderParticles = false;
  110364. this._blurTexture2.ignoreCameraViewport = true;
  110365. this._textures = [this._blurTexture1, this._blurTexture2];
  110366. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  110367. width: blurTextureWidth,
  110368. height: blurTextureHeight
  110369. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110370. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  110371. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  110372. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  110373. effect.setTexture("textureSampler", _this._mainTexture);
  110374. });
  110375. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  110376. width: blurTextureWidth,
  110377. height: blurTextureHeight
  110378. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110379. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  110380. width: blurTextureWidth2,
  110381. height: blurTextureHeight2
  110382. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110383. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  110384. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  110385. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  110386. effect.setTexture("textureSampler", _this._blurTexture1);
  110387. });
  110388. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  110389. width: blurTextureWidth2,
  110390. height: blurTextureHeight2
  110391. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110392. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  110393. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  110394. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  110395. this._mainTexture.samples = this._options.mainTextureSamples;
  110396. this._mainTexture.onAfterUnbindObservable.add(function () {
  110397. var internalTexture = _this._blurTexture1.getInternalTexture();
  110398. if (internalTexture) {
  110399. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  110400. internalTexture = _this._blurTexture2.getInternalTexture();
  110401. if (internalTexture) {
  110402. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  110403. }
  110404. }
  110405. });
  110406. // Prevent autoClear.
  110407. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  110408. };
  110409. /**
  110410. * Checks for the readiness of the element composing the layer.
  110411. * @param subMesh the mesh to check for
  110412. * @param useInstances specify wether or not to use instances to render the mesh
  110413. * @param emissiveTexture the associated emissive texture used to generate the glow
  110414. * @return true if ready otherwise, false
  110415. */
  110416. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  110417. var material = subMesh.getMaterial();
  110418. var mesh = subMesh.getRenderingMesh();
  110419. if (!material || !mesh) {
  110420. return false;
  110421. }
  110422. var emissiveTexture = material.emissiveTexture;
  110423. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  110424. };
  110425. /**
  110426. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  110427. */
  110428. GlowLayer.prototype.needStencil = function () {
  110429. return false;
  110430. };
  110431. /**
  110432. * Implementation specific of rendering the generating effect on the main canvas.
  110433. * @param effect The effect used to render through
  110434. */
  110435. GlowLayer.prototype._internalRender = function (effect) {
  110436. // Texture
  110437. effect.setTexture("textureSampler", this._blurTexture1);
  110438. effect.setTexture("textureSampler2", this._blurTexture2);
  110439. effect.setFloat("offset", this._intensity);
  110440. // Cache
  110441. var engine = this._engine;
  110442. var previousStencilBuffer = engine.getStencilBuffer();
  110443. // Draw order
  110444. engine.setStencilBuffer(false);
  110445. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  110446. // Draw order
  110447. engine.setStencilBuffer(previousStencilBuffer);
  110448. };
  110449. /**
  110450. * Sets the required values for both the emissive texture and and the main color.
  110451. */
  110452. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  110453. var textureLevel = 1.0;
  110454. if (this.customEmissiveTextureSelector) {
  110455. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  110456. }
  110457. else {
  110458. if (material) {
  110459. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  110460. if (this._emissiveTextureAndColor.texture) {
  110461. textureLevel = this._emissiveTextureAndColor.texture.level;
  110462. }
  110463. }
  110464. else {
  110465. this._emissiveTextureAndColor.texture = null;
  110466. }
  110467. }
  110468. if (this.customEmissiveColorSelector) {
  110469. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  110470. }
  110471. else {
  110472. if (material.emissiveColor) {
  110473. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  110474. }
  110475. else {
  110476. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  110477. }
  110478. }
  110479. };
  110480. /**
  110481. * Returns true if the mesh should render, otherwise false.
  110482. * @param mesh The mesh to render
  110483. * @returns true if it should render otherwise false
  110484. */
  110485. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  110486. return this.hasMesh(mesh);
  110487. };
  110488. /**
  110489. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  110490. * @param mesh The mesh to exclude from the glow layer
  110491. */
  110492. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  110493. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  110494. this._excludedMeshes.push(mesh.uniqueId);
  110495. }
  110496. };
  110497. /**
  110498. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  110499. * @param mesh The mesh to remove
  110500. */
  110501. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  110502. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  110503. if (index !== -1) {
  110504. this._excludedMeshes.splice(index, 1);
  110505. }
  110506. };
  110507. /**
  110508. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  110509. * @param mesh The mesh to include in the glow layer
  110510. */
  110511. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  110512. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  110513. this._includedOnlyMeshes.push(mesh.uniqueId);
  110514. }
  110515. };
  110516. /**
  110517. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  110518. * @param mesh The mesh to remove
  110519. */
  110520. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  110521. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  110522. if (index !== -1) {
  110523. this._includedOnlyMeshes.splice(index, 1);
  110524. }
  110525. };
  110526. /**
  110527. * Determine if a given mesh will be used in the glow layer
  110528. * @param mesh The mesh to test
  110529. * @returns true if the mesh will be highlighted by the current glow layer
  110530. */
  110531. GlowLayer.prototype.hasMesh = function (mesh) {
  110532. if (!_super.prototype.hasMesh.call(this, mesh)) {
  110533. return false;
  110534. }
  110535. // Included Mesh
  110536. if (this._includedOnlyMeshes.length) {
  110537. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  110538. }
  110539. // Excluded Mesh
  110540. if (this._excludedMeshes.length) {
  110541. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  110542. }
  110543. return true;
  110544. };
  110545. /**
  110546. * Free any resources and references associated to a mesh.
  110547. * Internal use
  110548. * @param mesh The mesh to free.
  110549. * @hidden
  110550. */
  110551. GlowLayer.prototype._disposeMesh = function (mesh) {
  110552. this.removeIncludedOnlyMesh(mesh);
  110553. this.removeExcludedMesh(mesh);
  110554. };
  110555. /**
  110556. * Gets the class name of the effect layer
  110557. * @returns the string with the class name of the effect layer
  110558. */
  110559. GlowLayer.prototype.getClassName = function () {
  110560. return "GlowLayer";
  110561. };
  110562. /**
  110563. * Serializes this glow layer
  110564. * @returns a serialized glow layer object
  110565. */
  110566. GlowLayer.prototype.serialize = function () {
  110567. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  110568. serializationObject.customType = "BABYLON.GlowLayer";
  110569. var index;
  110570. // Included meshes
  110571. serializationObject.includedMeshes = [];
  110572. if (this._includedOnlyMeshes.length) {
  110573. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  110574. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  110575. if (mesh) {
  110576. serializationObject.includedMeshes.push(mesh.id);
  110577. }
  110578. }
  110579. }
  110580. // Excluded meshes
  110581. serializationObject.excludedMeshes = [];
  110582. if (this._excludedMeshes.length) {
  110583. for (index = 0; index < this._excludedMeshes.length; index++) {
  110584. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  110585. if (mesh) {
  110586. serializationObject.excludedMeshes.push(mesh.id);
  110587. }
  110588. }
  110589. }
  110590. return serializationObject;
  110591. };
  110592. /**
  110593. * Creates a Glow Layer from parsed glow layer data
  110594. * @param parsedGlowLayer defines glow layer data
  110595. * @param scene defines the current scene
  110596. * @param rootUrl defines the root URL containing the glow layer information
  110597. * @returns a parsed Glow Layer
  110598. */
  110599. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  110600. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  110601. var index;
  110602. // Excluded meshes
  110603. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  110604. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  110605. if (mesh) {
  110606. gl.addExcludedMesh(mesh);
  110607. }
  110608. }
  110609. // Included meshes
  110610. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  110611. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  110612. if (mesh) {
  110613. gl.addIncludedOnlyMesh(mesh);
  110614. }
  110615. }
  110616. return gl;
  110617. };
  110618. /**
  110619. * Effect Name of the layer.
  110620. */
  110621. GlowLayer.EffectName = "GlowLayer";
  110622. /**
  110623. * The default blur kernel size used for the glow.
  110624. */
  110625. GlowLayer.DefaultBlurKernelSize = 32;
  110626. /**
  110627. * The default texture size ratio used for the glow.
  110628. */
  110629. GlowLayer.DefaultTextureRatio = 0.5;
  110630. __decorate([
  110631. BABYLON.serialize()
  110632. ], GlowLayer.prototype, "blurKernelSize", null);
  110633. __decorate([
  110634. BABYLON.serialize()
  110635. ], GlowLayer.prototype, "intensity", null);
  110636. __decorate([
  110637. BABYLON.serialize("options")
  110638. ], GlowLayer.prototype, "_options", void 0);
  110639. return GlowLayer;
  110640. }(BABYLON.EffectLayer));
  110641. BABYLON.GlowLayer = GlowLayer;
  110642. })(BABYLON || (BABYLON = {}));
  110643. //# sourceMappingURL=babylon.glowLayer.js.map
  110644. var BABYLON;
  110645. (function (BABYLON) {
  110646. /**
  110647. * Defines the list of states available for a task inside a AssetsManager
  110648. */
  110649. var AssetTaskState;
  110650. (function (AssetTaskState) {
  110651. /**
  110652. * Initialization
  110653. */
  110654. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  110655. /**
  110656. * Running
  110657. */
  110658. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  110659. /**
  110660. * Done
  110661. */
  110662. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  110663. /**
  110664. * Error
  110665. */
  110666. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  110667. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  110668. /**
  110669. * Define an abstract asset task used with a AssetsManager class to load assets into a scene
  110670. */
  110671. var AbstractAssetTask = /** @class */ (function () {
  110672. /**
  110673. * Creates a new AssetsManager
  110674. * @param name defines the name of the task
  110675. */
  110676. function AbstractAssetTask(
  110677. /**
  110678. * Task name
  110679. */ name) {
  110680. this.name = name;
  110681. this._isCompleted = false;
  110682. this._taskState = AssetTaskState.INIT;
  110683. }
  110684. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  110685. /**
  110686. * Get if the task is completed
  110687. */
  110688. get: function () {
  110689. return this._isCompleted;
  110690. },
  110691. enumerable: true,
  110692. configurable: true
  110693. });
  110694. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  110695. /**
  110696. * Gets the current state of the task
  110697. */
  110698. get: function () {
  110699. return this._taskState;
  110700. },
  110701. enumerable: true,
  110702. configurable: true
  110703. });
  110704. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  110705. /**
  110706. * Gets the current error object (if task is in error)
  110707. */
  110708. get: function () {
  110709. return this._errorObject;
  110710. },
  110711. enumerable: true,
  110712. configurable: true
  110713. });
  110714. /**
  110715. * Internal only
  110716. * @hidden
  110717. */
  110718. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  110719. if (this._errorObject) {
  110720. return;
  110721. }
  110722. this._errorObject = {
  110723. message: message,
  110724. exception: exception
  110725. };
  110726. };
  110727. /**
  110728. * Execute the current task
  110729. * @param scene defines the scene where you want your assets to be loaded
  110730. * @param onSuccess is a callback called when the task is successfully executed
  110731. * @param onError is a callback called if an error occurs
  110732. */
  110733. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  110734. var _this = this;
  110735. this._taskState = AssetTaskState.RUNNING;
  110736. this.runTask(scene, function () {
  110737. _this.onDoneCallback(onSuccess, onError);
  110738. }, function (msg, exception) {
  110739. _this.onErrorCallback(onError, msg, exception);
  110740. });
  110741. };
  110742. /**
  110743. * Execute the current task
  110744. * @param scene defines the scene where you want your assets to be loaded
  110745. * @param onSuccess is a callback called when the task is successfully executed
  110746. * @param onError is a callback called if an error occurs
  110747. */
  110748. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110749. throw new Error("runTask is not implemented");
  110750. };
  110751. /**
  110752. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  110753. * This can be used with failed tasks that have the reason for failure fixed.
  110754. */
  110755. AbstractAssetTask.prototype.reset = function () {
  110756. this._taskState = AssetTaskState.INIT;
  110757. };
  110758. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  110759. this._taskState = AssetTaskState.ERROR;
  110760. this._errorObject = {
  110761. message: message,
  110762. exception: exception
  110763. };
  110764. if (this.onError) {
  110765. this.onError(this, message, exception);
  110766. }
  110767. onError();
  110768. };
  110769. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  110770. try {
  110771. this._taskState = AssetTaskState.DONE;
  110772. this._isCompleted = true;
  110773. if (this.onSuccess) {
  110774. this.onSuccess(this);
  110775. }
  110776. onSuccess();
  110777. }
  110778. catch (e) {
  110779. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  110780. }
  110781. };
  110782. return AbstractAssetTask;
  110783. }());
  110784. BABYLON.AbstractAssetTask = AbstractAssetTask;
  110785. /**
  110786. * Class used to share progress information about assets loading
  110787. */
  110788. var AssetsProgressEvent = /** @class */ (function () {
  110789. /**
  110790. * Creates a AssetsProgressEvent
  110791. * @param remainingCount defines the number of remaining tasks to process
  110792. * @param totalCount defines the total number of tasks
  110793. * @param task defines the task that was just processed
  110794. */
  110795. function AssetsProgressEvent(remainingCount, totalCount, task) {
  110796. this.remainingCount = remainingCount;
  110797. this.totalCount = totalCount;
  110798. this.task = task;
  110799. }
  110800. return AssetsProgressEvent;
  110801. }());
  110802. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  110803. /**
  110804. * Define a task used by AssetsManager to load meshes
  110805. */
  110806. var MeshAssetTask = /** @class */ (function (_super) {
  110807. __extends(MeshAssetTask, _super);
  110808. /**
  110809. * Creates a new MeshAssetTask
  110810. * @param name defines the name of the task
  110811. * @param meshesNames defines the list of mesh's names you want to load
  110812. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  110813. * @param sceneFilename defines the filename of the scene to load from
  110814. */
  110815. function MeshAssetTask(
  110816. /**
  110817. * Defines the name of the task
  110818. */
  110819. name,
  110820. /**
  110821. * Defines the list of mesh's names you want to load
  110822. */
  110823. meshesNames,
  110824. /**
  110825. * Defines the root url to use as a base to load your meshes and associated resources
  110826. */
  110827. rootUrl,
  110828. /**
  110829. * Defines the filename of the scene to load from
  110830. */
  110831. sceneFilename) {
  110832. var _this = _super.call(this, name) || this;
  110833. _this.name = name;
  110834. _this.meshesNames = meshesNames;
  110835. _this.rootUrl = rootUrl;
  110836. _this.sceneFilename = sceneFilename;
  110837. return _this;
  110838. }
  110839. /**
  110840. * Execute the current task
  110841. * @param scene defines the scene where you want your assets to be loaded
  110842. * @param onSuccess is a callback called when the task is successfully executed
  110843. * @param onError is a callback called if an error occurs
  110844. */
  110845. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110846. var _this = this;
  110847. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  110848. _this.loadedMeshes = meshes;
  110849. _this.loadedParticleSystems = particleSystems;
  110850. _this.loadedSkeletons = skeletons;
  110851. onSuccess();
  110852. }, null, function (scene, message, exception) {
  110853. onError(message, exception);
  110854. });
  110855. };
  110856. return MeshAssetTask;
  110857. }(AbstractAssetTask));
  110858. BABYLON.MeshAssetTask = MeshAssetTask;
  110859. /**
  110860. * Define a task used by AssetsManager to load text content
  110861. */
  110862. var TextFileAssetTask = /** @class */ (function (_super) {
  110863. __extends(TextFileAssetTask, _super);
  110864. /**
  110865. * Creates a new TextFileAssetTask object
  110866. * @param name defines the name of the task
  110867. * @param url defines the location of the file to load
  110868. */
  110869. function TextFileAssetTask(
  110870. /**
  110871. * Defines the name of the task
  110872. */
  110873. name,
  110874. /**
  110875. * Defines the location of the file to load
  110876. */
  110877. url) {
  110878. var _this = _super.call(this, name) || this;
  110879. _this.name = name;
  110880. _this.url = url;
  110881. return _this;
  110882. }
  110883. /**
  110884. * Execute the current task
  110885. * @param scene defines the scene where you want your assets to be loaded
  110886. * @param onSuccess is a callback called when the task is successfully executed
  110887. * @param onError is a callback called if an error occurs
  110888. */
  110889. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110890. var _this = this;
  110891. scene._loadFile(this.url, function (data) {
  110892. _this.text = data;
  110893. onSuccess();
  110894. }, undefined, false, false, function (request, exception) {
  110895. if (request) {
  110896. onError(request.status + " " + request.statusText, exception);
  110897. }
  110898. });
  110899. };
  110900. return TextFileAssetTask;
  110901. }(AbstractAssetTask));
  110902. BABYLON.TextFileAssetTask = TextFileAssetTask;
  110903. /**
  110904. * Define a task used by AssetsManager to load binary data
  110905. */
  110906. var BinaryFileAssetTask = /** @class */ (function (_super) {
  110907. __extends(BinaryFileAssetTask, _super);
  110908. /**
  110909. * Creates a new BinaryFileAssetTask object
  110910. * @param name defines the name of the new task
  110911. * @param url defines the location of the file to load
  110912. */
  110913. function BinaryFileAssetTask(
  110914. /**
  110915. * Defines the name of the task
  110916. */
  110917. name,
  110918. /**
  110919. * Defines the location of the file to load
  110920. */
  110921. url) {
  110922. var _this = _super.call(this, name) || this;
  110923. _this.name = name;
  110924. _this.url = url;
  110925. return _this;
  110926. }
  110927. /**
  110928. * Execute the current task
  110929. * @param scene defines the scene where you want your assets to be loaded
  110930. * @param onSuccess is a callback called when the task is successfully executed
  110931. * @param onError is a callback called if an error occurs
  110932. */
  110933. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110934. var _this = this;
  110935. scene._loadFile(this.url, function (data) {
  110936. _this.data = data;
  110937. onSuccess();
  110938. }, undefined, true, true, function (request, exception) {
  110939. if (request) {
  110940. onError(request.status + " " + request.statusText, exception);
  110941. }
  110942. });
  110943. };
  110944. return BinaryFileAssetTask;
  110945. }(AbstractAssetTask));
  110946. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  110947. /**
  110948. * Define a task used by AssetsManager to load images
  110949. */
  110950. var ImageAssetTask = /** @class */ (function (_super) {
  110951. __extends(ImageAssetTask, _super);
  110952. /**
  110953. * Creates a new ImageAssetTask
  110954. * @param name defines the name of the task
  110955. * @param url defines the location of the image to load
  110956. */
  110957. function ImageAssetTask(
  110958. /**
  110959. * Defines the name of the task
  110960. */
  110961. name,
  110962. /**
  110963. * Defines the location of the image to load
  110964. */
  110965. url) {
  110966. var _this = _super.call(this, name) || this;
  110967. _this.name = name;
  110968. _this.url = url;
  110969. return _this;
  110970. }
  110971. /**
  110972. * Execute the current task
  110973. * @param scene defines the scene where you want your assets to be loaded
  110974. * @param onSuccess is a callback called when the task is successfully executed
  110975. * @param onError is a callback called if an error occurs
  110976. */
  110977. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110978. var _this = this;
  110979. var img = new Image();
  110980. BABYLON.Tools.SetCorsBehavior(this.url, img);
  110981. img.onload = function () {
  110982. _this.image = img;
  110983. onSuccess();
  110984. };
  110985. img.onerror = function (err) {
  110986. onError("Error loading image", err);
  110987. };
  110988. img.src = this.url;
  110989. };
  110990. return ImageAssetTask;
  110991. }(AbstractAssetTask));
  110992. BABYLON.ImageAssetTask = ImageAssetTask;
  110993. /**
  110994. * Define a task used by AssetsManager to load 2D textures
  110995. */
  110996. var TextureAssetTask = /** @class */ (function (_super) {
  110997. __extends(TextureAssetTask, _super);
  110998. /**
  110999. * Creates a new TextureAssetTask object
  111000. * @param name defines the name of the task
  111001. * @param url defines the location of the file to load
  111002. * @param noMipmap defines if mipmap should not be generated (default is false)
  111003. * @param invertY defines if texture must be inverted on Y axis (default is false)
  111004. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  111005. */
  111006. function TextureAssetTask(
  111007. /**
  111008. * Defines the name of the task
  111009. */
  111010. name,
  111011. /**
  111012. * Defines the location of the file to load
  111013. */
  111014. url,
  111015. /**
  111016. * Defines if mipmap should not be generated (default is false)
  111017. */
  111018. noMipmap,
  111019. /**
  111020. * Defines if texture must be inverted on Y axis (default is false)
  111021. */
  111022. invertY,
  111023. /**
  111024. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  111025. */
  111026. samplingMode) {
  111027. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  111028. var _this = _super.call(this, name) || this;
  111029. _this.name = name;
  111030. _this.url = url;
  111031. _this.noMipmap = noMipmap;
  111032. _this.invertY = invertY;
  111033. _this.samplingMode = samplingMode;
  111034. return _this;
  111035. }
  111036. /**
  111037. * Execute the current task
  111038. * @param scene defines the scene where you want your assets to be loaded
  111039. * @param onSuccess is a callback called when the task is successfully executed
  111040. * @param onError is a callback called if an error occurs
  111041. */
  111042. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  111043. var onload = function () {
  111044. onSuccess();
  111045. };
  111046. var onerror = function (message, exception) {
  111047. onError(message, exception);
  111048. };
  111049. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  111050. };
  111051. return TextureAssetTask;
  111052. }(AbstractAssetTask));
  111053. BABYLON.TextureAssetTask = TextureAssetTask;
  111054. /**
  111055. * Define a task used by AssetsManager to load cube textures
  111056. */
  111057. var CubeTextureAssetTask = /** @class */ (function (_super) {
  111058. __extends(CubeTextureAssetTask, _super);
  111059. /**
  111060. * Creates a new CubeTextureAssetTask
  111061. * @param name defines the name of the task
  111062. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  111063. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  111064. * @param noMipmap defines if mipmaps should not be generated (default is false)
  111065. * @param files defines the explicit list of files (undefined by default)
  111066. */
  111067. function CubeTextureAssetTask(
  111068. /**
  111069. * Defines the name of the task
  111070. */
  111071. name,
  111072. /**
  111073. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  111074. */
  111075. url,
  111076. /**
  111077. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  111078. */
  111079. extensions,
  111080. /**
  111081. * Defines if mipmaps should not be generated (default is false)
  111082. */
  111083. noMipmap,
  111084. /**
  111085. * Defines the explicit list of files (undefined by default)
  111086. */
  111087. files) {
  111088. var _this = _super.call(this, name) || this;
  111089. _this.name = name;
  111090. _this.url = url;
  111091. _this.extensions = extensions;
  111092. _this.noMipmap = noMipmap;
  111093. _this.files = files;
  111094. return _this;
  111095. }
  111096. /**
  111097. * Execute the current task
  111098. * @param scene defines the scene where you want your assets to be loaded
  111099. * @param onSuccess is a callback called when the task is successfully executed
  111100. * @param onError is a callback called if an error occurs
  111101. */
  111102. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  111103. var onload = function () {
  111104. onSuccess();
  111105. };
  111106. var onerror = function (message, exception) {
  111107. onError(message, exception);
  111108. };
  111109. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  111110. };
  111111. return CubeTextureAssetTask;
  111112. }(AbstractAssetTask));
  111113. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  111114. /**
  111115. * Define a task used by AssetsManager to load HDR cube textures
  111116. */
  111117. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  111118. __extends(HDRCubeTextureAssetTask, _super);
  111119. /**
  111120. * Creates a new HDRCubeTextureAssetTask object
  111121. * @param name defines the name of the task
  111122. * @param url defines the location of the file to load
  111123. * @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.
  111124. * @param noMipmap defines if mipmaps should not be generated (default is false)
  111125. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  111126. * @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)
  111127. * @param reserved Internal use only
  111128. */
  111129. function HDRCubeTextureAssetTask(
  111130. /**
  111131. * Defines the name of the task
  111132. */
  111133. name,
  111134. /**
  111135. * Defines the location of the file to load
  111136. */
  111137. url,
  111138. /**
  111139. * Defines the desired size (the more it increases the longer the generation will be)
  111140. */
  111141. size,
  111142. /**
  111143. * Defines if mipmaps should not be generated (default is false)
  111144. */
  111145. noMipmap,
  111146. /**
  111147. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  111148. */
  111149. generateHarmonics,
  111150. /**
  111151. * 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)
  111152. */
  111153. gammaSpace,
  111154. /**
  111155. * Internal Use Only
  111156. */
  111157. reserved) {
  111158. if (noMipmap === void 0) { noMipmap = false; }
  111159. if (generateHarmonics === void 0) { generateHarmonics = true; }
  111160. if (gammaSpace === void 0) { gammaSpace = false; }
  111161. if (reserved === void 0) { reserved = false; }
  111162. var _this = _super.call(this, name) || this;
  111163. _this.name = name;
  111164. _this.url = url;
  111165. _this.size = size;
  111166. _this.noMipmap = noMipmap;
  111167. _this.generateHarmonics = generateHarmonics;
  111168. _this.gammaSpace = gammaSpace;
  111169. _this.reserved = reserved;
  111170. return _this;
  111171. }
  111172. /**
  111173. * Execute the current task
  111174. * @param scene defines the scene where you want your assets to be loaded
  111175. * @param onSuccess is a callback called when the task is successfully executed
  111176. * @param onError is a callback called if an error occurs
  111177. */
  111178. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  111179. var onload = function () {
  111180. onSuccess();
  111181. };
  111182. var onerror = function (message, exception) {
  111183. onError(message, exception);
  111184. };
  111185. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  111186. };
  111187. return HDRCubeTextureAssetTask;
  111188. }(AbstractAssetTask));
  111189. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  111190. /**
  111191. * This class can be used to easily import assets into a scene
  111192. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  111193. */
  111194. var AssetsManager = /** @class */ (function () {
  111195. /**
  111196. * Creates a new AssetsManager
  111197. * @param scene defines the scene to work on
  111198. */
  111199. function AssetsManager(scene) {
  111200. this._isLoading = false;
  111201. this._tasks = new Array();
  111202. this._waitingTasksCount = 0;
  111203. this._totalTasksCount = 0;
  111204. /**
  111205. * Observable called when all tasks are processed
  111206. */
  111207. this.onTaskSuccessObservable = new BABYLON.Observable();
  111208. /**
  111209. * Observable called when a task had an error
  111210. */
  111211. this.onTaskErrorObservable = new BABYLON.Observable();
  111212. /**
  111213. * Observable called when a task is successful
  111214. */
  111215. this.onTasksDoneObservable = new BABYLON.Observable();
  111216. /**
  111217. * Observable called when a task is done (whatever the result is)
  111218. */
  111219. this.onProgressObservable = new BABYLON.Observable();
  111220. /**
  111221. * Gets or sets a boolean defining if the AssetsManager should use the default loading screen
  111222. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  111223. */
  111224. this.useDefaultLoadingScreen = true;
  111225. this._scene = scene;
  111226. }
  111227. /**
  111228. * Add a MeshAssetTask to the list of active tasks
  111229. * @param taskName defines the name of the new task
  111230. * @param meshesNames defines the name of meshes to load
  111231. * @param rootUrl defines the root url to use to locate files
  111232. * @param sceneFilename defines the filename of the scene file
  111233. * @returns a new MeshAssetTask object
  111234. */
  111235. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  111236. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  111237. this._tasks.push(task);
  111238. return task;
  111239. };
  111240. /**
  111241. * Add a TextFileAssetTask to the list of active tasks
  111242. * @param taskName defines the name of the new task
  111243. * @param url defines the url of the file to load
  111244. * @returns a new TextFileAssetTask object
  111245. */
  111246. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  111247. var task = new TextFileAssetTask(taskName, url);
  111248. this._tasks.push(task);
  111249. return task;
  111250. };
  111251. /**
  111252. * Add a BinaryFileAssetTask to the list of active tasks
  111253. * @param taskName defines the name of the new task
  111254. * @param url defines the url of the file to load
  111255. * @returns a new BinaryFileAssetTask object
  111256. */
  111257. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  111258. var task = new BinaryFileAssetTask(taskName, url);
  111259. this._tasks.push(task);
  111260. return task;
  111261. };
  111262. /**
  111263. * Add a ImageAssetTask to the list of active tasks
  111264. * @param taskName defines the name of the new task
  111265. * @param url defines the url of the file to load
  111266. * @returns a new ImageAssetTask object
  111267. */
  111268. AssetsManager.prototype.addImageTask = function (taskName, url) {
  111269. var task = new ImageAssetTask(taskName, url);
  111270. this._tasks.push(task);
  111271. return task;
  111272. };
  111273. /**
  111274. * Add a TextureAssetTask to the list of active tasks
  111275. * @param taskName defines the name of the new task
  111276. * @param url defines the url of the file to load
  111277. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  111278. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  111279. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  111280. * @returns a new TextureAssetTask object
  111281. */
  111282. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  111283. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  111284. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  111285. this._tasks.push(task);
  111286. return task;
  111287. };
  111288. /**
  111289. * Add a CubeTextureAssetTask to the list of active tasks
  111290. * @param taskName defines the name of the new task
  111291. * @param url defines the url of the file to load
  111292. * @param extensions defines the extension to use to load the cube map (can be null)
  111293. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  111294. * @param files defines the list of files to load (can be null)
  111295. * @returns a new CubeTextureAssetTask object
  111296. */
  111297. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  111298. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  111299. this._tasks.push(task);
  111300. return task;
  111301. };
  111302. /**
  111303. *
  111304. * Add a HDRCubeTextureAssetTask to the list of active tasks
  111305. * @param taskName defines the name of the new task
  111306. * @param url defines the url of the file to load
  111307. * @param size defines the size you want for the cubemap (can be null)
  111308. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  111309. * @param generateHarmonics defines if you want to automatically generate (true by default)
  111310. * @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)
  111311. * @param reserved Internal use only
  111312. * @returns a new HDRCubeTextureAssetTask object
  111313. */
  111314. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  111315. if (noMipmap === void 0) { noMipmap = false; }
  111316. if (generateHarmonics === void 0) { generateHarmonics = true; }
  111317. if (gammaSpace === void 0) { gammaSpace = false; }
  111318. if (reserved === void 0) { reserved = false; }
  111319. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  111320. this._tasks.push(task);
  111321. return task;
  111322. };
  111323. /**
  111324. * Remove a task from the assets manager.
  111325. * @param task the task to remove
  111326. */
  111327. AssetsManager.prototype.removeTask = function (task) {
  111328. var index = this._tasks.indexOf(task);
  111329. if (index > -1) {
  111330. this._tasks.splice(index, 1);
  111331. }
  111332. };
  111333. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  111334. this._waitingTasksCount--;
  111335. try {
  111336. if (this.onProgress) {
  111337. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  111338. }
  111339. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  111340. }
  111341. catch (e) {
  111342. BABYLON.Tools.Error("Error running progress callbacks.");
  111343. console.log(e);
  111344. }
  111345. if (this._waitingTasksCount === 0) {
  111346. try {
  111347. if (this.onFinish) {
  111348. this.onFinish(this._tasks);
  111349. }
  111350. // Let's remove successfull tasks
  111351. var currentTasks = this._tasks.slice();
  111352. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  111353. var task = currentTasks_1[_i];
  111354. if (task.taskState === AssetTaskState.DONE) {
  111355. var index = this._tasks.indexOf(task);
  111356. if (index > -1) {
  111357. this._tasks.splice(index, 1);
  111358. }
  111359. }
  111360. }
  111361. this.onTasksDoneObservable.notifyObservers(this._tasks);
  111362. }
  111363. catch (e) {
  111364. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  111365. console.log(e);
  111366. }
  111367. this._isLoading = false;
  111368. this._scene.getEngine().hideLoadingUI();
  111369. }
  111370. };
  111371. AssetsManager.prototype._runTask = function (task) {
  111372. var _this = this;
  111373. var done = function () {
  111374. try {
  111375. if (_this.onTaskSuccess) {
  111376. _this.onTaskSuccess(task);
  111377. }
  111378. _this.onTaskSuccessObservable.notifyObservers(task);
  111379. _this._decreaseWaitingTasksCount(task);
  111380. }
  111381. catch (e) {
  111382. error("Error executing task success callbacks", e);
  111383. }
  111384. };
  111385. var error = function (message, exception) {
  111386. task._setErrorObject(message, exception);
  111387. if (_this.onTaskError) {
  111388. _this.onTaskError(task);
  111389. }
  111390. _this.onTaskErrorObservable.notifyObservers(task);
  111391. _this._decreaseWaitingTasksCount(task);
  111392. };
  111393. task.run(this._scene, done, error);
  111394. };
  111395. /**
  111396. * Reset the AssetsManager and remove all tasks
  111397. * @return the current instance of the AssetsManager
  111398. */
  111399. AssetsManager.prototype.reset = function () {
  111400. this._isLoading = false;
  111401. this._tasks = new Array();
  111402. return this;
  111403. };
  111404. /**
  111405. * Start the loading process
  111406. * @return the current instance of the AssetsManager
  111407. */
  111408. AssetsManager.prototype.load = function () {
  111409. if (this._isLoading) {
  111410. return this;
  111411. }
  111412. this._isLoading = true;
  111413. this._waitingTasksCount = this._tasks.length;
  111414. this._totalTasksCount = this._tasks.length;
  111415. if (this._waitingTasksCount === 0) {
  111416. this._isLoading = false;
  111417. if (this.onFinish) {
  111418. this.onFinish(this._tasks);
  111419. }
  111420. this.onTasksDoneObservable.notifyObservers(this._tasks);
  111421. return this;
  111422. }
  111423. if (this.useDefaultLoadingScreen) {
  111424. this._scene.getEngine().displayLoadingUI();
  111425. }
  111426. for (var index = 0; index < this._tasks.length; index++) {
  111427. var task = this._tasks[index];
  111428. if (task.taskState === AssetTaskState.INIT) {
  111429. this._runTask(task);
  111430. }
  111431. }
  111432. return this;
  111433. };
  111434. return AssetsManager;
  111435. }());
  111436. BABYLON.AssetsManager = AssetsManager;
  111437. })(BABYLON || (BABYLON = {}));
  111438. //# sourceMappingURL=babylon.assetsManager.js.map
  111439. var BABYLON;
  111440. (function (BABYLON) {
  111441. var serializedGeometries = [];
  111442. var serializeGeometry = function (geometry, serializationGeometries) {
  111443. if (serializedGeometries[geometry.id]) {
  111444. return;
  111445. }
  111446. if (geometry.doNotSerialize) {
  111447. return;
  111448. }
  111449. if (geometry instanceof BABYLON.BoxGeometry) {
  111450. serializationGeometries.boxes.push(geometry.serialize());
  111451. }
  111452. else if (geometry instanceof BABYLON.SphereGeometry) {
  111453. serializationGeometries.spheres.push(geometry.serialize());
  111454. }
  111455. else if (geometry instanceof BABYLON.CylinderGeometry) {
  111456. serializationGeometries.cylinders.push(geometry.serialize());
  111457. }
  111458. else if (geometry instanceof BABYLON.TorusGeometry) {
  111459. serializationGeometries.toruses.push(geometry.serialize());
  111460. }
  111461. else if (geometry instanceof BABYLON.GroundGeometry) {
  111462. serializationGeometries.grounds.push(geometry.serialize());
  111463. }
  111464. else if (geometry instanceof BABYLON.Plane) {
  111465. serializationGeometries.planes.push(geometry.serialize());
  111466. }
  111467. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  111468. serializationGeometries.torusKnots.push(geometry.serialize());
  111469. }
  111470. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  111471. throw new Error("Unknown primitive type");
  111472. }
  111473. else {
  111474. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  111475. }
  111476. serializedGeometries[geometry.id] = true;
  111477. };
  111478. var serializeMesh = function (mesh, serializationScene) {
  111479. var serializationObject = {};
  111480. // Geometry
  111481. var geometry = mesh._geometry;
  111482. if (geometry) {
  111483. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  111484. // 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
  111485. serializeGeometry(geometry, serializationScene.geometries);
  111486. }
  111487. }
  111488. // Custom
  111489. if (mesh.serialize) {
  111490. mesh.serialize(serializationObject);
  111491. }
  111492. return serializationObject;
  111493. };
  111494. var finalizeSingleMesh = function (mesh, serializationObject) {
  111495. //only works if the mesh is already loaded
  111496. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  111497. //serialize material
  111498. if (mesh.material) {
  111499. if (mesh.material instanceof BABYLON.MultiMaterial) {
  111500. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  111501. serializationObject.materials = serializationObject.materials || [];
  111502. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  111503. serializationObject.multiMaterials.push(mesh.material.serialize());
  111504. var _loop_1 = function (submaterial) {
  111505. if (submaterial) {
  111506. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  111507. serializationObject.materials.push(submaterial.serialize());
  111508. }
  111509. }
  111510. };
  111511. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  111512. var submaterial = _a[_i];
  111513. _loop_1(submaterial);
  111514. }
  111515. }
  111516. }
  111517. else {
  111518. serializationObject.materials = serializationObject.materials || [];
  111519. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  111520. serializationObject.materials.push(mesh.material.serialize());
  111521. }
  111522. }
  111523. }
  111524. //serialize geometry
  111525. var geometry = mesh._geometry;
  111526. if (geometry) {
  111527. if (!serializationObject.geometries) {
  111528. serializationObject.geometries = {};
  111529. serializationObject.geometries.boxes = [];
  111530. serializationObject.geometries.spheres = [];
  111531. serializationObject.geometries.cylinders = [];
  111532. serializationObject.geometries.toruses = [];
  111533. serializationObject.geometries.grounds = [];
  111534. serializationObject.geometries.planes = [];
  111535. serializationObject.geometries.torusKnots = [];
  111536. serializationObject.geometries.vertexData = [];
  111537. }
  111538. serializeGeometry(geometry, serializationObject.geometries);
  111539. }
  111540. // Skeletons
  111541. if (mesh.skeleton) {
  111542. serializationObject.skeletons = serializationObject.skeletons || [];
  111543. serializationObject.skeletons.push(mesh.skeleton.serialize());
  111544. }
  111545. //serialize the actual mesh
  111546. serializationObject.meshes = serializationObject.meshes || [];
  111547. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  111548. }
  111549. };
  111550. /**
  111551. * Class used to serialize a scene into a string
  111552. */
  111553. var SceneSerializer = /** @class */ (function () {
  111554. function SceneSerializer() {
  111555. }
  111556. /**
  111557. * Clear cache used by a previous serialization
  111558. */
  111559. SceneSerializer.ClearCache = function () {
  111560. serializedGeometries = [];
  111561. };
  111562. /**
  111563. * Serialize a scene into a JSON compatible object
  111564. * @param scene defines the scene to serialize
  111565. * @returns a JSON compatible object
  111566. */
  111567. SceneSerializer.Serialize = function (scene) {
  111568. var serializationObject = {};
  111569. SceneSerializer.ClearCache();
  111570. // Scene
  111571. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  111572. serializationObject.autoClear = scene.autoClear;
  111573. serializationObject.clearColor = scene.clearColor.asArray();
  111574. serializationObject.ambientColor = scene.ambientColor.asArray();
  111575. serializationObject.gravity = scene.gravity.asArray();
  111576. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  111577. serializationObject.workerCollisions = scene.workerCollisions;
  111578. // Fog
  111579. if (scene.fogMode && scene.fogMode !== 0) {
  111580. serializationObject.fogMode = scene.fogMode;
  111581. serializationObject.fogColor = scene.fogColor.asArray();
  111582. serializationObject.fogStart = scene.fogStart;
  111583. serializationObject.fogEnd = scene.fogEnd;
  111584. serializationObject.fogDensity = scene.fogDensity;
  111585. }
  111586. //Physics
  111587. if (scene.isPhysicsEnabled()) {
  111588. var physicEngine = scene.getPhysicsEngine();
  111589. if (physicEngine) {
  111590. serializationObject.physicsEnabled = true;
  111591. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  111592. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  111593. }
  111594. }
  111595. // Metadata
  111596. if (scene.metadata) {
  111597. serializationObject.metadata = scene.metadata;
  111598. }
  111599. // Morph targets
  111600. serializationObject.morphTargetManagers = [];
  111601. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  111602. var abstractMesh = _a[_i];
  111603. var manager = abstractMesh.morphTargetManager;
  111604. if (manager) {
  111605. serializationObject.morphTargetManagers.push(manager.serialize());
  111606. }
  111607. }
  111608. // Lights
  111609. serializationObject.lights = [];
  111610. var index;
  111611. var light;
  111612. for (index = 0; index < scene.lights.length; index++) {
  111613. light = scene.lights[index];
  111614. if (!light.doNotSerialize) {
  111615. serializationObject.lights.push(light.serialize());
  111616. }
  111617. }
  111618. // Cameras
  111619. serializationObject.cameras = [];
  111620. for (index = 0; index < scene.cameras.length; index++) {
  111621. var camera = scene.cameras[index];
  111622. if (!camera.doNotSerialize) {
  111623. serializationObject.cameras.push(camera.serialize());
  111624. }
  111625. }
  111626. if (scene.activeCamera) {
  111627. serializationObject.activeCameraID = scene.activeCamera.id;
  111628. }
  111629. // Animations
  111630. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  111631. // Materials
  111632. serializationObject.materials = [];
  111633. serializationObject.multiMaterials = [];
  111634. var material;
  111635. for (index = 0; index < scene.materials.length; index++) {
  111636. material = scene.materials[index];
  111637. if (!material.doNotSerialize) {
  111638. serializationObject.materials.push(material.serialize());
  111639. }
  111640. }
  111641. // MultiMaterials
  111642. serializationObject.multiMaterials = [];
  111643. for (index = 0; index < scene.multiMaterials.length; index++) {
  111644. var multiMaterial = scene.multiMaterials[index];
  111645. serializationObject.multiMaterials.push(multiMaterial.serialize());
  111646. }
  111647. // Environment texture
  111648. if (scene.environmentTexture) {
  111649. serializationObject.environmentTexture = scene.environmentTexture.name;
  111650. }
  111651. // Skeletons
  111652. serializationObject.skeletons = [];
  111653. for (index = 0; index < scene.skeletons.length; index++) {
  111654. var skeleton = scene.skeletons[index];
  111655. if (!skeleton.doNotSerialize) {
  111656. serializationObject.skeletons.push(skeleton.serialize());
  111657. }
  111658. }
  111659. // Transform nodes
  111660. serializationObject.transformNodes = [];
  111661. for (index = 0; index < scene.transformNodes.length; index++) {
  111662. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  111663. }
  111664. // Geometries
  111665. serializationObject.geometries = {};
  111666. serializationObject.geometries.boxes = [];
  111667. serializationObject.geometries.spheres = [];
  111668. serializationObject.geometries.cylinders = [];
  111669. serializationObject.geometries.toruses = [];
  111670. serializationObject.geometries.grounds = [];
  111671. serializationObject.geometries.planes = [];
  111672. serializationObject.geometries.torusKnots = [];
  111673. serializationObject.geometries.vertexData = [];
  111674. serializedGeometries = [];
  111675. var geometries = scene.getGeometries();
  111676. for (index = 0; index < geometries.length; index++) {
  111677. var geometry = geometries[index];
  111678. if (geometry.isReady()) {
  111679. serializeGeometry(geometry, serializationObject.geometries);
  111680. }
  111681. }
  111682. // Meshes
  111683. serializationObject.meshes = [];
  111684. for (index = 0; index < scene.meshes.length; index++) {
  111685. var abstractMesh = scene.meshes[index];
  111686. if (abstractMesh instanceof BABYLON.Mesh) {
  111687. var mesh = abstractMesh;
  111688. if (!mesh.doNotSerialize) {
  111689. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  111690. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  111691. }
  111692. }
  111693. }
  111694. }
  111695. // Particles Systems
  111696. serializationObject.particleSystems = [];
  111697. for (index = 0; index < scene.particleSystems.length; index++) {
  111698. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  111699. }
  111700. // Action Manager
  111701. if (scene.actionManager) {
  111702. serializationObject.actions = scene.actionManager.serialize("scene");
  111703. }
  111704. // Components
  111705. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  111706. var component = _c[_b];
  111707. component.serialize(serializationObject);
  111708. }
  111709. return serializationObject;
  111710. };
  111711. /**
  111712. * Serialize a mesh into a JSON compatible object
  111713. * @param toSerialize defines the mesh to serialize
  111714. * @param withParents defines if parents must be serialized as well
  111715. * @param withChildren defines if children must be serialized as well
  111716. * @returns a JSON compatible object
  111717. */
  111718. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  111719. if (withParents === void 0) { withParents = false; }
  111720. if (withChildren === void 0) { withChildren = false; }
  111721. var serializationObject = {};
  111722. SceneSerializer.ClearCache();
  111723. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  111724. if (withParents || withChildren) {
  111725. //deliberate for loop! not for each, appended should be processed as well.
  111726. for (var i = 0; i < toSerialize.length; ++i) {
  111727. if (withChildren) {
  111728. toSerialize[i].getDescendants().forEach(function (node) {
  111729. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  111730. toSerialize.push(node);
  111731. }
  111732. });
  111733. }
  111734. //make sure the array doesn't contain the object already
  111735. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  111736. toSerialize.push(toSerialize[i].parent);
  111737. }
  111738. }
  111739. }
  111740. toSerialize.forEach(function (mesh) {
  111741. finalizeSingleMesh(mesh, serializationObject);
  111742. });
  111743. return serializationObject;
  111744. };
  111745. return SceneSerializer;
  111746. }());
  111747. BABYLON.SceneSerializer = SceneSerializer;
  111748. })(BABYLON || (BABYLON = {}));
  111749. //# sourceMappingURL=babylon.sceneSerializer.js.map
  111750. var BABYLON;
  111751. (function (BABYLON) {
  111752. /**
  111753. * Class used to generate realtime reflection / refraction cube textures
  111754. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  111755. */
  111756. var ReflectionProbe = /** @class */ (function () {
  111757. /**
  111758. * Creates a new reflection probe
  111759. * @param name defines the name of the probe
  111760. * @param size defines the texture resolution (for each face)
  111761. * @param scene defines the hosting scene
  111762. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  111763. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  111764. */
  111765. function ReflectionProbe(
  111766. /** defines the name of the probe */
  111767. name, size, scene, generateMipMaps, useFloat) {
  111768. if (generateMipMaps === void 0) { generateMipMaps = true; }
  111769. if (useFloat === void 0) { useFloat = false; }
  111770. var _this = this;
  111771. this.name = name;
  111772. this._viewMatrix = BABYLON.Matrix.Identity();
  111773. this._target = BABYLON.Vector3.Zero();
  111774. this._add = BABYLON.Vector3.Zero();
  111775. this._invertYAxis = false;
  111776. /** Gets or sets probe position (center of the cube map) */
  111777. this.position = BABYLON.Vector3.Zero();
  111778. this._scene = scene;
  111779. // Create the scene field if not exist.
  111780. if (!this._scene.reflectionProbes) {
  111781. this._scene.reflectionProbes = new Array();
  111782. }
  111783. this._scene.reflectionProbes.push(this);
  111784. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  111785. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  111786. switch (faceIndex) {
  111787. case 0:
  111788. _this._add.copyFromFloats(1, 0, 0);
  111789. break;
  111790. case 1:
  111791. _this._add.copyFromFloats(-1, 0, 0);
  111792. break;
  111793. case 2:
  111794. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  111795. break;
  111796. case 3:
  111797. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  111798. break;
  111799. case 4:
  111800. _this._add.copyFromFloats(0, 0, 1);
  111801. break;
  111802. case 5:
  111803. _this._add.copyFromFloats(0, 0, -1);
  111804. break;
  111805. }
  111806. if (_this._attachedMesh) {
  111807. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  111808. }
  111809. _this.position.addToRef(_this._add, _this._target);
  111810. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  111811. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  111812. scene._forcedViewPosition = _this.position;
  111813. });
  111814. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  111815. scene._forcedViewPosition = null;
  111816. scene.updateTransformMatrix(true);
  111817. });
  111818. if (scene.activeCamera) {
  111819. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  111820. }
  111821. }
  111822. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  111823. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  111824. get: function () {
  111825. return this._renderTargetTexture.samples;
  111826. },
  111827. set: function (value) {
  111828. this._renderTargetTexture.samples = value;
  111829. },
  111830. enumerable: true,
  111831. configurable: true
  111832. });
  111833. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  111834. /** Gets or sets the refresh rate to use (on every frame by default) */
  111835. get: function () {
  111836. return this._renderTargetTexture.refreshRate;
  111837. },
  111838. set: function (value) {
  111839. this._renderTargetTexture.refreshRate = value;
  111840. },
  111841. enumerable: true,
  111842. configurable: true
  111843. });
  111844. /**
  111845. * Gets the hosting scene
  111846. * @returns a Scene
  111847. */
  111848. ReflectionProbe.prototype.getScene = function () {
  111849. return this._scene;
  111850. };
  111851. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  111852. /** Gets the internal CubeTexture used to render to */
  111853. get: function () {
  111854. return this._renderTargetTexture;
  111855. },
  111856. enumerable: true,
  111857. configurable: true
  111858. });
  111859. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  111860. /** Gets the list of meshes to render */
  111861. get: function () {
  111862. return this._renderTargetTexture.renderList;
  111863. },
  111864. enumerable: true,
  111865. configurable: true
  111866. });
  111867. /**
  111868. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  111869. * @param mesh defines the mesh to attach to
  111870. */
  111871. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  111872. this._attachedMesh = mesh;
  111873. };
  111874. /**
  111875. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  111876. * @param renderingGroupId The rendering group id corresponding to its index
  111877. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  111878. */
  111879. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  111880. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  111881. };
  111882. /**
  111883. * Clean all associated resources
  111884. */
  111885. ReflectionProbe.prototype.dispose = function () {
  111886. var index = this._scene.reflectionProbes.indexOf(this);
  111887. if (index !== -1) {
  111888. // Remove from the scene if found
  111889. this._scene.reflectionProbes.splice(index, 1);
  111890. }
  111891. if (this._renderTargetTexture) {
  111892. this._renderTargetTexture.dispose();
  111893. this._renderTargetTexture = null;
  111894. }
  111895. };
  111896. return ReflectionProbe;
  111897. }());
  111898. BABYLON.ReflectionProbe = ReflectionProbe;
  111899. })(BABYLON || (BABYLON = {}));
  111900. //# sourceMappingURL=babylon.reflectionProbe.js.map
  111901. var BABYLON;
  111902. (function (BABYLON) {
  111903. /**
  111904. * Defines the layer scene component responsible to manage any layers
  111905. * in a given scene.
  111906. */
  111907. var LayerSceneComponent = /** @class */ (function () {
  111908. /**
  111909. * Creates a new instance of the component for the given scene
  111910. * @param scene Defines the scene to register the component in
  111911. */
  111912. function LayerSceneComponent(scene) {
  111913. /**
  111914. * The component name helpfull to identify the component in the list of scene components.
  111915. */
  111916. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  111917. this.scene = scene;
  111918. this._engine = scene.getEngine();
  111919. scene.layers = new Array();
  111920. }
  111921. /**
  111922. * Registers the component in a given scene
  111923. */
  111924. LayerSceneComponent.prototype.register = function () {
  111925. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  111926. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  111927. };
  111928. /**
  111929. * Rebuilds the elements related to this component in case of
  111930. * context lost for instance.
  111931. */
  111932. LayerSceneComponent.prototype.rebuild = function () {
  111933. var layers = this.scene.layers;
  111934. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  111935. var layer = layers_1[_i];
  111936. layer._rebuild();
  111937. }
  111938. };
  111939. /**
  111940. * Disposes the component and the associated ressources.
  111941. */
  111942. LayerSceneComponent.prototype.dispose = function () {
  111943. var layers = this.scene.layers;
  111944. while (layers.length) {
  111945. layers[0].dispose();
  111946. }
  111947. };
  111948. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  111949. var layers = this.scene.layers;
  111950. if (layers.length) {
  111951. this._engine.setDepthBuffer(false);
  111952. var cameraLayerMask = camera.layerMask;
  111953. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  111954. var layer = layers_2[_i];
  111955. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  111956. layer.render();
  111957. }
  111958. }
  111959. this._engine.setDepthBuffer(true);
  111960. }
  111961. };
  111962. LayerSceneComponent.prototype._drawBackground = function (camera) {
  111963. this._draw(camera, true);
  111964. };
  111965. LayerSceneComponent.prototype._drawForeground = function (camera) {
  111966. this._draw(camera, false);
  111967. };
  111968. return LayerSceneComponent;
  111969. }());
  111970. BABYLON.LayerSceneComponent = LayerSceneComponent;
  111971. })(BABYLON || (BABYLON = {}));
  111972. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  111973. var BABYLON;
  111974. (function (BABYLON) {
  111975. /**
  111976. * This represents a full screen 2d layer.
  111977. * This can be usefull to display a picture in the background of your scene for instance.
  111978. * @see https://www.babylonjs-playground.com/#08A2BS#1
  111979. */
  111980. var Layer = /** @class */ (function () {
  111981. /**
  111982. * Instantiates a new layer.
  111983. * This represents a full screen 2d layer.
  111984. * This can be usefull to display a picture in the background of your scene for instance.
  111985. * @see https://www.babylonjs-playground.com/#08A2BS#1
  111986. * @param name Define the name of the layer in the scene
  111987. * @param imgUrl Define the url of the texture to display in the layer
  111988. * @param scene Define the scene the layer belongs to
  111989. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  111990. * @param color Defines a color for the layer
  111991. */
  111992. function Layer(
  111993. /**
  111994. * Define the name of the layer.
  111995. */
  111996. name, imgUrl, scene, isBackground, color) {
  111997. this.name = name;
  111998. /**
  111999. * Define the scale of the layer in order to zoom in out of the texture.
  112000. */
  112001. this.scale = new BABYLON.Vector2(1, 1);
  112002. /**
  112003. * Define an offset for the layer in order to shift the texture.
  112004. */
  112005. this.offset = new BABYLON.Vector2(0, 0);
  112006. /**
  112007. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  112008. */
  112009. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  112010. /**
  112011. * Define a mask to restrict the layer to only some of the scene cameras.
  112012. */
  112013. this.layerMask = 0x0FFFFFFF;
  112014. this._vertexBuffers = {};
  112015. /**
  112016. * An event triggered when the layer is disposed.
  112017. */
  112018. this.onDisposeObservable = new BABYLON.Observable();
  112019. /**
  112020. * An event triggered before rendering the scene
  112021. */
  112022. this.onBeforeRenderObservable = new BABYLON.Observable();
  112023. /**
  112024. * An event triggered after rendering the scene
  112025. */
  112026. this.onAfterRenderObservable = new BABYLON.Observable();
  112027. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  112028. this.isBackground = isBackground === undefined ? true : isBackground;
  112029. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  112030. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  112031. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  112032. if (!layerComponent) {
  112033. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  112034. this._scene._addComponent(layerComponent);
  112035. }
  112036. this._scene.layers.push(this);
  112037. var engine = this._scene.getEngine();
  112038. // VBO
  112039. var vertices = [];
  112040. vertices.push(1, 1);
  112041. vertices.push(-1, 1);
  112042. vertices.push(-1, -1);
  112043. vertices.push(1, -1);
  112044. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  112045. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  112046. this._createIndexBuffer();
  112047. // Effects
  112048. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  112049. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  112050. }
  112051. Object.defineProperty(Layer.prototype, "onDispose", {
  112052. /**
  112053. * Back compatibility with callback before the onDisposeObservable existed.
  112054. * The set callback will be triggered when the layer has been disposed.
  112055. */
  112056. set: function (callback) {
  112057. if (this._onDisposeObserver) {
  112058. this.onDisposeObservable.remove(this._onDisposeObserver);
  112059. }
  112060. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  112061. },
  112062. enumerable: true,
  112063. configurable: true
  112064. });
  112065. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  112066. /**
  112067. * Back compatibility with callback before the onBeforeRenderObservable existed.
  112068. * The set callback will be triggered just before rendering the layer.
  112069. */
  112070. set: function (callback) {
  112071. if (this._onBeforeRenderObserver) {
  112072. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  112073. }
  112074. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  112075. },
  112076. enumerable: true,
  112077. configurable: true
  112078. });
  112079. Object.defineProperty(Layer.prototype, "onAfterRender", {
  112080. /**
  112081. * Back compatibility with callback before the onAfterRenderObservable existed.
  112082. * The set callback will be triggered just after rendering the layer.
  112083. */
  112084. set: function (callback) {
  112085. if (this._onAfterRenderObserver) {
  112086. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  112087. }
  112088. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  112089. },
  112090. enumerable: true,
  112091. configurable: true
  112092. });
  112093. Layer.prototype._createIndexBuffer = function () {
  112094. var engine = this._scene.getEngine();
  112095. // Indices
  112096. var indices = [];
  112097. indices.push(0);
  112098. indices.push(1);
  112099. indices.push(2);
  112100. indices.push(0);
  112101. indices.push(2);
  112102. indices.push(3);
  112103. this._indexBuffer = engine.createIndexBuffer(indices);
  112104. };
  112105. /** @hidden */
  112106. Layer.prototype._rebuild = function () {
  112107. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  112108. if (vb) {
  112109. vb._rebuild();
  112110. }
  112111. this._createIndexBuffer();
  112112. };
  112113. /**
  112114. * Renders the layer in the scene.
  112115. */
  112116. Layer.prototype.render = function () {
  112117. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  112118. // Check
  112119. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady()) {
  112120. return;
  112121. }
  112122. var engine = this._scene.getEngine();
  112123. this.onBeforeRenderObservable.notifyObservers(this);
  112124. // Render
  112125. engine.enableEffect(currentEffect);
  112126. engine.setState(false);
  112127. // Texture
  112128. currentEffect.setTexture("textureSampler", this.texture);
  112129. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  112130. // Color
  112131. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  112132. // Scale / offset
  112133. currentEffect.setVector2("offset", this.offset);
  112134. currentEffect.setVector2("scale", this.scale);
  112135. // VBOs
  112136. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  112137. // Draw order
  112138. if (!this.alphaTest) {
  112139. engine.setAlphaMode(this.alphaBlendingMode);
  112140. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  112141. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  112142. }
  112143. else {
  112144. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  112145. }
  112146. this.onAfterRenderObservable.notifyObservers(this);
  112147. };
  112148. /**
  112149. * Disposes and releases the associated ressources.
  112150. */
  112151. Layer.prototype.dispose = function () {
  112152. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  112153. if (vertexBuffer) {
  112154. vertexBuffer.dispose();
  112155. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  112156. }
  112157. if (this._indexBuffer) {
  112158. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  112159. this._indexBuffer = null;
  112160. }
  112161. if (this.texture) {
  112162. this.texture.dispose();
  112163. this.texture = null;
  112164. }
  112165. // Remove from scene
  112166. var index = this._scene.layers.indexOf(this);
  112167. this._scene.layers.splice(index, 1);
  112168. // Callback
  112169. this.onDisposeObservable.notifyObservers(this);
  112170. this.onDisposeObservable.clear();
  112171. this.onAfterRenderObservable.clear();
  112172. this.onBeforeRenderObservable.clear();
  112173. };
  112174. return Layer;
  112175. }());
  112176. BABYLON.Layer = Layer;
  112177. })(BABYLON || (BABYLON = {}));
  112178. //# sourceMappingURL=babylon.layer.js.map
  112179. var BABYLON;
  112180. (function (BABYLON) {
  112181. /**
  112182. * Class used to host texture specific utilities
  112183. */
  112184. var TextureTools = /** @class */ (function () {
  112185. function TextureTools() {
  112186. }
  112187. /**
  112188. * Uses the GPU to create a copy texture rescaled at a given size
  112189. * @param texture Texture to copy from
  112190. * @param width defines the desired width
  112191. * @param height defines the desired height
  112192. * @param useBilinearMode defines if bilinear mode has to be used
  112193. * @return the generated texture
  112194. */
  112195. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  112196. if (useBilinearMode === void 0) { useBilinearMode = true; }
  112197. var scene = texture.getScene();
  112198. var engine = scene.getEngine();
  112199. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  112200. rtt.wrapU = texture.wrapU;
  112201. rtt.wrapV = texture.wrapV;
  112202. rtt.uOffset = texture.uOffset;
  112203. rtt.vOffset = texture.vOffset;
  112204. rtt.uScale = texture.uScale;
  112205. rtt.vScale = texture.vScale;
  112206. rtt.uAng = texture.uAng;
  112207. rtt.vAng = texture.vAng;
  112208. rtt.wAng = texture.wAng;
  112209. rtt.coordinatesIndex = texture.coordinatesIndex;
  112210. rtt.level = texture.level;
  112211. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  112212. rtt._texture.isReady = false;
  112213. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112214. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112215. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  112216. passPostProcess.getEffect().executeWhenCompiled(function () {
  112217. passPostProcess.onApply = function (effect) {
  112218. effect.setTexture("textureSampler", texture);
  112219. };
  112220. var internalTexture = rtt.getInternalTexture();
  112221. if (internalTexture) {
  112222. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  112223. engine.unBindFramebuffer(internalTexture);
  112224. rtt.disposeFramebufferObjects();
  112225. passPostProcess.dispose();
  112226. internalTexture.isReady = true;
  112227. }
  112228. });
  112229. return rtt;
  112230. };
  112231. /**
  112232. * Gets an environment BRDF texture for a given scene
  112233. * @param scene defines the hosting scene
  112234. * @returns the environment BRDF texture
  112235. */
  112236. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  112237. if (!scene._environmentBRDFTexture) {
  112238. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  112239. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112240. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112241. scene._environmentBRDFTexture = texture;
  112242. }
  112243. return scene._environmentBRDFTexture;
  112244. };
  112245. 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=";
  112246. return TextureTools;
  112247. }());
  112248. BABYLON.TextureTools = TextureTools;
  112249. })(BABYLON || (BABYLON = {}));
  112250. //# sourceMappingURL=babylon.textureTools.js.map
  112251. var BABYLON;
  112252. (function (BABYLON) {
  112253. /**
  112254. * The framing behavior (BABYLON.FramingBehavior) is designed to automatically position an ArcRotateCamera when its target is set to a mesh. It is also useful if you want to prevent the camera to go under a virtual horizontal plane.
  112255. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  112256. */
  112257. var FramingBehavior = /** @class */ (function () {
  112258. function FramingBehavior() {
  112259. this._mode = FramingBehavior.FitFrustumSidesMode;
  112260. this._radiusScale = 1.0;
  112261. this._positionScale = 0.5;
  112262. this._defaultElevation = 0.3;
  112263. this._elevationReturnTime = 1500;
  112264. this._elevationReturnWaitTime = 1000;
  112265. this._zoomStopsAnimation = false;
  112266. this._framingTime = 1500;
  112267. /**
  112268. * Define if the behavior should automatically change the configured
  112269. * camera limits and sensibilities.
  112270. */
  112271. this.autoCorrectCameraLimitsAndSensibility = true;
  112272. this._isPointerDown = false;
  112273. this._lastInteractionTime = -Infinity;
  112274. // Framing control
  112275. this._animatables = new Array();
  112276. this._betaIsAnimating = false;
  112277. }
  112278. Object.defineProperty(FramingBehavior.prototype, "name", {
  112279. /**
  112280. * Gets the name of the behavior.
  112281. */
  112282. get: function () {
  112283. return "Framing";
  112284. },
  112285. enumerable: true,
  112286. configurable: true
  112287. });
  112288. Object.defineProperty(FramingBehavior.prototype, "mode", {
  112289. /**
  112290. * Gets current mode used by the behavior.
  112291. */
  112292. get: function () {
  112293. return this._mode;
  112294. },
  112295. /**
  112296. * Sets the current mode used by the behavior
  112297. */
  112298. set: function (mode) {
  112299. this._mode = mode;
  112300. },
  112301. enumerable: true,
  112302. configurable: true
  112303. });
  112304. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  112305. /**
  112306. * Gets the scale applied to the radius
  112307. */
  112308. get: function () {
  112309. return this._radiusScale;
  112310. },
  112311. /**
  112312. * Sets the scale applied to the radius (1 by default)
  112313. */
  112314. set: function (radius) {
  112315. this._radiusScale = radius;
  112316. },
  112317. enumerable: true,
  112318. configurable: true
  112319. });
  112320. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  112321. /**
  112322. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  112323. */
  112324. get: function () {
  112325. return this._positionScale;
  112326. },
  112327. /**
  112328. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  112329. */
  112330. set: function (scale) {
  112331. this._positionScale = scale;
  112332. },
  112333. enumerable: true,
  112334. configurable: true
  112335. });
  112336. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  112337. /**
  112338. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  112339. * behaviour is triggered, in radians.
  112340. */
  112341. get: function () {
  112342. return this._defaultElevation;
  112343. },
  112344. /**
  112345. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  112346. * behaviour is triggered, in radians.
  112347. */
  112348. set: function (elevation) {
  112349. this._defaultElevation = elevation;
  112350. },
  112351. enumerable: true,
  112352. configurable: true
  112353. });
  112354. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  112355. /**
  112356. * Gets the time (in milliseconds) taken to return to the default beta position.
  112357. * Negative value indicates camera should not return to default.
  112358. */
  112359. get: function () {
  112360. return this._elevationReturnTime;
  112361. },
  112362. /**
  112363. * Sets the time (in milliseconds) taken to return to the default beta position.
  112364. * Negative value indicates camera should not return to default.
  112365. */
  112366. set: function (speed) {
  112367. this._elevationReturnTime = speed;
  112368. },
  112369. enumerable: true,
  112370. configurable: true
  112371. });
  112372. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  112373. /**
  112374. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  112375. */
  112376. get: function () {
  112377. return this._elevationReturnWaitTime;
  112378. },
  112379. /**
  112380. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  112381. */
  112382. set: function (time) {
  112383. this._elevationReturnWaitTime = time;
  112384. },
  112385. enumerable: true,
  112386. configurable: true
  112387. });
  112388. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  112389. /**
  112390. * Gets the flag that indicates if user zooming should stop animation.
  112391. */
  112392. get: function () {
  112393. return this._zoomStopsAnimation;
  112394. },
  112395. /**
  112396. * Sets the flag that indicates if user zooming should stop animation.
  112397. */
  112398. set: function (flag) {
  112399. this._zoomStopsAnimation = flag;
  112400. },
  112401. enumerable: true,
  112402. configurable: true
  112403. });
  112404. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  112405. /**
  112406. * Gets the transition time when framing the mesh, in milliseconds
  112407. */
  112408. get: function () {
  112409. return this._framingTime;
  112410. },
  112411. /**
  112412. * Sets the transition time when framing the mesh, in milliseconds
  112413. */
  112414. set: function (time) {
  112415. this._framingTime = time;
  112416. },
  112417. enumerable: true,
  112418. configurable: true
  112419. });
  112420. /**
  112421. * Initializes the behavior.
  112422. */
  112423. FramingBehavior.prototype.init = function () {
  112424. // Do notihng
  112425. };
  112426. /**
  112427. * Attaches the behavior to its arc rotate camera.
  112428. * @param camera Defines the camera to attach the behavior to
  112429. */
  112430. FramingBehavior.prototype.attach = function (camera) {
  112431. var _this = this;
  112432. this._attachedCamera = camera;
  112433. var scene = this._attachedCamera.getScene();
  112434. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  112435. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  112436. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  112437. _this._isPointerDown = true;
  112438. return;
  112439. }
  112440. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  112441. _this._isPointerDown = false;
  112442. }
  112443. });
  112444. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  112445. if (mesh) {
  112446. _this.zoomOnMesh(mesh);
  112447. }
  112448. });
  112449. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  112450. // Stop the animation if there is user interaction and the animation should stop for this interaction
  112451. _this._applyUserInteraction();
  112452. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  112453. // back to the default position after a given timeout
  112454. _this._maintainCameraAboveGround();
  112455. });
  112456. };
  112457. /**
  112458. * Detaches the behavior from its current arc rotate camera.
  112459. */
  112460. FramingBehavior.prototype.detach = function () {
  112461. if (!this._attachedCamera) {
  112462. return;
  112463. }
  112464. var scene = this._attachedCamera.getScene();
  112465. if (this._onPrePointerObservableObserver) {
  112466. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  112467. }
  112468. if (this._onAfterCheckInputsObserver) {
  112469. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  112470. }
  112471. if (this._onMeshTargetChangedObserver) {
  112472. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  112473. }
  112474. this._attachedCamera = null;
  112475. };
  112476. /**
  112477. * Targets the given mesh and updates zoom level accordingly.
  112478. * @param mesh The mesh to target.
  112479. * @param radius Optional. If a cached radius position already exists, overrides default.
  112480. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  112481. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112482. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112483. */
  112484. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  112485. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112486. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112487. mesh.computeWorldMatrix(true);
  112488. var boundingBox = mesh.getBoundingInfo().boundingBox;
  112489. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  112490. };
  112491. /**
  112492. * Targets the given mesh with its children and updates zoom level accordingly.
  112493. * @param mesh The mesh to target.
  112494. * @param radius Optional. If a cached radius position already exists, overrides default.
  112495. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  112496. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112497. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112498. */
  112499. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  112500. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112501. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112502. mesh.computeWorldMatrix(true);
  112503. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  112504. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  112505. };
  112506. /**
  112507. * Targets the given meshes with their children and updates zoom level accordingly.
  112508. * @param meshes The mesh to target.
  112509. * @param radius Optional. If a cached radius position already exists, overrides default.
  112510. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  112511. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112512. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112513. */
  112514. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  112515. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112516. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112517. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  112518. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  112519. for (var i = 0; i < meshes.length; i++) {
  112520. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  112521. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  112522. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  112523. }
  112524. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  112525. };
  112526. /**
  112527. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  112528. * @param minimumWorld Determines the smaller position of the bounding box extend
  112529. * @param maximumWorld Determines the bigger position of the bounding box extend
  112530. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112531. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112532. */
  112533. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  112534. var _this = this;
  112535. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112536. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112537. var zoomTarget;
  112538. if (!this._attachedCamera) {
  112539. return;
  112540. }
  112541. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  112542. var bottom = minimumWorld.y;
  112543. var top = maximumWorld.y;
  112544. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  112545. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  112546. if (focusOnOriginXZ) {
  112547. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  112548. }
  112549. else {
  112550. var centerWorld = minimumWorld.add(radiusWorld);
  112551. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  112552. }
  112553. if (!this._vectorTransition) {
  112554. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  112555. }
  112556. this._betaIsAnimating = true;
  112557. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  112558. if (animatable) {
  112559. this._animatables.push(animatable);
  112560. }
  112561. // sets the radius and lower radius bounds
  112562. // Small delta ensures camera is not always at lower zoom limit.
  112563. var radius = 0;
  112564. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  112565. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  112566. if (this.autoCorrectCameraLimitsAndSensibility) {
  112567. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  112568. }
  112569. radius = position;
  112570. }
  112571. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  112572. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  112573. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  112574. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  112575. }
  112576. }
  112577. // Set sensibilities
  112578. if (this.autoCorrectCameraLimitsAndSensibility) {
  112579. var extend = maximumWorld.subtract(minimumWorld).length();
  112580. this._attachedCamera.panningSensibility = 5000 / extend;
  112581. this._attachedCamera.wheelPrecision = 100 / radius;
  112582. }
  112583. // transition to new radius
  112584. if (!this._radiusTransition) {
  112585. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  112586. }
  112587. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  112588. _this.stopAllAnimations();
  112589. if (onAnimationEnd) {
  112590. onAnimationEnd();
  112591. }
  112592. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  112593. _this._attachedCamera.storeState();
  112594. }
  112595. });
  112596. if (animatable) {
  112597. this._animatables.push(animatable);
  112598. }
  112599. };
  112600. /**
  112601. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  112602. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  112603. * frustum width.
  112604. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  112605. * to fully enclose the mesh in the viewing frustum.
  112606. */
  112607. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  112608. var size = maximumWorld.subtract(minimumWorld);
  112609. var boxVectorGlobalDiagonal = size.length();
  112610. var frustumSlope = this._getFrustumSlope();
  112611. // Formula for setting distance
  112612. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  112613. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  112614. // Horizon distance
  112615. var radius = radiusWithoutFraming * this._radiusScale;
  112616. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  112617. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  112618. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  112619. var camera = this._attachedCamera;
  112620. if (!camera) {
  112621. return 0;
  112622. }
  112623. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  112624. // Don't exceed the requested limit
  112625. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  112626. }
  112627. // Don't exceed the upper radius limit
  112628. if (camera.upperRadiusLimit) {
  112629. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  112630. }
  112631. return distance;
  112632. };
  112633. /**
  112634. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  112635. * is automatically returned to its default position (expected to be above ground plane).
  112636. */
  112637. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  112638. var _this = this;
  112639. if (this._elevationReturnTime < 0) {
  112640. return;
  112641. }
  112642. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  112643. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  112644. var limitBeta = Math.PI * 0.5;
  112645. // Bring the camera back up if below the ground plane
  112646. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  112647. this._betaIsAnimating = true;
  112648. //Transition to new position
  112649. this.stopAllAnimations();
  112650. if (!this._betaTransition) {
  112651. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  112652. }
  112653. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  112654. _this._clearAnimationLocks();
  112655. _this.stopAllAnimations();
  112656. });
  112657. if (animatabe) {
  112658. this._animatables.push(animatabe);
  112659. }
  112660. }
  112661. };
  112662. /**
  112663. * Returns the frustum slope based on the canvas ratio and camera FOV
  112664. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  112665. */
  112666. FramingBehavior.prototype._getFrustumSlope = function () {
  112667. // Calculate the viewport ratio
  112668. // Aspect Ratio is Height/Width.
  112669. var camera = this._attachedCamera;
  112670. if (!camera) {
  112671. return BABYLON.Vector2.Zero();
  112672. }
  112673. var engine = camera.getScene().getEngine();
  112674. var aspectRatio = engine.getAspectRatio(camera);
  112675. // Camera FOV is the vertical field of view (top-bottom) in radians.
  112676. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  112677. var frustumSlopeY = Math.tan(camera.fov / 2);
  112678. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  112679. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  112680. // along the forward vector.
  112681. var frustumSlopeX = frustumSlopeY * aspectRatio;
  112682. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  112683. };
  112684. /**
  112685. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  112686. */
  112687. FramingBehavior.prototype._clearAnimationLocks = function () {
  112688. this._betaIsAnimating = false;
  112689. };
  112690. /**
  112691. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  112692. */
  112693. FramingBehavior.prototype._applyUserInteraction = function () {
  112694. if (this.isUserIsMoving) {
  112695. this._lastInteractionTime = BABYLON.Tools.Now;
  112696. this.stopAllAnimations();
  112697. this._clearAnimationLocks();
  112698. }
  112699. };
  112700. /**
  112701. * Stops and removes all animations that have been applied to the camera
  112702. */
  112703. FramingBehavior.prototype.stopAllAnimations = function () {
  112704. if (this._attachedCamera) {
  112705. this._attachedCamera.animations = [];
  112706. }
  112707. while (this._animatables.length) {
  112708. if (this._animatables[0]) {
  112709. this._animatables[0].onAnimationEnd = null;
  112710. this._animatables[0].stop();
  112711. }
  112712. this._animatables.shift();
  112713. }
  112714. };
  112715. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  112716. /**
  112717. * Gets a value indicating if the user is moving the camera
  112718. */
  112719. get: function () {
  112720. if (!this._attachedCamera) {
  112721. return false;
  112722. }
  112723. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  112724. this._attachedCamera.inertialBetaOffset !== 0 ||
  112725. this._attachedCamera.inertialRadiusOffset !== 0 ||
  112726. this._attachedCamera.inertialPanningX !== 0 ||
  112727. this._attachedCamera.inertialPanningY !== 0 ||
  112728. this._isPointerDown;
  112729. },
  112730. enumerable: true,
  112731. configurable: true
  112732. });
  112733. /**
  112734. * The easing function used by animations
  112735. */
  112736. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  112737. /**
  112738. * The easing mode used by animations
  112739. */
  112740. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  112741. // Statics
  112742. /**
  112743. * The camera can move all the way towards the mesh.
  112744. */
  112745. FramingBehavior.IgnoreBoundsSizeMode = 0;
  112746. /**
  112747. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  112748. */
  112749. FramingBehavior.FitFrustumSidesMode = 1;
  112750. return FramingBehavior;
  112751. }());
  112752. BABYLON.FramingBehavior = FramingBehavior;
  112753. })(BABYLON || (BABYLON = {}));
  112754. //# sourceMappingURL=babylon.framingBehavior.js.map
  112755. var BABYLON;
  112756. (function (BABYLON) {
  112757. /**
  112758. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  112759. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  112760. */
  112761. var BouncingBehavior = /** @class */ (function () {
  112762. function BouncingBehavior() {
  112763. /**
  112764. * The duration of the animation, in milliseconds
  112765. */
  112766. this.transitionDuration = 450;
  112767. /**
  112768. * Length of the distance animated by the transition when lower radius is reached
  112769. */
  112770. this.lowerRadiusTransitionRange = 2;
  112771. /**
  112772. * Length of the distance animated by the transition when upper radius is reached
  112773. */
  112774. this.upperRadiusTransitionRange = -2;
  112775. this._autoTransitionRange = false;
  112776. // Animations
  112777. this._radiusIsAnimating = false;
  112778. this._radiusBounceTransition = null;
  112779. this._animatables = new Array();
  112780. }
  112781. Object.defineProperty(BouncingBehavior.prototype, "name", {
  112782. /**
  112783. * Gets the name of the behavior.
  112784. */
  112785. get: function () {
  112786. return "Bouncing";
  112787. },
  112788. enumerable: true,
  112789. configurable: true
  112790. });
  112791. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  112792. /**
  112793. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  112794. */
  112795. get: function () {
  112796. return this._autoTransitionRange;
  112797. },
  112798. /**
  112799. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  112800. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  112801. */
  112802. set: function (value) {
  112803. var _this = this;
  112804. if (this._autoTransitionRange === value) {
  112805. return;
  112806. }
  112807. this._autoTransitionRange = value;
  112808. var camera = this._attachedCamera;
  112809. if (!camera) {
  112810. return;
  112811. }
  112812. if (value) {
  112813. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  112814. if (!mesh) {
  112815. return;
  112816. }
  112817. mesh.computeWorldMatrix(true);
  112818. var diagonal = mesh.getBoundingInfo().diagonalLength;
  112819. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  112820. _this.upperRadiusTransitionRange = diagonal * 0.05;
  112821. });
  112822. }
  112823. else if (this._onMeshTargetChangedObserver) {
  112824. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  112825. }
  112826. },
  112827. enumerable: true,
  112828. configurable: true
  112829. });
  112830. /**
  112831. * Initializes the behavior.
  112832. */
  112833. BouncingBehavior.prototype.init = function () {
  112834. // Do notihng
  112835. };
  112836. /**
  112837. * Attaches the behavior to its arc rotate camera.
  112838. * @param camera Defines the camera to attach the behavior to
  112839. */
  112840. BouncingBehavior.prototype.attach = function (camera) {
  112841. var _this = this;
  112842. this._attachedCamera = camera;
  112843. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  112844. if (!_this._attachedCamera) {
  112845. return;
  112846. }
  112847. // Add the bounce animation to the lower radius limit
  112848. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  112849. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  112850. }
  112851. // Add the bounce animation to the upper radius limit
  112852. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  112853. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  112854. }
  112855. });
  112856. };
  112857. /**
  112858. * Detaches the behavior from its current arc rotate camera.
  112859. */
  112860. BouncingBehavior.prototype.detach = function () {
  112861. if (!this._attachedCamera) {
  112862. return;
  112863. }
  112864. if (this._onAfterCheckInputsObserver) {
  112865. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  112866. }
  112867. if (this._onMeshTargetChangedObserver) {
  112868. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  112869. }
  112870. this._attachedCamera = null;
  112871. };
  112872. /**
  112873. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  112874. * @param radiusLimit The limit to check against.
  112875. * @return Bool to indicate if at limit.
  112876. */
  112877. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  112878. if (!this._attachedCamera) {
  112879. return false;
  112880. }
  112881. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  112882. return true;
  112883. }
  112884. return false;
  112885. };
  112886. /**
  112887. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  112888. * @param radiusDelta The delta by which to animate to. Can be negative.
  112889. */
  112890. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  112891. var _this = this;
  112892. if (!this._attachedCamera) {
  112893. return;
  112894. }
  112895. if (!this._radiusBounceTransition) {
  112896. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  112897. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  112898. }
  112899. // Prevent zoom until bounce has completed
  112900. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  112901. this._attachedCamera.wheelPrecision = Infinity;
  112902. this._attachedCamera.inertialRadiusOffset = 0;
  112903. // Animate to the radius limit
  112904. this.stopAllAnimations();
  112905. this._radiusIsAnimating = true;
  112906. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  112907. if (animatable) {
  112908. this._animatables.push(animatable);
  112909. }
  112910. };
  112911. /**
  112912. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  112913. */
  112914. BouncingBehavior.prototype._clearAnimationLocks = function () {
  112915. this._radiusIsAnimating = false;
  112916. if (this._attachedCamera) {
  112917. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  112918. }
  112919. };
  112920. /**
  112921. * Stops and removes all animations that have been applied to the camera
  112922. */
  112923. BouncingBehavior.prototype.stopAllAnimations = function () {
  112924. if (this._attachedCamera) {
  112925. this._attachedCamera.animations = [];
  112926. }
  112927. while (this._animatables.length) {
  112928. this._animatables[0].onAnimationEnd = null;
  112929. this._animatables[0].stop();
  112930. this._animatables.shift();
  112931. }
  112932. };
  112933. /**
  112934. * The easing function used by animations
  112935. */
  112936. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  112937. /**
  112938. * The easing mode used by animations
  112939. */
  112940. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  112941. return BouncingBehavior;
  112942. }());
  112943. BABYLON.BouncingBehavior = BouncingBehavior;
  112944. })(BABYLON || (BABYLON = {}));
  112945. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  112946. var BABYLON;
  112947. (function (BABYLON) {
  112948. /**
  112949. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  112950. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  112951. */
  112952. var AutoRotationBehavior = /** @class */ (function () {
  112953. function AutoRotationBehavior() {
  112954. this._zoomStopsAnimation = false;
  112955. this._idleRotationSpeed = 0.05;
  112956. this._idleRotationWaitTime = 2000;
  112957. this._idleRotationSpinupTime = 2000;
  112958. this._isPointerDown = false;
  112959. this._lastFrameTime = null;
  112960. this._lastInteractionTime = -Infinity;
  112961. this._cameraRotationSpeed = 0;
  112962. this._lastFrameRadius = 0;
  112963. }
  112964. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  112965. /**
  112966. * Gets the name of the behavior.
  112967. */
  112968. get: function () {
  112969. return "AutoRotation";
  112970. },
  112971. enumerable: true,
  112972. configurable: true
  112973. });
  112974. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  112975. /**
  112976. * Gets the flag that indicates if user zooming should stop animation.
  112977. */
  112978. get: function () {
  112979. return this._zoomStopsAnimation;
  112980. },
  112981. /**
  112982. * Sets the flag that indicates if user zooming should stop animation.
  112983. */
  112984. set: function (flag) {
  112985. this._zoomStopsAnimation = flag;
  112986. },
  112987. enumerable: true,
  112988. configurable: true
  112989. });
  112990. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  112991. /**
  112992. * Gets the default speed at which the camera rotates around the model.
  112993. */
  112994. get: function () {
  112995. return this._idleRotationSpeed;
  112996. },
  112997. /**
  112998. * Sets the default speed at which the camera rotates around the model.
  112999. */
  113000. set: function (speed) {
  113001. this._idleRotationSpeed = speed;
  113002. },
  113003. enumerable: true,
  113004. configurable: true
  113005. });
  113006. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  113007. /**
  113008. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  113009. */
  113010. get: function () {
  113011. return this._idleRotationWaitTime;
  113012. },
  113013. /**
  113014. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  113015. */
  113016. set: function (time) {
  113017. this._idleRotationWaitTime = time;
  113018. },
  113019. enumerable: true,
  113020. configurable: true
  113021. });
  113022. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  113023. /**
  113024. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  113025. */
  113026. get: function () {
  113027. return this._idleRotationSpinupTime;
  113028. },
  113029. /**
  113030. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  113031. */
  113032. set: function (time) {
  113033. this._idleRotationSpinupTime = time;
  113034. },
  113035. enumerable: true,
  113036. configurable: true
  113037. });
  113038. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  113039. /**
  113040. * Gets a value indicating if the camera is currently rotating because of this behavior
  113041. */
  113042. get: function () {
  113043. return Math.abs(this._cameraRotationSpeed) > 0;
  113044. },
  113045. enumerable: true,
  113046. configurable: true
  113047. });
  113048. /**
  113049. * Initializes the behavior.
  113050. */
  113051. AutoRotationBehavior.prototype.init = function () {
  113052. // Do notihng
  113053. };
  113054. /**
  113055. * Attaches the behavior to its arc rotate camera.
  113056. * @param camera Defines the camera to attach the behavior to
  113057. */
  113058. AutoRotationBehavior.prototype.attach = function (camera) {
  113059. var _this = this;
  113060. this._attachedCamera = camera;
  113061. var scene = this._attachedCamera.getScene();
  113062. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  113063. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  113064. _this._isPointerDown = true;
  113065. return;
  113066. }
  113067. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  113068. _this._isPointerDown = false;
  113069. }
  113070. });
  113071. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  113072. var now = BABYLON.Tools.Now;
  113073. var dt = 0;
  113074. if (_this._lastFrameTime != null) {
  113075. dt = now - _this._lastFrameTime;
  113076. }
  113077. _this._lastFrameTime = now;
  113078. // Stop the animation if there is user interaction and the animation should stop for this interaction
  113079. _this._applyUserInteraction();
  113080. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  113081. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  113082. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  113083. // Step camera rotation by rotation speed
  113084. if (_this._attachedCamera) {
  113085. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  113086. }
  113087. });
  113088. };
  113089. /**
  113090. * Detaches the behavior from its current arc rotate camera.
  113091. */
  113092. AutoRotationBehavior.prototype.detach = function () {
  113093. if (!this._attachedCamera) {
  113094. return;
  113095. }
  113096. var scene = this._attachedCamera.getScene();
  113097. if (this._onPrePointerObservableObserver) {
  113098. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  113099. }
  113100. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  113101. this._attachedCamera = null;
  113102. };
  113103. /**
  113104. * Returns true if user is scrolling.
  113105. * @return true if user is scrolling.
  113106. */
  113107. AutoRotationBehavior.prototype._userIsZooming = function () {
  113108. if (!this._attachedCamera) {
  113109. return false;
  113110. }
  113111. return this._attachedCamera.inertialRadiusOffset !== 0;
  113112. };
  113113. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  113114. if (!this._attachedCamera) {
  113115. return false;
  113116. }
  113117. var zoomHasHitLimit = false;
  113118. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  113119. zoomHasHitLimit = true;
  113120. }
  113121. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  113122. this._lastFrameRadius = this._attachedCamera.radius;
  113123. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  113124. };
  113125. /**
  113126. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  113127. */
  113128. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  113129. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  113130. this._lastInteractionTime = BABYLON.Tools.Now;
  113131. }
  113132. };
  113133. // Tools
  113134. AutoRotationBehavior.prototype._userIsMoving = function () {
  113135. if (!this._attachedCamera) {
  113136. return false;
  113137. }
  113138. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  113139. this._attachedCamera.inertialBetaOffset !== 0 ||
  113140. this._attachedCamera.inertialRadiusOffset !== 0 ||
  113141. this._attachedCamera.inertialPanningX !== 0 ||
  113142. this._attachedCamera.inertialPanningY !== 0 ||
  113143. this._isPointerDown;
  113144. };
  113145. return AutoRotationBehavior;
  113146. }());
  113147. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  113148. })(BABYLON || (BABYLON = {}));
  113149. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  113150. var BABYLON;
  113151. (function (BABYLON) {
  113152. /**
  113153. * Options to create the null engine
  113154. */
  113155. var NullEngineOptions = /** @class */ (function () {
  113156. function NullEngineOptions() {
  113157. /**
  113158. * Render width (Default: 512)
  113159. */
  113160. this.renderWidth = 512;
  113161. /**
  113162. * Render height (Default: 256)
  113163. */
  113164. this.renderHeight = 256;
  113165. /**
  113166. * Texture size (Default: 512)
  113167. */
  113168. this.textureSize = 512;
  113169. /**
  113170. * If delta time between frames should be constant
  113171. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  113172. */
  113173. this.deterministicLockstep = false;
  113174. /**
  113175. * Maximum about of steps between frames (Default: 4)
  113176. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  113177. */
  113178. this.lockstepMaxSteps = 4;
  113179. }
  113180. return NullEngineOptions;
  113181. }());
  113182. BABYLON.NullEngineOptions = NullEngineOptions;
  113183. /**
  113184. * The null engine class provides support for headless version of babylon.js.
  113185. * This can be used in server side scenario or for testing purposes
  113186. */
  113187. var NullEngine = /** @class */ (function (_super) {
  113188. __extends(NullEngine, _super);
  113189. function NullEngine(options) {
  113190. if (options === void 0) { options = new NullEngineOptions(); }
  113191. var _this = _super.call(this, null) || this;
  113192. if (options.deterministicLockstep === undefined) {
  113193. options.deterministicLockstep = false;
  113194. }
  113195. if (options.lockstepMaxSteps === undefined) {
  113196. options.lockstepMaxSteps = 4;
  113197. }
  113198. _this._options = options;
  113199. // Init caps
  113200. // We consider we are on a webgl1 capable device
  113201. _this._caps = new BABYLON.EngineCapabilities();
  113202. _this._caps.maxTexturesImageUnits = 16;
  113203. _this._caps.maxVertexTextureImageUnits = 16;
  113204. _this._caps.maxTextureSize = 512;
  113205. _this._caps.maxCubemapTextureSize = 512;
  113206. _this._caps.maxRenderTextureSize = 512;
  113207. _this._caps.maxVertexAttribs = 16;
  113208. _this._caps.maxVaryingVectors = 16;
  113209. _this._caps.maxFragmentUniformVectors = 16;
  113210. _this._caps.maxVertexUniformVectors = 16;
  113211. // Extensions
  113212. _this._caps.standardDerivatives = false;
  113213. _this._caps.astc = null;
  113214. _this._caps.s3tc = null;
  113215. _this._caps.pvrtc = null;
  113216. _this._caps.etc1 = null;
  113217. _this._caps.etc2 = null;
  113218. _this._caps.textureAnisotropicFilterExtension = null;
  113219. _this._caps.maxAnisotropy = 0;
  113220. _this._caps.uintIndices = false;
  113221. _this._caps.fragmentDepthSupported = false;
  113222. _this._caps.highPrecisionShaderSupported = true;
  113223. _this._caps.colorBufferFloat = false;
  113224. _this._caps.textureFloat = false;
  113225. _this._caps.textureFloatLinearFiltering = false;
  113226. _this._caps.textureFloatRender = false;
  113227. _this._caps.textureHalfFloat = false;
  113228. _this._caps.textureHalfFloatLinearFiltering = false;
  113229. _this._caps.textureHalfFloatRender = false;
  113230. _this._caps.textureLOD = false;
  113231. _this._caps.drawBuffersExtension = false;
  113232. _this._caps.depthTextureExtension = false;
  113233. _this._caps.vertexArrayObject = false;
  113234. _this._caps.instancedArrays = false;
  113235. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  113236. // Wrappers
  113237. if (typeof URL === "undefined") {
  113238. URL = {
  113239. createObjectURL: function () { },
  113240. revokeObjectURL: function () { }
  113241. };
  113242. }
  113243. if (typeof Blob === "undefined") {
  113244. Blob = function () { };
  113245. }
  113246. return _this;
  113247. }
  113248. /**
  113249. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  113250. */
  113251. NullEngine.prototype.isDeterministicLockStep = function () {
  113252. return this._options.deterministicLockstep;
  113253. };
  113254. /** @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep */
  113255. NullEngine.prototype.getLockstepMaxSteps = function () {
  113256. return this._options.lockstepMaxSteps;
  113257. };
  113258. /**
  113259. * Sets hardware scaling, used to save performance if needed
  113260. * @see https://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  113261. */
  113262. NullEngine.prototype.getHardwareScalingLevel = function () {
  113263. return 1.0;
  113264. };
  113265. NullEngine.prototype.createVertexBuffer = function (vertices) {
  113266. return {
  113267. capacity: 0,
  113268. references: 1,
  113269. is32Bits: false
  113270. };
  113271. };
  113272. NullEngine.prototype.createIndexBuffer = function (indices) {
  113273. return {
  113274. capacity: 0,
  113275. references: 1,
  113276. is32Bits: false
  113277. };
  113278. };
  113279. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  113280. if (stencil === void 0) { stencil = false; }
  113281. };
  113282. NullEngine.prototype.getRenderWidth = function (useScreen) {
  113283. if (useScreen === void 0) { useScreen = false; }
  113284. if (!useScreen && this._currentRenderTarget) {
  113285. return this._currentRenderTarget.width;
  113286. }
  113287. return this._options.renderWidth;
  113288. };
  113289. NullEngine.prototype.getRenderHeight = function (useScreen) {
  113290. if (useScreen === void 0) { useScreen = false; }
  113291. if (!useScreen && this._currentRenderTarget) {
  113292. return this._currentRenderTarget.height;
  113293. }
  113294. return this._options.renderHeight;
  113295. };
  113296. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  113297. this._cachedViewport = viewport;
  113298. };
  113299. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  113300. return {
  113301. transformFeedback: null,
  113302. __SPECTOR_rebuildProgram: null
  113303. };
  113304. };
  113305. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  113306. return [];
  113307. };
  113308. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  113309. return [];
  113310. };
  113311. NullEngine.prototype.bindSamplers = function (effect) {
  113312. this._currentEffect = null;
  113313. };
  113314. NullEngine.prototype.enableEffect = function (effect) {
  113315. this._currentEffect = effect;
  113316. if (effect.onBind) {
  113317. effect.onBind(effect);
  113318. }
  113319. if (effect._onBindObservable) {
  113320. effect._onBindObservable.notifyObservers(effect);
  113321. }
  113322. };
  113323. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  113324. if (zOffset === void 0) { zOffset = 0; }
  113325. if (reverseSide === void 0) { reverseSide = false; }
  113326. };
  113327. NullEngine.prototype.setIntArray = function (uniform, array) {
  113328. };
  113329. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  113330. };
  113331. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  113332. };
  113333. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  113334. };
  113335. NullEngine.prototype.setFloatArray = function (uniform, array) {
  113336. };
  113337. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  113338. };
  113339. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  113340. };
  113341. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  113342. };
  113343. NullEngine.prototype.setArray = function (uniform, array) {
  113344. };
  113345. NullEngine.prototype.setArray2 = function (uniform, array) {
  113346. };
  113347. NullEngine.prototype.setArray3 = function (uniform, array) {
  113348. };
  113349. NullEngine.prototype.setArray4 = function (uniform, array) {
  113350. };
  113351. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  113352. };
  113353. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  113354. };
  113355. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  113356. };
  113357. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  113358. };
  113359. NullEngine.prototype.setFloat = function (uniform, value) {
  113360. };
  113361. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  113362. };
  113363. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  113364. };
  113365. NullEngine.prototype.setBool = function (uniform, bool) {
  113366. };
  113367. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  113368. };
  113369. NullEngine.prototype.setColor3 = function (uniform, color3) {
  113370. };
  113371. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  113372. };
  113373. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  113374. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  113375. if (this._alphaMode === mode) {
  113376. return;
  113377. }
  113378. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  113379. if (!noDepthWriteChange) {
  113380. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  113381. }
  113382. this._alphaMode = mode;
  113383. };
  113384. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  113385. };
  113386. NullEngine.prototype.wipeCaches = function (bruteForce) {
  113387. if (this.preventCacheWipeBetweenFrames) {
  113388. return;
  113389. }
  113390. this.resetTextureCache();
  113391. this._currentEffect = null;
  113392. if (bruteForce) {
  113393. this._currentProgram = null;
  113394. this._stencilState.reset();
  113395. this._depthCullingState.reset();
  113396. this._alphaState.reset();
  113397. }
  113398. this._cachedVertexBuffers = null;
  113399. this._cachedIndexBuffer = null;
  113400. this._cachedEffectForVertexBuffers = null;
  113401. };
  113402. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  113403. };
  113404. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  113405. };
  113406. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  113407. };
  113408. /** @hidden */
  113409. NullEngine.prototype._createTexture = function () {
  113410. return {};
  113411. };
  113412. /** @hidden */
  113413. NullEngine.prototype._releaseTexture = function (texture) {
  113414. };
  113415. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  113416. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  113417. if (onLoad === void 0) { onLoad = null; }
  113418. if (onError === void 0) { onError = null; }
  113419. if (buffer === void 0) { buffer = null; }
  113420. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  113421. var url = String(urlArg);
  113422. texture.url = url;
  113423. texture.generateMipMaps = !noMipmap;
  113424. texture.samplingMode = samplingMode;
  113425. texture.invertY = invertY;
  113426. texture.baseWidth = this._options.textureSize;
  113427. texture.baseHeight = this._options.textureSize;
  113428. texture.width = this._options.textureSize;
  113429. texture.height = this._options.textureSize;
  113430. if (format) {
  113431. texture.format = format;
  113432. }
  113433. texture.isReady = true;
  113434. if (onLoad) {
  113435. onLoad();
  113436. }
  113437. this._internalTexturesCache.push(texture);
  113438. return texture;
  113439. };
  113440. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  113441. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  113442. if (options !== undefined && typeof options === "object") {
  113443. fullOptions.generateMipMaps = options.generateMipMaps;
  113444. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  113445. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  113446. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  113447. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  113448. }
  113449. else {
  113450. fullOptions.generateMipMaps = options;
  113451. fullOptions.generateDepthBuffer = true;
  113452. fullOptions.generateStencilBuffer = false;
  113453. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  113454. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  113455. }
  113456. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  113457. var width = size.width || size;
  113458. var height = size.height || size;
  113459. texture._depthStencilBuffer = {};
  113460. texture._framebuffer = {};
  113461. texture.baseWidth = width;
  113462. texture.baseHeight = height;
  113463. texture.width = width;
  113464. texture.height = height;
  113465. texture.isReady = true;
  113466. texture.samples = 1;
  113467. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  113468. texture.samplingMode = fullOptions.samplingMode;
  113469. texture.type = fullOptions.type;
  113470. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  113471. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  113472. this._internalTexturesCache.push(texture);
  113473. return texture;
  113474. };
  113475. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  113476. texture.samplingMode = samplingMode;
  113477. };
  113478. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  113479. if (this._currentRenderTarget) {
  113480. this.unBindFramebuffer(this._currentRenderTarget);
  113481. }
  113482. this._currentRenderTarget = texture;
  113483. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  113484. if (this._cachedViewport && !forceFullscreenViewport) {
  113485. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  113486. }
  113487. };
  113488. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  113489. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  113490. this._currentRenderTarget = null;
  113491. if (onBeforeUnbind) {
  113492. if (texture._MSAAFramebuffer) {
  113493. this._currentFramebuffer = texture._framebuffer;
  113494. }
  113495. onBeforeUnbind();
  113496. }
  113497. this._currentFramebuffer = null;
  113498. };
  113499. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  113500. var vbo = {
  113501. capacity: 1,
  113502. references: 1,
  113503. is32Bits: false
  113504. };
  113505. return vbo;
  113506. };
  113507. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  113508. if (premulAlpha === void 0) { premulAlpha = false; }
  113509. };
  113510. /**
  113511. * @hidden
  113512. * Get the current error code of the webGL context
  113513. * @returns the error code
  113514. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  113515. */
  113516. NullEngine.prototype.getError = function () {
  113517. return 0;
  113518. };
  113519. /** @hidden */
  113520. NullEngine.prototype._getUnpackAlignement = function () {
  113521. return 1;
  113522. };
  113523. /** @hidden */
  113524. NullEngine.prototype._unpackFlipY = function (value) {
  113525. };
  113526. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  113527. if (offset === void 0) { offset = 0; }
  113528. };
  113529. /**
  113530. * Updates a dynamic vertex buffer.
  113531. * @param vertexBuffer the vertex buffer to update
  113532. * @param data the data used to update the vertex buffer
  113533. * @param byteOffset the byte offset of the data (optional)
  113534. * @param byteLength the byte length of the data (optional)
  113535. */
  113536. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  113537. };
  113538. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  113539. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  113540. this._boundTexturesCache[this._activeChannel] = texture;
  113541. return true;
  113542. }
  113543. return false;
  113544. };
  113545. /** @hidden */
  113546. NullEngine.prototype._bindTexture = function (channel, texture) {
  113547. if (channel < 0) {
  113548. return;
  113549. }
  113550. this._bindTextureDirectly(0, texture);
  113551. };
  113552. /** @hidden */
  113553. NullEngine.prototype._releaseBuffer = function (buffer) {
  113554. buffer.references--;
  113555. if (buffer.references === 0) {
  113556. return true;
  113557. }
  113558. return false;
  113559. };
  113560. NullEngine.prototype.releaseEffects = function () {
  113561. };
  113562. NullEngine.prototype.displayLoadingUI = function () {
  113563. };
  113564. NullEngine.prototype.hideLoadingUI = function () {
  113565. };
  113566. /** @hidden */
  113567. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  113568. if (faceIndex === void 0) { faceIndex = 0; }
  113569. if (lod === void 0) { lod = 0; }
  113570. };
  113571. /** @hidden */
  113572. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  113573. if (faceIndex === void 0) { faceIndex = 0; }
  113574. if (lod === void 0) { lod = 0; }
  113575. };
  113576. /** @hidden */
  113577. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  113578. if (faceIndex === void 0) { faceIndex = 0; }
  113579. if (lod === void 0) { lod = 0; }
  113580. };
  113581. /** @hidden */
  113582. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  113583. if (faceIndex === void 0) { faceIndex = 0; }
  113584. if (lod === void 0) { lod = 0; }
  113585. };
  113586. return NullEngine;
  113587. }(BABYLON.Engine));
  113588. BABYLON.NullEngine = NullEngine;
  113589. })(BABYLON || (BABYLON = {}));
  113590. //# sourceMappingURL=babylon.nullEngine.js.map
  113591. var BABYLON;
  113592. (function (BABYLON) {
  113593. /**
  113594. * This class can be used to get instrumentation data from a Babylon engine
  113595. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  113596. */
  113597. var EngineInstrumentation = /** @class */ (function () {
  113598. /**
  113599. * Instantiates a new engine instrumentation.
  113600. * This class can be used to get instrumentation data from a Babylon engine
  113601. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  113602. * @param engine Defines the engine to instrument
  113603. */
  113604. function EngineInstrumentation(
  113605. /**
  113606. * Define the instrumented engine.
  113607. */
  113608. engine) {
  113609. this.engine = engine;
  113610. this._captureGPUFrameTime = false;
  113611. this._gpuFrameTime = new BABYLON.PerfCounter();
  113612. this._captureShaderCompilationTime = false;
  113613. this._shaderCompilationTime = new BABYLON.PerfCounter();
  113614. // Observers
  113615. this._onBeginFrameObserver = null;
  113616. this._onEndFrameObserver = null;
  113617. this._onBeforeShaderCompilationObserver = null;
  113618. this._onAfterShaderCompilationObserver = null;
  113619. }
  113620. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  113621. // Properties
  113622. /**
  113623. * Gets the perf counter used for GPU frame time
  113624. */
  113625. get: function () {
  113626. return this._gpuFrameTime;
  113627. },
  113628. enumerable: true,
  113629. configurable: true
  113630. });
  113631. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  113632. /**
  113633. * Gets the GPU frame time capture status
  113634. */
  113635. get: function () {
  113636. return this._captureGPUFrameTime;
  113637. },
  113638. /**
  113639. * Enable or disable the GPU frame time capture
  113640. */
  113641. set: function (value) {
  113642. var _this = this;
  113643. if (value === this._captureGPUFrameTime) {
  113644. return;
  113645. }
  113646. this._captureGPUFrameTime = value;
  113647. if (value) {
  113648. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  113649. if (!_this._gpuFrameTimeToken) {
  113650. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  113651. }
  113652. });
  113653. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  113654. if (!_this._gpuFrameTimeToken) {
  113655. return;
  113656. }
  113657. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  113658. if (time > -1) {
  113659. _this._gpuFrameTimeToken = null;
  113660. _this._gpuFrameTime.fetchNewFrame();
  113661. _this._gpuFrameTime.addCount(time, true);
  113662. }
  113663. });
  113664. }
  113665. else {
  113666. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  113667. this._onBeginFrameObserver = null;
  113668. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  113669. this._onEndFrameObserver = null;
  113670. }
  113671. },
  113672. enumerable: true,
  113673. configurable: true
  113674. });
  113675. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  113676. /**
  113677. * Gets the perf counter used for shader compilation time
  113678. */
  113679. get: function () {
  113680. return this._shaderCompilationTime;
  113681. },
  113682. enumerable: true,
  113683. configurable: true
  113684. });
  113685. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  113686. /**
  113687. * Gets the shader compilation time capture status
  113688. */
  113689. get: function () {
  113690. return this._captureShaderCompilationTime;
  113691. },
  113692. /**
  113693. * Enable or disable the shader compilation time capture
  113694. */
  113695. set: function (value) {
  113696. var _this = this;
  113697. if (value === this._captureShaderCompilationTime) {
  113698. return;
  113699. }
  113700. this._captureShaderCompilationTime = value;
  113701. if (value) {
  113702. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  113703. _this._shaderCompilationTime.fetchNewFrame();
  113704. _this._shaderCompilationTime.beginMonitoring();
  113705. });
  113706. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  113707. _this._shaderCompilationTime.endMonitoring();
  113708. });
  113709. }
  113710. else {
  113711. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  113712. this._onBeforeShaderCompilationObserver = null;
  113713. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  113714. this._onAfterShaderCompilationObserver = null;
  113715. }
  113716. },
  113717. enumerable: true,
  113718. configurable: true
  113719. });
  113720. /**
  113721. * Dispose and release associated resources.
  113722. */
  113723. EngineInstrumentation.prototype.dispose = function () {
  113724. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  113725. this._onBeginFrameObserver = null;
  113726. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  113727. this._onEndFrameObserver = null;
  113728. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  113729. this._onBeforeShaderCompilationObserver = null;
  113730. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  113731. this._onAfterShaderCompilationObserver = null;
  113732. this.engine = null;
  113733. };
  113734. return EngineInstrumentation;
  113735. }());
  113736. BABYLON.EngineInstrumentation = EngineInstrumentation;
  113737. })(BABYLON || (BABYLON = {}));
  113738. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  113739. var BABYLON;
  113740. (function (BABYLON) {
  113741. /**
  113742. * This class can be used to get instrumentation data from a Babylon engine
  113743. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  113744. */
  113745. var SceneInstrumentation = /** @class */ (function () {
  113746. /**
  113747. * Instantiates a new scene instrumentation.
  113748. * This class can be used to get instrumentation data from a Babylon engine
  113749. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  113750. * @param scene Defines the scene to instrument
  113751. */
  113752. function SceneInstrumentation(
  113753. /**
  113754. * Defines the scene to instrument
  113755. */
  113756. scene) {
  113757. var _this = this;
  113758. this.scene = scene;
  113759. this._captureActiveMeshesEvaluationTime = false;
  113760. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  113761. this._captureRenderTargetsRenderTime = false;
  113762. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  113763. this._captureFrameTime = false;
  113764. this._frameTime = new BABYLON.PerfCounter();
  113765. this._captureRenderTime = false;
  113766. this._renderTime = new BABYLON.PerfCounter();
  113767. this._captureInterFrameTime = false;
  113768. this._interFrameTime = new BABYLON.PerfCounter();
  113769. this._captureParticlesRenderTime = false;
  113770. this._particlesRenderTime = new BABYLON.PerfCounter();
  113771. this._captureSpritesRenderTime = false;
  113772. this._spritesRenderTime = new BABYLON.PerfCounter();
  113773. this._capturePhysicsTime = false;
  113774. this._physicsTime = new BABYLON.PerfCounter();
  113775. this._captureAnimationsTime = false;
  113776. this._animationsTime = new BABYLON.PerfCounter();
  113777. this._captureCameraRenderTime = false;
  113778. this._cameraRenderTime = new BABYLON.PerfCounter();
  113779. // Observers
  113780. this._onBeforeActiveMeshesEvaluationObserver = null;
  113781. this._onAfterActiveMeshesEvaluationObserver = null;
  113782. this._onBeforeRenderTargetsRenderObserver = null;
  113783. this._onAfterRenderTargetsRenderObserver = null;
  113784. this._onAfterRenderObserver = null;
  113785. this._onBeforeDrawPhaseObserver = null;
  113786. this._onAfterDrawPhaseObserver = null;
  113787. this._onBeforeAnimationsObserver = null;
  113788. this._onBeforeParticlesRenderingObserver = null;
  113789. this._onAfterParticlesRenderingObserver = null;
  113790. this._onBeforeSpritesRenderingObserver = null;
  113791. this._onAfterSpritesRenderingObserver = null;
  113792. this._onBeforePhysicsObserver = null;
  113793. this._onAfterPhysicsObserver = null;
  113794. this._onAfterAnimationsObserver = null;
  113795. this._onBeforeCameraRenderObserver = null;
  113796. this._onAfterCameraRenderObserver = null;
  113797. // Before render
  113798. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  113799. if (_this._captureActiveMeshesEvaluationTime) {
  113800. _this._activeMeshesEvaluationTime.fetchNewFrame();
  113801. }
  113802. if (_this._captureRenderTargetsRenderTime) {
  113803. _this._renderTargetsRenderTime.fetchNewFrame();
  113804. }
  113805. if (_this._captureFrameTime) {
  113806. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  113807. _this._frameTime.beginMonitoring();
  113808. }
  113809. if (_this._captureInterFrameTime) {
  113810. _this._interFrameTime.endMonitoring();
  113811. }
  113812. if (_this._captureParticlesRenderTime) {
  113813. _this._particlesRenderTime.fetchNewFrame();
  113814. }
  113815. if (_this._captureSpritesRenderTime) {
  113816. _this._spritesRenderTime.fetchNewFrame();
  113817. }
  113818. if (_this._captureAnimationsTime) {
  113819. _this._animationsTime.beginMonitoring();
  113820. }
  113821. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  113822. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  113823. });
  113824. // After render
  113825. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  113826. if (_this._captureFrameTime) {
  113827. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  113828. _this._frameTime.endMonitoring();
  113829. }
  113830. if (_this._captureRenderTime) {
  113831. _this._renderTime.endMonitoring(false);
  113832. }
  113833. if (_this._captureInterFrameTime) {
  113834. _this._interFrameTime.beginMonitoring();
  113835. }
  113836. });
  113837. }
  113838. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  113839. // Properties
  113840. /**
  113841. * Gets the perf counter used for active meshes evaluation time
  113842. */
  113843. get: function () {
  113844. return this._activeMeshesEvaluationTime;
  113845. },
  113846. enumerable: true,
  113847. configurable: true
  113848. });
  113849. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  113850. /**
  113851. * Gets the active meshes evaluation time capture status
  113852. */
  113853. get: function () {
  113854. return this._captureActiveMeshesEvaluationTime;
  113855. },
  113856. /**
  113857. * Enable or disable the active meshes evaluation time capture
  113858. */
  113859. set: function (value) {
  113860. var _this = this;
  113861. if (value === this._captureActiveMeshesEvaluationTime) {
  113862. return;
  113863. }
  113864. this._captureActiveMeshesEvaluationTime = value;
  113865. if (value) {
  113866. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  113867. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  113868. _this._activeMeshesEvaluationTime.beginMonitoring();
  113869. });
  113870. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  113871. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  113872. _this._activeMeshesEvaluationTime.endMonitoring();
  113873. });
  113874. }
  113875. else {
  113876. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  113877. this._onBeforeActiveMeshesEvaluationObserver = null;
  113878. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  113879. this._onAfterActiveMeshesEvaluationObserver = null;
  113880. }
  113881. },
  113882. enumerable: true,
  113883. configurable: true
  113884. });
  113885. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  113886. /**
  113887. * Gets the perf counter used for render targets render time
  113888. */
  113889. get: function () {
  113890. return this._renderTargetsRenderTime;
  113891. },
  113892. enumerable: true,
  113893. configurable: true
  113894. });
  113895. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  113896. /**
  113897. * Gets the render targets render time capture status
  113898. */
  113899. get: function () {
  113900. return this._captureRenderTargetsRenderTime;
  113901. },
  113902. /**
  113903. * Enable or disable the render targets render time capture
  113904. */
  113905. set: function (value) {
  113906. var _this = this;
  113907. if (value === this._captureRenderTargetsRenderTime) {
  113908. return;
  113909. }
  113910. this._captureRenderTargetsRenderTime = value;
  113911. if (value) {
  113912. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  113913. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  113914. _this._renderTargetsRenderTime.beginMonitoring();
  113915. });
  113916. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  113917. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  113918. _this._renderTargetsRenderTime.endMonitoring(false);
  113919. });
  113920. }
  113921. else {
  113922. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  113923. this._onBeforeRenderTargetsRenderObserver = null;
  113924. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  113925. this._onAfterRenderTargetsRenderObserver = null;
  113926. }
  113927. },
  113928. enumerable: true,
  113929. configurable: true
  113930. });
  113931. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  113932. /**
  113933. * Gets the perf counter used for particles render time
  113934. */
  113935. get: function () {
  113936. return this._particlesRenderTime;
  113937. },
  113938. enumerable: true,
  113939. configurable: true
  113940. });
  113941. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  113942. /**
  113943. * Gets the particles render time capture status
  113944. */
  113945. get: function () {
  113946. return this._captureParticlesRenderTime;
  113947. },
  113948. /**
  113949. * Enable or disable the particles render time capture
  113950. */
  113951. set: function (value) {
  113952. var _this = this;
  113953. if (value === this._captureParticlesRenderTime) {
  113954. return;
  113955. }
  113956. this._captureParticlesRenderTime = value;
  113957. if (value) {
  113958. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  113959. BABYLON.Tools.StartPerformanceCounter("Particles");
  113960. _this._particlesRenderTime.beginMonitoring();
  113961. });
  113962. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  113963. BABYLON.Tools.EndPerformanceCounter("Particles");
  113964. _this._particlesRenderTime.endMonitoring(false);
  113965. });
  113966. }
  113967. else {
  113968. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  113969. this._onBeforeParticlesRenderingObserver = null;
  113970. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  113971. this._onAfterParticlesRenderingObserver = null;
  113972. }
  113973. },
  113974. enumerable: true,
  113975. configurable: true
  113976. });
  113977. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  113978. /**
  113979. * Gets the perf counter used for sprites render time
  113980. */
  113981. get: function () {
  113982. return this._spritesRenderTime;
  113983. },
  113984. enumerable: true,
  113985. configurable: true
  113986. });
  113987. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  113988. /**
  113989. * Gets the sprites render time capture status
  113990. */
  113991. get: function () {
  113992. return this._captureSpritesRenderTime;
  113993. },
  113994. /**
  113995. * Enable or disable the sprites render time capture
  113996. */
  113997. set: function (value) {
  113998. var _this = this;
  113999. if (value === this._captureSpritesRenderTime) {
  114000. return;
  114001. }
  114002. this._captureSpritesRenderTime = value;
  114003. if (!this.scene.spriteManagers) {
  114004. return;
  114005. }
  114006. if (value) {
  114007. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  114008. BABYLON.Tools.StartPerformanceCounter("Sprites");
  114009. _this._spritesRenderTime.beginMonitoring();
  114010. });
  114011. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  114012. BABYLON.Tools.EndPerformanceCounter("Sprites");
  114013. _this._spritesRenderTime.endMonitoring(false);
  114014. });
  114015. }
  114016. else {
  114017. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  114018. this._onBeforeSpritesRenderingObserver = null;
  114019. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  114020. this._onAfterSpritesRenderingObserver = null;
  114021. }
  114022. },
  114023. enumerable: true,
  114024. configurable: true
  114025. });
  114026. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  114027. /**
  114028. * Gets the perf counter used for physics time
  114029. */
  114030. get: function () {
  114031. return this._physicsTime;
  114032. },
  114033. enumerable: true,
  114034. configurable: true
  114035. });
  114036. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  114037. /**
  114038. * Gets the physics time capture status
  114039. */
  114040. get: function () {
  114041. return this._capturePhysicsTime;
  114042. },
  114043. /**
  114044. * Enable or disable the physics time capture
  114045. */
  114046. set: function (value) {
  114047. var _this = this;
  114048. if (value === this._capturePhysicsTime) {
  114049. return;
  114050. }
  114051. if (!this.scene.onBeforePhysicsObservable) {
  114052. return;
  114053. }
  114054. this._capturePhysicsTime = value;
  114055. if (value) {
  114056. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  114057. BABYLON.Tools.StartPerformanceCounter("Physics");
  114058. _this._physicsTime.beginMonitoring();
  114059. });
  114060. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  114061. BABYLON.Tools.EndPerformanceCounter("Physics");
  114062. _this._physicsTime.endMonitoring();
  114063. });
  114064. }
  114065. else {
  114066. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  114067. this._onBeforePhysicsObserver = null;
  114068. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  114069. this._onAfterPhysicsObserver = null;
  114070. }
  114071. },
  114072. enumerable: true,
  114073. configurable: true
  114074. });
  114075. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  114076. /**
  114077. * Gets the perf counter used for animations time
  114078. */
  114079. get: function () {
  114080. return this._animationsTime;
  114081. },
  114082. enumerable: true,
  114083. configurable: true
  114084. });
  114085. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  114086. /**
  114087. * Gets the animations time capture status
  114088. */
  114089. get: function () {
  114090. return this._captureAnimationsTime;
  114091. },
  114092. /**
  114093. * Enable or disable the animations time capture
  114094. */
  114095. set: function (value) {
  114096. var _this = this;
  114097. if (value === this._captureAnimationsTime) {
  114098. return;
  114099. }
  114100. this._captureAnimationsTime = value;
  114101. if (value) {
  114102. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  114103. _this._animationsTime.endMonitoring();
  114104. });
  114105. }
  114106. else {
  114107. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  114108. this._onAfterAnimationsObserver = null;
  114109. }
  114110. },
  114111. enumerable: true,
  114112. configurable: true
  114113. });
  114114. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  114115. /**
  114116. * Gets the perf counter used for frame time capture
  114117. */
  114118. get: function () {
  114119. return this._frameTime;
  114120. },
  114121. enumerable: true,
  114122. configurable: true
  114123. });
  114124. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  114125. /**
  114126. * Gets the frame time capture status
  114127. */
  114128. get: function () {
  114129. return this._captureFrameTime;
  114130. },
  114131. /**
  114132. * Enable or disable the frame time capture
  114133. */
  114134. set: function (value) {
  114135. this._captureFrameTime = value;
  114136. },
  114137. enumerable: true,
  114138. configurable: true
  114139. });
  114140. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  114141. /**
  114142. * Gets the perf counter used for inter-frames time capture
  114143. */
  114144. get: function () {
  114145. return this._interFrameTime;
  114146. },
  114147. enumerable: true,
  114148. configurable: true
  114149. });
  114150. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  114151. /**
  114152. * Gets the inter-frames time capture status
  114153. */
  114154. get: function () {
  114155. return this._captureInterFrameTime;
  114156. },
  114157. /**
  114158. * Enable or disable the inter-frames time capture
  114159. */
  114160. set: function (value) {
  114161. this._captureInterFrameTime = value;
  114162. },
  114163. enumerable: true,
  114164. configurable: true
  114165. });
  114166. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  114167. /**
  114168. * Gets the perf counter used for render time capture
  114169. */
  114170. get: function () {
  114171. return this._renderTime;
  114172. },
  114173. enumerable: true,
  114174. configurable: true
  114175. });
  114176. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  114177. /**
  114178. * Gets the render time capture status
  114179. */
  114180. get: function () {
  114181. return this._captureRenderTime;
  114182. },
  114183. /**
  114184. * Enable or disable the render time capture
  114185. */
  114186. set: function (value) {
  114187. var _this = this;
  114188. if (value === this._captureRenderTime) {
  114189. return;
  114190. }
  114191. this._captureRenderTime = value;
  114192. if (value) {
  114193. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  114194. _this._renderTime.beginMonitoring();
  114195. BABYLON.Tools.StartPerformanceCounter("Main render");
  114196. });
  114197. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  114198. _this._renderTime.endMonitoring(false);
  114199. BABYLON.Tools.EndPerformanceCounter("Main render");
  114200. });
  114201. }
  114202. else {
  114203. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  114204. this._onBeforeDrawPhaseObserver = null;
  114205. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  114206. this._onAfterDrawPhaseObserver = null;
  114207. }
  114208. },
  114209. enumerable: true,
  114210. configurable: true
  114211. });
  114212. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  114213. /**
  114214. * Gets the perf counter used for camera render time capture
  114215. */
  114216. get: function () {
  114217. return this._cameraRenderTime;
  114218. },
  114219. enumerable: true,
  114220. configurable: true
  114221. });
  114222. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  114223. /**
  114224. * Gets the camera render time capture status
  114225. */
  114226. get: function () {
  114227. return this._captureCameraRenderTime;
  114228. },
  114229. /**
  114230. * Enable or disable the camera render time capture
  114231. */
  114232. set: function (value) {
  114233. var _this = this;
  114234. if (value === this._captureCameraRenderTime) {
  114235. return;
  114236. }
  114237. this._captureCameraRenderTime = value;
  114238. if (value) {
  114239. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  114240. _this._cameraRenderTime.beginMonitoring();
  114241. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  114242. });
  114243. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  114244. _this._cameraRenderTime.endMonitoring(false);
  114245. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  114246. });
  114247. }
  114248. else {
  114249. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  114250. this._onBeforeCameraRenderObserver = null;
  114251. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  114252. this._onAfterCameraRenderObserver = null;
  114253. }
  114254. },
  114255. enumerable: true,
  114256. configurable: true
  114257. });
  114258. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  114259. /**
  114260. * Gets the perf counter used for draw calls
  114261. */
  114262. get: function () {
  114263. return this.scene.getEngine()._drawCalls;
  114264. },
  114265. enumerable: true,
  114266. configurable: true
  114267. });
  114268. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  114269. /**
  114270. * Gets the perf counter used for texture collisions
  114271. */
  114272. get: function () {
  114273. return this.scene.getEngine()._textureCollisions;
  114274. },
  114275. enumerable: true,
  114276. configurable: true
  114277. });
  114278. /**
  114279. * Dispose and release associated resources.
  114280. */
  114281. SceneInstrumentation.prototype.dispose = function () {
  114282. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  114283. this._onAfterRenderObserver = null;
  114284. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  114285. this._onBeforeActiveMeshesEvaluationObserver = null;
  114286. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  114287. this._onAfterActiveMeshesEvaluationObserver = null;
  114288. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  114289. this._onBeforeRenderTargetsRenderObserver = null;
  114290. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  114291. this._onAfterRenderTargetsRenderObserver = null;
  114292. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  114293. this._onBeforeAnimationsObserver = null;
  114294. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  114295. this._onBeforeParticlesRenderingObserver = null;
  114296. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  114297. this._onAfterParticlesRenderingObserver = null;
  114298. if (this._onBeforeSpritesRenderingObserver) {
  114299. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  114300. this._onBeforeSpritesRenderingObserver = null;
  114301. }
  114302. if (this._onAfterSpritesRenderingObserver) {
  114303. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  114304. this._onAfterSpritesRenderingObserver = null;
  114305. }
  114306. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  114307. this._onBeforeDrawPhaseObserver = null;
  114308. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  114309. this._onAfterDrawPhaseObserver = null;
  114310. if (this._onBeforePhysicsObserver) {
  114311. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  114312. this._onBeforePhysicsObserver = null;
  114313. }
  114314. if (this._onAfterPhysicsObserver) {
  114315. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  114316. this._onAfterPhysicsObserver = null;
  114317. }
  114318. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  114319. this._onAfterAnimationsObserver = null;
  114320. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  114321. this._onBeforeCameraRenderObserver = null;
  114322. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  114323. this._onAfterCameraRenderObserver = null;
  114324. this.scene = null;
  114325. };
  114326. return SceneInstrumentation;
  114327. }());
  114328. BABYLON.SceneInstrumentation = SceneInstrumentation;
  114329. })(BABYLON || (BABYLON = {}));
  114330. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  114331. var BABYLON;
  114332. (function (BABYLON) {
  114333. /**
  114334. * @hidden
  114335. **/
  114336. var _TimeToken = /** @class */ (function () {
  114337. function _TimeToken() {
  114338. this._timeElapsedQueryEnded = false;
  114339. }
  114340. return _TimeToken;
  114341. }());
  114342. BABYLON._TimeToken = _TimeToken;
  114343. })(BABYLON || (BABYLON = {}));
  114344. //# sourceMappingURL=babylon.timeToken.js.map
  114345. var BABYLON;
  114346. (function (BABYLON) {
  114347. /**
  114348. * Background material defines definition.
  114349. * @hidden Mainly internal Use
  114350. */
  114351. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  114352. __extends(BackgroundMaterialDefines, _super);
  114353. /**
  114354. * Constructor of the defines.
  114355. */
  114356. function BackgroundMaterialDefines() {
  114357. var _this = _super.call(this) || this;
  114358. /**
  114359. * True if the diffuse texture is in use.
  114360. */
  114361. _this.DIFFUSE = false;
  114362. /**
  114363. * The direct UV channel to use.
  114364. */
  114365. _this.DIFFUSEDIRECTUV = 0;
  114366. /**
  114367. * True if the diffuse texture is in gamma space.
  114368. */
  114369. _this.GAMMADIFFUSE = false;
  114370. /**
  114371. * True if the diffuse texture has opacity in the alpha channel.
  114372. */
  114373. _this.DIFFUSEHASALPHA = false;
  114374. /**
  114375. * True if you want the material to fade to transparent at grazing angle.
  114376. */
  114377. _this.OPACITYFRESNEL = false;
  114378. /**
  114379. * True if an extra blur needs to be added in the reflection.
  114380. */
  114381. _this.REFLECTIONBLUR = false;
  114382. /**
  114383. * True if you want the material to fade to reflection at grazing angle.
  114384. */
  114385. _this.REFLECTIONFRESNEL = false;
  114386. /**
  114387. * True if you want the material to falloff as far as you move away from the scene center.
  114388. */
  114389. _this.REFLECTIONFALLOFF = false;
  114390. /**
  114391. * False if the current Webgl implementation does not support the texture lod extension.
  114392. */
  114393. _this.TEXTURELODSUPPORT = false;
  114394. /**
  114395. * True to ensure the data are premultiplied.
  114396. */
  114397. _this.PREMULTIPLYALPHA = false;
  114398. /**
  114399. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  114400. */
  114401. _this.USERGBCOLOR = false;
  114402. /**
  114403. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  114404. * stays aligned with the desired configuration.
  114405. */
  114406. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  114407. /**
  114408. * True to add noise in order to reduce the banding effect.
  114409. */
  114410. _this.NOISE = false;
  114411. /**
  114412. * is the reflection texture in BGR color scheme?
  114413. * Mainly used to solve a bug in ios10 video tag
  114414. */
  114415. _this.REFLECTIONBGR = false;
  114416. _this.IMAGEPROCESSING = false;
  114417. _this.VIGNETTE = false;
  114418. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  114419. _this.VIGNETTEBLENDMODEOPAQUE = false;
  114420. _this.TONEMAPPING = false;
  114421. _this.TONEMAPPING_ACES = false;
  114422. _this.CONTRAST = false;
  114423. _this.COLORCURVES = false;
  114424. _this.COLORGRADING = false;
  114425. _this.COLORGRADING3D = false;
  114426. _this.SAMPLER3DGREENDEPTH = false;
  114427. _this.SAMPLER3DBGRMAP = false;
  114428. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  114429. _this.EXPOSURE = false;
  114430. // Reflection.
  114431. _this.REFLECTION = false;
  114432. _this.REFLECTIONMAP_3D = false;
  114433. _this.REFLECTIONMAP_SPHERICAL = false;
  114434. _this.REFLECTIONMAP_PLANAR = false;
  114435. _this.REFLECTIONMAP_CUBIC = false;
  114436. _this.REFLECTIONMAP_PROJECTION = false;
  114437. _this.REFLECTIONMAP_SKYBOX = false;
  114438. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  114439. _this.REFLECTIONMAP_EXPLICIT = false;
  114440. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  114441. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  114442. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  114443. _this.INVERTCUBICMAP = false;
  114444. _this.REFLECTIONMAP_OPPOSITEZ = false;
  114445. _this.LODINREFLECTIONALPHA = false;
  114446. _this.GAMMAREFLECTION = false;
  114447. _this.RGBDREFLECTION = false;
  114448. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  114449. // Default BJS.
  114450. _this.MAINUV1 = false;
  114451. _this.MAINUV2 = false;
  114452. _this.UV1 = false;
  114453. _this.UV2 = false;
  114454. _this.CLIPPLANE = false;
  114455. _this.CLIPPLANE2 = false;
  114456. _this.CLIPPLANE3 = false;
  114457. _this.CLIPPLANE4 = false;
  114458. _this.POINTSIZE = false;
  114459. _this.FOG = false;
  114460. _this.NORMAL = false;
  114461. _this.NUM_BONE_INFLUENCERS = 0;
  114462. _this.BonesPerMesh = 0;
  114463. _this.INSTANCES = false;
  114464. _this.SHADOWFLOAT = false;
  114465. _this.rebuild();
  114466. return _this;
  114467. }
  114468. return BackgroundMaterialDefines;
  114469. }(BABYLON.MaterialDefines));
  114470. /**
  114471. * Background material used to create an efficient environement around your scene.
  114472. */
  114473. var BackgroundMaterial = /** @class */ (function (_super) {
  114474. __extends(BackgroundMaterial, _super);
  114475. /**
  114476. * Instantiates a Background Material in the given scene
  114477. * @param name The friendly name of the material
  114478. * @param scene The scene to add the material to
  114479. */
  114480. function BackgroundMaterial(name, scene) {
  114481. var _this = _super.call(this, name, scene) || this;
  114482. /**
  114483. * Key light Color (multiply against the environement texture)
  114484. */
  114485. _this.primaryColor = BABYLON.Color3.White();
  114486. _this._primaryColorShadowLevel = 0;
  114487. _this._primaryColorHighlightLevel = 0;
  114488. /**
  114489. * Reflection Texture used in the material.
  114490. * Should be author in a specific way for the best result (refer to the documentation).
  114491. */
  114492. _this.reflectionTexture = null;
  114493. /**
  114494. * Reflection Texture level of blur.
  114495. *
  114496. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  114497. * texture twice.
  114498. */
  114499. _this.reflectionBlur = 0;
  114500. /**
  114501. * Diffuse Texture used in the material.
  114502. * Should be author in a specific way for the best result (refer to the documentation).
  114503. */
  114504. _this.diffuseTexture = null;
  114505. _this._shadowLights = null;
  114506. /**
  114507. * Specify the list of lights casting shadow on the material.
  114508. * All scene shadow lights will be included if null.
  114509. */
  114510. _this.shadowLights = null;
  114511. /**
  114512. * Helps adjusting the shadow to a softer level if required.
  114513. * 0 means black shadows and 1 means no shadows.
  114514. */
  114515. _this.shadowLevel = 0;
  114516. /**
  114517. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  114518. * It is usually zero but might be interesting to modify according to your setup.
  114519. */
  114520. _this.sceneCenter = BABYLON.Vector3.Zero();
  114521. /**
  114522. * This helps specifying that the material is falling off to the sky box at grazing angle.
  114523. * This helps ensuring a nice transition when the camera goes under the ground.
  114524. */
  114525. _this.opacityFresnel = true;
  114526. /**
  114527. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  114528. * This helps adding a mirror texture on the ground.
  114529. */
  114530. _this.reflectionFresnel = false;
  114531. /**
  114532. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  114533. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  114534. */
  114535. _this.reflectionFalloffDistance = 0.0;
  114536. /**
  114537. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  114538. */
  114539. _this.reflectionAmount = 1.0;
  114540. /**
  114541. * This specifies the weight of the reflection at grazing angle.
  114542. */
  114543. _this.reflectionReflectance0 = 0.05;
  114544. /**
  114545. * This specifies the weight of the reflection at a perpendicular point of view.
  114546. */
  114547. _this.reflectionReflectance90 = 0.5;
  114548. /**
  114549. * Helps to directly use the maps channels instead of their level.
  114550. */
  114551. _this.useRGBColor = true;
  114552. /**
  114553. * This helps reducing the banding effect that could occur on the background.
  114554. */
  114555. _this.enableNoise = false;
  114556. _this._fovMultiplier = 1.0;
  114557. /**
  114558. * Enable the FOV adjustment feature controlled by fovMultiplier.
  114559. */
  114560. _this.useEquirectangularFOV = false;
  114561. _this._maxSimultaneousLights = 4;
  114562. /**
  114563. * Number of Simultaneous lights allowed on the material.
  114564. */
  114565. _this.maxSimultaneousLights = 4;
  114566. /**
  114567. * Keep track of the image processing observer to allow dispose and replace.
  114568. */
  114569. _this._imageProcessingObserver = null;
  114570. /**
  114571. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  114572. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  114573. */
  114574. _this.switchToBGR = false;
  114575. // Temp values kept as cache in the material.
  114576. _this._renderTargets = new BABYLON.SmartArray(16);
  114577. _this._reflectionControls = BABYLON.Vector4.Zero();
  114578. _this._white = BABYLON.Color3.White();
  114579. _this._primaryShadowColor = BABYLON.Color3.Black();
  114580. _this._primaryHighlightColor = BABYLON.Color3.Black();
  114581. // Setup the default processing configuration to the scene.
  114582. _this._attachImageProcessingConfiguration(null);
  114583. _this.getRenderTargetTextures = function () {
  114584. _this._renderTargets.reset();
  114585. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  114586. _this._renderTargets.push(_this._diffuseTexture);
  114587. }
  114588. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  114589. _this._renderTargets.push(_this._reflectionTexture);
  114590. }
  114591. return _this._renderTargets;
  114592. };
  114593. return _this;
  114594. }
  114595. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  114596. /**
  114597. * Experimental Internal Use Only.
  114598. *
  114599. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  114600. * This acts as a helper to set the primary color to a more "human friendly" value.
  114601. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  114602. * output color as close as possible from the chosen value.
  114603. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  114604. * part of lighting setup.)
  114605. */
  114606. get: function () {
  114607. return this.__perceptualColor;
  114608. },
  114609. set: function (value) {
  114610. this.__perceptualColor = value;
  114611. this._computePrimaryColorFromPerceptualColor();
  114612. this._markAllSubMeshesAsLightsDirty();
  114613. },
  114614. enumerable: true,
  114615. configurable: true
  114616. });
  114617. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  114618. /**
  114619. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  114620. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  114621. */
  114622. get: function () {
  114623. return this._primaryColorShadowLevel;
  114624. },
  114625. set: function (value) {
  114626. this._primaryColorShadowLevel = value;
  114627. this._computePrimaryColors();
  114628. this._markAllSubMeshesAsLightsDirty();
  114629. },
  114630. enumerable: true,
  114631. configurable: true
  114632. });
  114633. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  114634. /**
  114635. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  114636. * The primary color is used at the level chosen to define what the white area would look.
  114637. */
  114638. get: function () {
  114639. return this._primaryColorHighlightLevel;
  114640. },
  114641. set: function (value) {
  114642. this._primaryColorHighlightLevel = value;
  114643. this._computePrimaryColors();
  114644. this._markAllSubMeshesAsLightsDirty();
  114645. },
  114646. enumerable: true,
  114647. configurable: true
  114648. });
  114649. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  114650. /**
  114651. * Sets the reflection reflectance fresnel values according to the default standard
  114652. * empirically know to work well :-)
  114653. */
  114654. set: function (value) {
  114655. var reflectionWeight = value;
  114656. if (reflectionWeight < 0.5) {
  114657. reflectionWeight = reflectionWeight * 2.0;
  114658. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  114659. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  114660. }
  114661. else {
  114662. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  114663. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  114664. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  114665. }
  114666. },
  114667. enumerable: true,
  114668. configurable: true
  114669. });
  114670. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  114671. /**
  114672. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  114673. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  114674. * Recommended to be keep at 1.0 except for special cases.
  114675. */
  114676. get: function () {
  114677. return this._fovMultiplier;
  114678. },
  114679. set: function (value) {
  114680. if (isNaN(value)) {
  114681. value = 1.0;
  114682. }
  114683. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  114684. },
  114685. enumerable: true,
  114686. configurable: true
  114687. });
  114688. /**
  114689. * Attaches a new image processing configuration to the PBR Material.
  114690. * @param configuration (if null the scene configuration will be use)
  114691. */
  114692. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  114693. var _this = this;
  114694. if (configuration === this._imageProcessingConfiguration) {
  114695. return;
  114696. }
  114697. // Detaches observer.
  114698. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  114699. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  114700. }
  114701. // Pick the scene configuration if needed.
  114702. if (!configuration) {
  114703. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  114704. }
  114705. else {
  114706. this._imageProcessingConfiguration = configuration;
  114707. }
  114708. // Attaches observer.
  114709. if (this._imageProcessingConfiguration) {
  114710. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  114711. _this._computePrimaryColorFromPerceptualColor();
  114712. _this._markAllSubMeshesAsImageProcessingDirty();
  114713. });
  114714. }
  114715. };
  114716. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  114717. /**
  114718. * Gets the image processing configuration used either in this material.
  114719. */
  114720. get: function () {
  114721. return this._imageProcessingConfiguration;
  114722. },
  114723. /**
  114724. * Sets the Default image processing configuration used either in the this material.
  114725. *
  114726. * If sets to null, the scene one is in use.
  114727. */
  114728. set: function (value) {
  114729. this._attachImageProcessingConfiguration(value);
  114730. // Ensure the effect will be rebuilt.
  114731. this._markAllSubMeshesAsTexturesDirty();
  114732. },
  114733. enumerable: true,
  114734. configurable: true
  114735. });
  114736. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  114737. /**
  114738. * Gets wether the color curves effect is enabled.
  114739. */
  114740. get: function () {
  114741. return this.imageProcessingConfiguration.colorCurvesEnabled;
  114742. },
  114743. /**
  114744. * Sets wether the color curves effect is enabled.
  114745. */
  114746. set: function (value) {
  114747. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  114748. },
  114749. enumerable: true,
  114750. configurable: true
  114751. });
  114752. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  114753. /**
  114754. * Gets wether the color grading effect is enabled.
  114755. */
  114756. get: function () {
  114757. return this.imageProcessingConfiguration.colorGradingEnabled;
  114758. },
  114759. /**
  114760. * Gets wether the color grading effect is enabled.
  114761. */
  114762. set: function (value) {
  114763. this.imageProcessingConfiguration.colorGradingEnabled = value;
  114764. },
  114765. enumerable: true,
  114766. configurable: true
  114767. });
  114768. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  114769. /**
  114770. * Gets wether tonemapping is enabled or not.
  114771. */
  114772. get: function () {
  114773. return this._imageProcessingConfiguration.toneMappingEnabled;
  114774. },
  114775. /**
  114776. * Sets wether tonemapping is enabled or not
  114777. */
  114778. set: function (value) {
  114779. this._imageProcessingConfiguration.toneMappingEnabled = value;
  114780. },
  114781. enumerable: true,
  114782. configurable: true
  114783. });
  114784. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  114785. /**
  114786. * The camera exposure used on this material.
  114787. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  114788. * This corresponds to a photographic exposure.
  114789. */
  114790. get: function () {
  114791. return this._imageProcessingConfiguration.exposure;
  114792. },
  114793. /**
  114794. * The camera exposure used on this material.
  114795. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  114796. * This corresponds to a photographic exposure.
  114797. */
  114798. set: function (value) {
  114799. this._imageProcessingConfiguration.exposure = value;
  114800. },
  114801. enumerable: true,
  114802. configurable: true
  114803. });
  114804. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  114805. /**
  114806. * Gets The camera contrast used on this material.
  114807. */
  114808. get: function () {
  114809. return this._imageProcessingConfiguration.contrast;
  114810. },
  114811. /**
  114812. * Sets The camera contrast used on this material.
  114813. */
  114814. set: function (value) {
  114815. this._imageProcessingConfiguration.contrast = value;
  114816. },
  114817. enumerable: true,
  114818. configurable: true
  114819. });
  114820. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  114821. /**
  114822. * Gets the Color Grading 2D Lookup Texture.
  114823. */
  114824. get: function () {
  114825. return this._imageProcessingConfiguration.colorGradingTexture;
  114826. },
  114827. /**
  114828. * Sets the Color Grading 2D Lookup Texture.
  114829. */
  114830. set: function (value) {
  114831. this.imageProcessingConfiguration.colorGradingTexture = value;
  114832. },
  114833. enumerable: true,
  114834. configurable: true
  114835. });
  114836. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  114837. /**
  114838. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  114839. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  114840. * 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;
  114841. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  114842. */
  114843. get: function () {
  114844. return this.imageProcessingConfiguration.colorCurves;
  114845. },
  114846. /**
  114847. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  114848. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  114849. * 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;
  114850. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  114851. */
  114852. set: function (value) {
  114853. this.imageProcessingConfiguration.colorCurves = value;
  114854. },
  114855. enumerable: true,
  114856. configurable: true
  114857. });
  114858. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  114859. /**
  114860. * Gets a boolean indicating that current material needs to register RTT
  114861. */
  114862. get: function () {
  114863. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  114864. return true;
  114865. }
  114866. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  114867. return true;
  114868. }
  114869. return false;
  114870. },
  114871. enumerable: true,
  114872. configurable: true
  114873. });
  114874. /**
  114875. * The entire material has been created in order to prevent overdraw.
  114876. * @returns false
  114877. */
  114878. BackgroundMaterial.prototype.needAlphaTesting = function () {
  114879. return true;
  114880. };
  114881. /**
  114882. * The entire material has been created in order to prevent overdraw.
  114883. * @returns true if blending is enable
  114884. */
  114885. BackgroundMaterial.prototype.needAlphaBlending = function () {
  114886. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  114887. };
  114888. /**
  114889. * Checks wether the material is ready to be rendered for a given mesh.
  114890. * @param mesh The mesh to render
  114891. * @param subMesh The submesh to check against
  114892. * @param useInstances Specify wether or not the material is used with instances
  114893. * @returns true if all the dependencies are ready (Textures, Effects...)
  114894. */
  114895. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  114896. var _this = this;
  114897. if (useInstances === void 0) { useInstances = false; }
  114898. if (subMesh.effect && this.isFrozen) {
  114899. if (this._wasPreviouslyReady) {
  114900. return true;
  114901. }
  114902. }
  114903. if (!subMesh._materialDefines) {
  114904. subMesh._materialDefines = new BackgroundMaterialDefines();
  114905. }
  114906. var scene = this.getScene();
  114907. var defines = subMesh._materialDefines;
  114908. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  114909. if (defines._renderId === scene.getRenderId()) {
  114910. return true;
  114911. }
  114912. }
  114913. var engine = scene.getEngine();
  114914. // Lights
  114915. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  114916. defines._needNormals = true;
  114917. // Textures
  114918. if (defines._areTexturesDirty) {
  114919. defines._needUVs = false;
  114920. if (scene.texturesEnabled) {
  114921. if (scene.getEngine().getCaps().textureLOD) {
  114922. defines.TEXTURELODSUPPORT = true;
  114923. }
  114924. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  114925. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  114926. return false;
  114927. }
  114928. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  114929. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  114930. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  114931. defines.OPACITYFRESNEL = this._opacityFresnel;
  114932. }
  114933. else {
  114934. defines.DIFFUSE = false;
  114935. defines.DIFFUSEHASALPHA = false;
  114936. defines.GAMMADIFFUSE = false;
  114937. defines.OPACITYFRESNEL = false;
  114938. }
  114939. var reflectionTexture = this._reflectionTexture;
  114940. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  114941. if (!reflectionTexture.isReadyOrNotBlocking()) {
  114942. return false;
  114943. }
  114944. defines.REFLECTION = true;
  114945. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  114946. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  114947. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  114948. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  114949. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  114950. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  114951. defines.REFLECTIONBGR = this.switchToBGR;
  114952. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  114953. defines.INVERTCUBICMAP = true;
  114954. }
  114955. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  114956. switch (reflectionTexture.coordinatesMode) {
  114957. case BABYLON.Texture.EXPLICIT_MODE:
  114958. defines.REFLECTIONMAP_EXPLICIT = true;
  114959. break;
  114960. case BABYLON.Texture.PLANAR_MODE:
  114961. defines.REFLECTIONMAP_PLANAR = true;
  114962. break;
  114963. case BABYLON.Texture.PROJECTION_MODE:
  114964. defines.REFLECTIONMAP_PROJECTION = true;
  114965. break;
  114966. case BABYLON.Texture.SKYBOX_MODE:
  114967. defines.REFLECTIONMAP_SKYBOX = true;
  114968. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  114969. break;
  114970. case BABYLON.Texture.SPHERICAL_MODE:
  114971. defines.REFLECTIONMAP_SPHERICAL = true;
  114972. break;
  114973. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  114974. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  114975. break;
  114976. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  114977. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  114978. break;
  114979. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  114980. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  114981. break;
  114982. case BABYLON.Texture.CUBIC_MODE:
  114983. case BABYLON.Texture.INVCUBIC_MODE:
  114984. default:
  114985. defines.REFLECTIONMAP_CUBIC = true;
  114986. break;
  114987. }
  114988. if (this.reflectionFresnel) {
  114989. defines.REFLECTIONFRESNEL = true;
  114990. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  114991. this._reflectionControls.x = this.reflectionAmount;
  114992. this._reflectionControls.y = this.reflectionReflectance0;
  114993. this._reflectionControls.z = this.reflectionReflectance90;
  114994. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  114995. }
  114996. else {
  114997. defines.REFLECTIONFRESNEL = false;
  114998. defines.REFLECTIONFALLOFF = false;
  114999. }
  115000. }
  115001. else {
  115002. defines.REFLECTION = false;
  115003. defines.REFLECTIONFRESNEL = false;
  115004. defines.REFLECTIONFALLOFF = false;
  115005. defines.REFLECTIONBLUR = false;
  115006. defines.REFLECTIONMAP_3D = false;
  115007. defines.REFLECTIONMAP_SPHERICAL = false;
  115008. defines.REFLECTIONMAP_PLANAR = false;
  115009. defines.REFLECTIONMAP_CUBIC = false;
  115010. defines.REFLECTIONMAP_PROJECTION = false;
  115011. defines.REFLECTIONMAP_SKYBOX = false;
  115012. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  115013. defines.REFLECTIONMAP_EXPLICIT = false;
  115014. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  115015. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  115016. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  115017. defines.INVERTCUBICMAP = false;
  115018. defines.REFLECTIONMAP_OPPOSITEZ = false;
  115019. defines.LODINREFLECTIONALPHA = false;
  115020. defines.GAMMAREFLECTION = false;
  115021. defines.RGBDREFLECTION = false;
  115022. }
  115023. }
  115024. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  115025. defines.USERGBCOLOR = this._useRGBColor;
  115026. defines.NOISE = this._enableNoise;
  115027. }
  115028. if (defines._areLightsDirty) {
  115029. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  115030. }
  115031. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  115032. if (!this._imageProcessingConfiguration.isReady()) {
  115033. return false;
  115034. }
  115035. this._imageProcessingConfiguration.prepareDefines(defines);
  115036. }
  115037. // Misc.
  115038. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  115039. // Values that need to be evaluated on every frame
  115040. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  115041. // Attribs
  115042. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  115043. if (mesh) {
  115044. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  115045. mesh.createNormals(true);
  115046. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  115047. }
  115048. }
  115049. }
  115050. // Get correct effect
  115051. if (defines.isDirty) {
  115052. defines.markAsProcessed();
  115053. scene.resetCachedMaterial();
  115054. // Fallbacks
  115055. var fallbacks = new BABYLON.EffectFallbacks();
  115056. if (defines.FOG) {
  115057. fallbacks.addFallback(0, "FOG");
  115058. }
  115059. if (defines.POINTSIZE) {
  115060. fallbacks.addFallback(1, "POINTSIZE");
  115061. }
  115062. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  115063. if (defines.NUM_BONE_INFLUENCERS > 0) {
  115064. fallbacks.addCPUSkinningFallback(0, mesh);
  115065. }
  115066. //Attributes
  115067. var attribs = [BABYLON.VertexBuffer.PositionKind];
  115068. if (defines.NORMAL) {
  115069. attribs.push(BABYLON.VertexBuffer.NormalKind);
  115070. }
  115071. if (defines.UV1) {
  115072. attribs.push(BABYLON.VertexBuffer.UVKind);
  115073. }
  115074. if (defines.UV2) {
  115075. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  115076. }
  115077. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  115078. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  115079. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  115080. "vFogInfos", "vFogColor", "pointSize",
  115081. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  115082. "vPrimaryColor", "vPrimaryColorShadow",
  115083. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  115084. "shadowLevel", "alpha",
  115085. "vBackgroundCenter", "vReflectionControl",
  115086. "vDiffuseInfos", "diffuseMatrix",
  115087. ];
  115088. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  115089. var uniformBuffers = ["Material", "Scene"];
  115090. if (BABYLON.ImageProcessingConfiguration) {
  115091. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  115092. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  115093. }
  115094. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  115095. uniformsNames: uniforms,
  115096. uniformBuffersNames: uniformBuffers,
  115097. samplers: samplers,
  115098. defines: defines,
  115099. maxSimultaneousLights: this._maxSimultaneousLights
  115100. });
  115101. var onCompiled = function (effect) {
  115102. if (_this.onCompiled) {
  115103. _this.onCompiled(effect);
  115104. }
  115105. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  115106. };
  115107. var join = defines.toString();
  115108. subMesh.setEffect(scene.getEngine().createEffect("background", {
  115109. attributes: attribs,
  115110. uniformsNames: uniforms,
  115111. uniformBuffersNames: uniformBuffers,
  115112. samplers: samplers,
  115113. defines: join,
  115114. fallbacks: fallbacks,
  115115. onCompiled: onCompiled,
  115116. onError: this.onError,
  115117. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  115118. }, engine), defines);
  115119. this.buildUniformLayout();
  115120. }
  115121. if (!subMesh.effect || !subMesh.effect.isReady()) {
  115122. return false;
  115123. }
  115124. defines._renderId = scene.getRenderId();
  115125. this._wasPreviouslyReady = true;
  115126. return true;
  115127. };
  115128. /**
  115129. * Compute the primary color according to the chosen perceptual color.
  115130. */
  115131. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  115132. if (!this.__perceptualColor) {
  115133. return;
  115134. }
  115135. this._primaryColor.copyFrom(this.__perceptualColor);
  115136. // Revert gamma space.
  115137. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  115138. // Revert image processing configuration.
  115139. if (this._imageProcessingConfiguration) {
  115140. // Revert Exposure.
  115141. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  115142. }
  115143. this._computePrimaryColors();
  115144. };
  115145. /**
  115146. * Compute the highlights and shadow colors according to their chosen levels.
  115147. */
  115148. BackgroundMaterial.prototype._computePrimaryColors = function () {
  115149. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  115150. return;
  115151. }
  115152. // Find the highlight color based on the configuration.
  115153. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  115154. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  115155. // Find the shadow color based on the configuration.
  115156. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  115157. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  115158. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  115159. };
  115160. /**
  115161. * Build the uniform buffer used in the material.
  115162. */
  115163. BackgroundMaterial.prototype.buildUniformLayout = function () {
  115164. // Order is important !
  115165. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  115166. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  115167. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  115168. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  115169. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  115170. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  115171. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  115172. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  115173. this._uniformBuffer.addUniform("pointSize", 1);
  115174. this._uniformBuffer.addUniform("shadowLevel", 1);
  115175. this._uniformBuffer.addUniform("alpha", 1);
  115176. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  115177. this._uniformBuffer.addUniform("vReflectionControl", 4);
  115178. this._uniformBuffer.create();
  115179. };
  115180. /**
  115181. * Unbind the material.
  115182. */
  115183. BackgroundMaterial.prototype.unbind = function () {
  115184. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  115185. this._uniformBuffer.setTexture("diffuseSampler", null);
  115186. }
  115187. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  115188. this._uniformBuffer.setTexture("reflectionSampler", null);
  115189. }
  115190. _super.prototype.unbind.call(this);
  115191. };
  115192. /**
  115193. * Bind only the world matrix to the material.
  115194. * @param world The world matrix to bind.
  115195. */
  115196. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  115197. this._activeEffect.setMatrix("world", world);
  115198. };
  115199. /**
  115200. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  115201. * @param world The world matrix to bind.
  115202. * @param subMesh The submesh to bind for.
  115203. */
  115204. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  115205. var scene = this.getScene();
  115206. var defines = subMesh._materialDefines;
  115207. if (!defines) {
  115208. return;
  115209. }
  115210. var effect = subMesh.effect;
  115211. if (!effect) {
  115212. return;
  115213. }
  115214. this._activeEffect = effect;
  115215. // Matrices
  115216. this.bindOnlyWorldMatrix(world);
  115217. // Bones
  115218. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  115219. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  115220. if (mustRebind) {
  115221. this._uniformBuffer.bindToEffect(effect, "Material");
  115222. this.bindViewProjection(effect);
  115223. var reflectionTexture = this._reflectionTexture;
  115224. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  115225. // Texture uniforms
  115226. if (scene.texturesEnabled) {
  115227. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  115228. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  115229. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  115230. }
  115231. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  115232. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  115233. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  115234. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  115235. }
  115236. }
  115237. if (this.shadowLevel > 0) {
  115238. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  115239. }
  115240. this._uniformBuffer.updateFloat("alpha", this.alpha);
  115241. // Point size
  115242. if (this.pointsCloud) {
  115243. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  115244. }
  115245. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  115246. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  115247. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  115248. }
  115249. else {
  115250. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  115251. }
  115252. }
  115253. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  115254. // Textures
  115255. if (scene.texturesEnabled) {
  115256. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  115257. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  115258. }
  115259. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  115260. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  115261. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  115262. }
  115263. else if (!defines.REFLECTIONBLUR) {
  115264. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  115265. }
  115266. else {
  115267. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  115268. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  115269. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  115270. }
  115271. if (defines.REFLECTIONFRESNEL) {
  115272. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  115273. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  115274. }
  115275. }
  115276. }
  115277. // Clip plane
  115278. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  115279. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  115280. }
  115281. if (mustRebind || !this.isFrozen) {
  115282. if (scene.lightsEnabled) {
  115283. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  115284. }
  115285. // View
  115286. this.bindView(effect);
  115287. // Fog
  115288. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  115289. // image processing
  115290. if (this._imageProcessingConfiguration) {
  115291. this._imageProcessingConfiguration.bind(this._activeEffect);
  115292. }
  115293. }
  115294. this._uniformBuffer.update();
  115295. this._afterBind(mesh, this._activeEffect);
  115296. };
  115297. /**
  115298. * Dispose the material.
  115299. * @param forceDisposeEffect Force disposal of the associated effect.
  115300. * @param forceDisposeTextures Force disposal of the associated textures.
  115301. */
  115302. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  115303. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  115304. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  115305. if (forceDisposeTextures) {
  115306. if (this.diffuseTexture) {
  115307. this.diffuseTexture.dispose();
  115308. }
  115309. if (this.reflectionTexture) {
  115310. this.reflectionTexture.dispose();
  115311. }
  115312. }
  115313. this._renderTargets.dispose();
  115314. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  115315. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  115316. }
  115317. _super.prototype.dispose.call(this, forceDisposeEffect);
  115318. };
  115319. /**
  115320. * Clones the material.
  115321. * @param name The cloned name.
  115322. * @returns The cloned material.
  115323. */
  115324. BackgroundMaterial.prototype.clone = function (name) {
  115325. var _this = this;
  115326. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  115327. };
  115328. /**
  115329. * Serializes the current material to its JSON representation.
  115330. * @returns The JSON representation.
  115331. */
  115332. BackgroundMaterial.prototype.serialize = function () {
  115333. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  115334. serializationObject.customType = "BABYLON.BackgroundMaterial";
  115335. return serializationObject;
  115336. };
  115337. /**
  115338. * Gets the class name of the material
  115339. * @returns "BackgroundMaterial"
  115340. */
  115341. BackgroundMaterial.prototype.getClassName = function () {
  115342. return "BackgroundMaterial";
  115343. };
  115344. /**
  115345. * Parse a JSON input to create back a background material.
  115346. * @param source The JSON data to parse
  115347. * @param scene The scene to create the parsed material in
  115348. * @param rootUrl The root url of the assets the material depends upon
  115349. * @returns the instantiated BackgroundMaterial.
  115350. */
  115351. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  115352. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  115353. };
  115354. /**
  115355. * Standard reflectance value at parallel view angle.
  115356. */
  115357. BackgroundMaterial.StandardReflectance0 = 0.05;
  115358. /**
  115359. * Standard reflectance value at grazing angle.
  115360. */
  115361. BackgroundMaterial.StandardReflectance90 = 0.5;
  115362. __decorate([
  115363. BABYLON.serializeAsColor3()
  115364. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  115365. __decorate([
  115366. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  115367. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  115368. __decorate([
  115369. BABYLON.serializeAsColor3()
  115370. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  115371. __decorate([
  115372. BABYLON.serialize()
  115373. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  115374. __decorate([
  115375. BABYLON.serialize()
  115376. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  115377. __decorate([
  115378. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  115379. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  115380. __decorate([
  115381. BABYLON.serializeAsTexture()
  115382. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  115383. __decorate([
  115384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115385. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  115386. __decorate([
  115387. BABYLON.serialize()
  115388. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  115389. __decorate([
  115390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115391. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  115392. __decorate([
  115393. BABYLON.serializeAsTexture()
  115394. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  115395. __decorate([
  115396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115397. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  115398. __decorate([
  115399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115400. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  115401. __decorate([
  115402. BABYLON.serialize()
  115403. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  115404. __decorate([
  115405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115406. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  115407. __decorate([
  115408. BABYLON.serializeAsVector3()
  115409. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  115410. __decorate([
  115411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115412. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  115413. __decorate([
  115414. BABYLON.serialize()
  115415. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  115416. __decorate([
  115417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115418. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  115419. __decorate([
  115420. BABYLON.serialize()
  115421. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  115422. __decorate([
  115423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115424. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  115425. __decorate([
  115426. BABYLON.serialize()
  115427. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  115428. __decorate([
  115429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115430. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  115431. __decorate([
  115432. BABYLON.serialize()
  115433. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  115434. __decorate([
  115435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115436. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  115437. __decorate([
  115438. BABYLON.serialize()
  115439. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  115440. __decorate([
  115441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115442. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  115443. __decorate([
  115444. BABYLON.serialize()
  115445. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  115446. __decorate([
  115447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115448. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  115449. __decorate([
  115450. BABYLON.serialize()
  115451. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  115452. __decorate([
  115453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115454. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  115455. __decorate([
  115456. BABYLON.serialize()
  115457. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  115458. __decorate([
  115459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115460. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  115461. __decorate([
  115462. BABYLON.serialize()
  115463. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  115464. __decorate([
  115465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115466. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  115467. __decorate([
  115468. BABYLON.serializeAsImageProcessingConfiguration()
  115469. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  115470. return BackgroundMaterial;
  115471. }(BABYLON.PushMaterial));
  115472. BABYLON.BackgroundMaterial = BackgroundMaterial;
  115473. })(BABYLON || (BABYLON = {}));
  115474. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  115475. var __assign = (this && this.__assign) || function () {
  115476. __assign = Object.assign || function(t) {
  115477. for (var s, i = 1, n = arguments.length; i < n; i++) {
  115478. s = arguments[i];
  115479. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  115480. t[p] = s[p];
  115481. }
  115482. return t;
  115483. };
  115484. return __assign.apply(this, arguments);
  115485. };
  115486. var BABYLON;
  115487. (function (BABYLON) {
  115488. /**
  115489. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  115490. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  115491. * It also helps with the default setup of your imageProcessing configuration.
  115492. */
  115493. var EnvironmentHelper = /** @class */ (function () {
  115494. /**
  115495. * constructor
  115496. * @param options
  115497. * @param scene The scene to add the material to
  115498. */
  115499. function EnvironmentHelper(options, scene) {
  115500. var _this = this;
  115501. this._errorHandler = function (message, exception) {
  115502. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  115503. };
  115504. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  115505. this._scene = scene;
  115506. this.onErrorObservable = new BABYLON.Observable();
  115507. this._setupBackground();
  115508. this._setupImageProcessing();
  115509. }
  115510. /**
  115511. * Creates the default options for the helper.
  115512. */
  115513. EnvironmentHelper._getDefaultOptions = function () {
  115514. return {
  115515. createGround: true,
  115516. groundSize: 15,
  115517. groundTexture: this._groundTextureCDNUrl,
  115518. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  115519. groundOpacity: 0.9,
  115520. enableGroundShadow: true,
  115521. groundShadowLevel: 0.5,
  115522. enableGroundMirror: false,
  115523. groundMirrorSizeRatio: 0.3,
  115524. groundMirrorBlurKernel: 64,
  115525. groundMirrorAmount: 1,
  115526. groundMirrorFresnelWeight: 1,
  115527. groundMirrorFallOffDistance: 0,
  115528. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  115529. groundYBias: 0.00001,
  115530. createSkybox: true,
  115531. skyboxSize: 20,
  115532. skyboxTexture: this._skyboxTextureCDNUrl,
  115533. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  115534. backgroundYRotation: 0,
  115535. sizeAuto: true,
  115536. rootPosition: BABYLON.Vector3.Zero(),
  115537. setupImageProcessing: true,
  115538. environmentTexture: this._environmentTextureCDNUrl,
  115539. cameraExposure: 0.8,
  115540. cameraContrast: 1.2,
  115541. toneMappingEnabled: true,
  115542. };
  115543. };
  115544. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  115545. /**
  115546. * Gets the root mesh created by the helper.
  115547. */
  115548. get: function () {
  115549. return this._rootMesh;
  115550. },
  115551. enumerable: true,
  115552. configurable: true
  115553. });
  115554. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  115555. /**
  115556. * Gets the skybox created by the helper.
  115557. */
  115558. get: function () {
  115559. return this._skybox;
  115560. },
  115561. enumerable: true,
  115562. configurable: true
  115563. });
  115564. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  115565. /**
  115566. * Gets the skybox texture created by the helper.
  115567. */
  115568. get: function () {
  115569. return this._skyboxTexture;
  115570. },
  115571. enumerable: true,
  115572. configurable: true
  115573. });
  115574. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  115575. /**
  115576. * Gets the skybox material created by the helper.
  115577. */
  115578. get: function () {
  115579. return this._skyboxMaterial;
  115580. },
  115581. enumerable: true,
  115582. configurable: true
  115583. });
  115584. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  115585. /**
  115586. * Gets the ground mesh created by the helper.
  115587. */
  115588. get: function () {
  115589. return this._ground;
  115590. },
  115591. enumerable: true,
  115592. configurable: true
  115593. });
  115594. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  115595. /**
  115596. * Gets the ground texture created by the helper.
  115597. */
  115598. get: function () {
  115599. return this._groundTexture;
  115600. },
  115601. enumerable: true,
  115602. configurable: true
  115603. });
  115604. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  115605. /**
  115606. * Gets the ground mirror created by the helper.
  115607. */
  115608. get: function () {
  115609. return this._groundMirror;
  115610. },
  115611. enumerable: true,
  115612. configurable: true
  115613. });
  115614. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  115615. /**
  115616. * Gets the ground mirror render list to helps pushing the meshes
  115617. * you wish in the ground reflection.
  115618. */
  115619. get: function () {
  115620. if (this._groundMirror) {
  115621. return this._groundMirror.renderList;
  115622. }
  115623. return null;
  115624. },
  115625. enumerable: true,
  115626. configurable: true
  115627. });
  115628. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  115629. /**
  115630. * Gets the ground material created by the helper.
  115631. */
  115632. get: function () {
  115633. return this._groundMaterial;
  115634. },
  115635. enumerable: true,
  115636. configurable: true
  115637. });
  115638. /**
  115639. * Updates the background according to the new options
  115640. * @param options
  115641. */
  115642. EnvironmentHelper.prototype.updateOptions = function (options) {
  115643. var newOptions = __assign({}, this._options, options);
  115644. if (this._ground && !newOptions.createGround) {
  115645. this._ground.dispose();
  115646. this._ground = null;
  115647. }
  115648. if (this._groundMaterial && !newOptions.createGround) {
  115649. this._groundMaterial.dispose();
  115650. this._groundMaterial = null;
  115651. }
  115652. if (this._groundTexture) {
  115653. if (this._options.groundTexture != newOptions.groundTexture) {
  115654. this._groundTexture.dispose();
  115655. this._groundTexture = null;
  115656. }
  115657. }
  115658. if (this._skybox && !newOptions.createSkybox) {
  115659. this._skybox.dispose();
  115660. this._skybox = null;
  115661. }
  115662. if (this._skyboxMaterial && !newOptions.createSkybox) {
  115663. this._skyboxMaterial.dispose();
  115664. this._skyboxMaterial = null;
  115665. }
  115666. if (this._skyboxTexture) {
  115667. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  115668. this._skyboxTexture.dispose();
  115669. this._skyboxTexture = null;
  115670. }
  115671. }
  115672. if (this._groundMirror && !newOptions.enableGroundMirror) {
  115673. this._groundMirror.dispose();
  115674. this._groundMirror = null;
  115675. }
  115676. if (this._scene.environmentTexture) {
  115677. if (this._options.environmentTexture != newOptions.environmentTexture) {
  115678. this._scene.environmentTexture.dispose();
  115679. }
  115680. }
  115681. this._options = newOptions;
  115682. this._setupBackground();
  115683. this._setupImageProcessing();
  115684. };
  115685. /**
  115686. * Sets the primary color of all the available elements.
  115687. * @param color the main color to affect to the ground and the background
  115688. */
  115689. EnvironmentHelper.prototype.setMainColor = function (color) {
  115690. if (this.groundMaterial) {
  115691. this.groundMaterial.primaryColor = color;
  115692. }
  115693. if (this.skyboxMaterial) {
  115694. this.skyboxMaterial.primaryColor = color;
  115695. }
  115696. if (this.groundMirror) {
  115697. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  115698. }
  115699. };
  115700. /**
  115701. * Setup the image processing according to the specified options.
  115702. */
  115703. EnvironmentHelper.prototype._setupImageProcessing = function () {
  115704. if (this._options.setupImageProcessing) {
  115705. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  115706. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  115707. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  115708. this._setupEnvironmentTexture();
  115709. }
  115710. };
  115711. /**
  115712. * Setup the environment texture according to the specified options.
  115713. */
  115714. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  115715. if (this._scene.environmentTexture) {
  115716. return;
  115717. }
  115718. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  115719. this._scene.environmentTexture = this._options.environmentTexture;
  115720. return;
  115721. }
  115722. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  115723. this._scene.environmentTexture = environmentTexture;
  115724. };
  115725. /**
  115726. * Setup the background according to the specified options.
  115727. */
  115728. EnvironmentHelper.prototype._setupBackground = function () {
  115729. if (!this._rootMesh) {
  115730. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  115731. }
  115732. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  115733. var sceneSize = this._getSceneSize();
  115734. if (this._options.createGround) {
  115735. this._setupGround(sceneSize);
  115736. this._setupGroundMaterial();
  115737. this._setupGroundDiffuseTexture();
  115738. if (this._options.enableGroundMirror) {
  115739. this._setupGroundMirrorTexture(sceneSize);
  115740. }
  115741. this._setupMirrorInGroundMaterial();
  115742. }
  115743. if (this._options.createSkybox) {
  115744. this._setupSkybox(sceneSize);
  115745. this._setupSkyboxMaterial();
  115746. this._setupSkyboxReflectionTexture();
  115747. }
  115748. this._rootMesh.position.x = sceneSize.rootPosition.x;
  115749. this._rootMesh.position.z = sceneSize.rootPosition.z;
  115750. this._rootMesh.position.y = sceneSize.rootPosition.y;
  115751. };
  115752. /**
  115753. * Get the scene sizes according to the setup.
  115754. */
  115755. EnvironmentHelper.prototype._getSceneSize = function () {
  115756. var _this = this;
  115757. var groundSize = this._options.groundSize;
  115758. var skyboxSize = this._options.skyboxSize;
  115759. var rootPosition = this._options.rootPosition;
  115760. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  115761. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  115762. }
  115763. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  115764. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  115765. });
  115766. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  115767. if (this._options.sizeAuto) {
  115768. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  115769. this._scene.activeCamera.upperRadiusLimit) {
  115770. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  115771. skyboxSize = groundSize;
  115772. }
  115773. var sceneDiagonalLenght = sceneDiagonal.length();
  115774. if (sceneDiagonalLenght > groundSize) {
  115775. groundSize = sceneDiagonalLenght * 2;
  115776. skyboxSize = groundSize;
  115777. }
  115778. // 10 % bigger.
  115779. groundSize *= 1.1;
  115780. skyboxSize *= 1.5;
  115781. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  115782. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  115783. }
  115784. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  115785. };
  115786. /**
  115787. * Setup the ground according to the specified options.
  115788. */
  115789. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  115790. var _this = this;
  115791. if (!this._ground || this._ground.isDisposed()) {
  115792. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  115793. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  115794. this._ground.parent = this._rootMesh;
  115795. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  115796. }
  115797. this._ground.receiveShadows = this._options.enableGroundShadow;
  115798. };
  115799. /**
  115800. * Setup the ground material according to the specified options.
  115801. */
  115802. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  115803. if (!this._groundMaterial) {
  115804. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  115805. }
  115806. this._groundMaterial.alpha = this._options.groundOpacity;
  115807. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  115808. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  115809. this._groundMaterial.primaryColor = this._options.groundColor;
  115810. this._groundMaterial.useRGBColor = false;
  115811. this._groundMaterial.enableNoise = true;
  115812. if (this._ground) {
  115813. this._ground.material = this._groundMaterial;
  115814. }
  115815. };
  115816. /**
  115817. * Setup the ground diffuse texture according to the specified options.
  115818. */
  115819. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  115820. if (!this._groundMaterial) {
  115821. return;
  115822. }
  115823. if (this._groundTexture) {
  115824. return;
  115825. }
  115826. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  115827. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  115828. return;
  115829. }
  115830. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  115831. diffuseTexture.gammaSpace = false;
  115832. diffuseTexture.hasAlpha = true;
  115833. this._groundMaterial.diffuseTexture = diffuseTexture;
  115834. };
  115835. /**
  115836. * Setup the ground mirror texture according to the specified options.
  115837. */
  115838. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  115839. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  115840. if (!this._groundMirror) {
  115841. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  115842. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  115843. this._groundMirror.anisotropicFilteringLevel = 1;
  115844. this._groundMirror.wrapU = wrapping;
  115845. this._groundMirror.wrapV = wrapping;
  115846. this._groundMirror.gammaSpace = false;
  115847. if (this._groundMirror.renderList) {
  115848. for (var i = 0; i < this._scene.meshes.length; i++) {
  115849. var mesh = this._scene.meshes[i];
  115850. if (mesh !== this._ground &&
  115851. mesh !== this._skybox &&
  115852. mesh !== this._rootMesh) {
  115853. this._groundMirror.renderList.push(mesh);
  115854. }
  115855. }
  115856. }
  115857. }
  115858. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  115859. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  115860. };
  115861. /**
  115862. * Setup the ground to receive the mirror texture.
  115863. */
  115864. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  115865. if (this._groundMaterial) {
  115866. this._groundMaterial.reflectionTexture = this._groundMirror;
  115867. this._groundMaterial.reflectionFresnel = true;
  115868. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  115869. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  115870. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  115871. }
  115872. };
  115873. /**
  115874. * Setup the skybox according to the specified options.
  115875. */
  115876. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  115877. var _this = this;
  115878. if (!this._skybox || this._skybox.isDisposed()) {
  115879. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  115880. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  115881. }
  115882. this._skybox.parent = this._rootMesh;
  115883. };
  115884. /**
  115885. * Setup the skybox material according to the specified options.
  115886. */
  115887. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  115888. if (!this._skybox) {
  115889. return;
  115890. }
  115891. if (!this._skyboxMaterial) {
  115892. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  115893. }
  115894. this._skyboxMaterial.useRGBColor = false;
  115895. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  115896. this._skyboxMaterial.enableNoise = true;
  115897. this._skybox.material = this._skyboxMaterial;
  115898. };
  115899. /**
  115900. * Setup the skybox reflection texture according to the specified options.
  115901. */
  115902. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  115903. if (!this._skyboxMaterial) {
  115904. return;
  115905. }
  115906. if (this._skyboxTexture) {
  115907. return;
  115908. }
  115909. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  115910. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  115911. return;
  115912. }
  115913. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  115914. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  115915. this._skyboxTexture.gammaSpace = false;
  115916. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  115917. };
  115918. /**
  115919. * Dispose all the elements created by the Helper.
  115920. */
  115921. EnvironmentHelper.prototype.dispose = function () {
  115922. if (this._groundMaterial) {
  115923. this._groundMaterial.dispose(true, true);
  115924. }
  115925. if (this._skyboxMaterial) {
  115926. this._skyboxMaterial.dispose(true, true);
  115927. }
  115928. this._rootMesh.dispose(false);
  115929. };
  115930. /**
  115931. * Default ground texture URL.
  115932. */
  115933. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  115934. /**
  115935. * Default skybox texture URL.
  115936. */
  115937. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  115938. /**
  115939. * Default environment texture URL.
  115940. */
  115941. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  115942. return EnvironmentHelper;
  115943. }());
  115944. BABYLON.EnvironmentHelper = EnvironmentHelper;
  115945. })(BABYLON || (BABYLON = {}));
  115946. //# sourceMappingURL=babylon.environmentHelper.js.map
  115947. var BABYLON;
  115948. (function (BABYLON) {
  115949. /** Internal class used to store shapes for emitters */
  115950. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  115951. function ParticleSystemSetEmitterCreationOptions() {
  115952. }
  115953. return ParticleSystemSetEmitterCreationOptions;
  115954. }());
  115955. /**
  115956. * Represents a set of particle systems working together to create a specific effect
  115957. */
  115958. var ParticleSystemSet = /** @class */ (function () {
  115959. function ParticleSystemSet() {
  115960. /**
  115961. * Gets the particle system list
  115962. */
  115963. this.systems = new Array();
  115964. }
  115965. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  115966. /**
  115967. * Gets the emitter node used with this set
  115968. */
  115969. get: function () {
  115970. return this._emitterNode;
  115971. },
  115972. enumerable: true,
  115973. configurable: true
  115974. });
  115975. /**
  115976. * Creates a new emitter mesh as a sphere
  115977. * @param options defines the options used to create the sphere
  115978. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  115979. * @param scene defines the hosting scene
  115980. */
  115981. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  115982. if (this._emitterNode) {
  115983. this._emitterNode.dispose();
  115984. }
  115985. this._emitterCreationOptions = {
  115986. kind: "Sphere",
  115987. options: options,
  115988. renderingGroupId: renderingGroupId
  115989. };
  115990. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  115991. emitterMesh.renderingGroupId = renderingGroupId;
  115992. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  115993. material.emissiveColor = options.color;
  115994. emitterMesh.material = material;
  115995. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  115996. var system = _a[_i];
  115997. system.emitter = emitterMesh;
  115998. }
  115999. this._emitterNode = emitterMesh;
  116000. };
  116001. /**
  116002. * Starts all particle systems of the set
  116003. * @param emitter defines an optional mesh to use as emitter for the particle systems
  116004. */
  116005. ParticleSystemSet.prototype.start = function (emitter) {
  116006. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  116007. var system = _a[_i];
  116008. if (emitter) {
  116009. system.emitter = emitter;
  116010. }
  116011. system.start();
  116012. }
  116013. };
  116014. /**
  116015. * Release all associated resources
  116016. */
  116017. ParticleSystemSet.prototype.dispose = function () {
  116018. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  116019. var system = _a[_i];
  116020. system.dispose();
  116021. }
  116022. this.systems = [];
  116023. if (this._emitterNode) {
  116024. this._emitterNode.dispose();
  116025. this._emitterNode = null;
  116026. }
  116027. };
  116028. /**
  116029. * Serialize the set into a JSON compatible object
  116030. * @returns a JSON compatible representation of the set
  116031. */
  116032. ParticleSystemSet.prototype.serialize = function () {
  116033. var result = {};
  116034. result.systems = [];
  116035. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  116036. var system = _a[_i];
  116037. result.systems.push(system.serialize());
  116038. }
  116039. if (this._emitterNode) {
  116040. result.emitter = this._emitterCreationOptions;
  116041. }
  116042. return result;
  116043. };
  116044. /**
  116045. * Parse a new ParticleSystemSet from a serialized source
  116046. * @param data defines a JSON compatible representation of the set
  116047. * @param scene defines the hosting scene
  116048. * @param gpu defines if we want GPU particles or CPU particles
  116049. * @returns a new ParticleSystemSet
  116050. */
  116051. ParticleSystemSet.Parse = function (data, scene, gpu) {
  116052. if (gpu === void 0) { gpu = false; }
  116053. var result = new ParticleSystemSet();
  116054. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  116055. scene = scene || BABYLON.Engine.LastCreatedScene;
  116056. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  116057. var system = _a[_i];
  116058. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  116059. }
  116060. if (data.emitter) {
  116061. var options = data.emitter.options;
  116062. switch (data.emitter.kind) {
  116063. case "Sphere":
  116064. result.setEmitterAsSphere({
  116065. diameter: options.diameter,
  116066. segments: options.segments,
  116067. color: BABYLON.Color3.FromArray(options.color)
  116068. }, data.emitter.renderingGroupId, scene);
  116069. break;
  116070. }
  116071. }
  116072. return result;
  116073. };
  116074. return ParticleSystemSet;
  116075. }());
  116076. BABYLON.ParticleSystemSet = ParticleSystemSet;
  116077. })(BABYLON || (BABYLON = {}));
  116078. //# sourceMappingURL=babylon.particleSystemSet.js.map
  116079. var BABYLON;
  116080. (function (BABYLON) {
  116081. /**
  116082. * This class is made for on one-liner static method to help creating particle system set.
  116083. */
  116084. var ParticleHelper = /** @class */ (function () {
  116085. function ParticleHelper() {
  116086. }
  116087. /**
  116088. * Create a default particle system that you can tweak
  116089. * @param emitter defines the emitter to use
  116090. * @param capacity defines the system capacity (default is 500 particles)
  116091. * @param scene defines the hosting scene
  116092. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  116093. * @returns the new Particle system
  116094. */
  116095. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  116096. if (capacity === void 0) { capacity = 500; }
  116097. if (useGPU === void 0) { useGPU = false; }
  116098. var system;
  116099. if (useGPU) {
  116100. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  116101. }
  116102. else {
  116103. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  116104. }
  116105. system.emitter = emitter;
  116106. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  116107. system.createConeEmitter(0.1, Math.PI / 4);
  116108. // Particle color
  116109. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  116110. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  116111. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  116112. // Particle Size
  116113. system.minSize = 0.1;
  116114. system.maxSize = 0.1;
  116115. // Emission speed
  116116. system.minEmitPower = 2;
  116117. system.maxEmitPower = 2;
  116118. // Update speed
  116119. system.updateSpeed = 1 / 60;
  116120. system.emitRate = 30;
  116121. return system;
  116122. };
  116123. /**
  116124. * This is the main static method (one-liner) of this helper to create different particle systems
  116125. * @param type This string represents the type to the particle system to create
  116126. * @param scene The scene where the particle system should live
  116127. * @param gpu If the system will use gpu
  116128. * @returns the ParticleSystemSet created
  116129. */
  116130. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  116131. if (gpu === void 0) { gpu = false; }
  116132. if (!scene) {
  116133. scene = BABYLON.Engine.LastCreatedScene;
  116134. }
  116135. var token = {};
  116136. scene._addPendingData(token);
  116137. return new Promise(function (resolve, reject) {
  116138. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  116139. scene._removePendingData(token);
  116140. return reject("Particle system with GPU is not supported.");
  116141. }
  116142. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  116143. scene._removePendingData(token);
  116144. var newData = JSON.parse(data.toString());
  116145. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  116146. }, undefined, undefined, undefined, function (req, exception) {
  116147. scene._removePendingData(token);
  116148. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  116149. });
  116150. });
  116151. };
  116152. /**
  116153. * Static function used to export a particle system to a ParticleSystemSet variable.
  116154. * Please note that the emitter shape is not exported
  116155. * @param systems defines the particle systems to export
  116156. * @returns the created particle system set
  116157. */
  116158. ParticleHelper.ExportSet = function (systems) {
  116159. var set = new BABYLON.ParticleSystemSet();
  116160. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  116161. var system = systems_1[_i];
  116162. set.systems.push(system);
  116163. }
  116164. return set;
  116165. };
  116166. /**
  116167. * Gets or sets base Assets URL
  116168. */
  116169. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  116170. return ParticleHelper;
  116171. }());
  116172. BABYLON.ParticleHelper = ParticleHelper;
  116173. })(BABYLON || (BABYLON = {}));
  116174. //# sourceMappingURL=babylon.particleHelper.js.map
  116175. var BABYLON;
  116176. (function (BABYLON) {
  116177. /**
  116178. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  116179. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  116180. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  116181. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  116182. */
  116183. var VideoDome = /** @class */ (function (_super) {
  116184. __extends(VideoDome, _super);
  116185. /**
  116186. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  116187. * @param name Element's name, child elements will append suffixes for their own names.
  116188. * @param urlsOrVideo defines the url(s) or the video element to use
  116189. * @param options An object containing optional or exposed sub element properties
  116190. */
  116191. function VideoDome(name, urlsOrVideo, options, scene) {
  116192. var _this = _super.call(this, name, scene) || this;
  116193. _this._useDirectMapping = false;
  116194. // set defaults and manage values
  116195. name = name || "videoDome";
  116196. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  116197. options.clickToPlay = Boolean(options.clickToPlay);
  116198. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  116199. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  116200. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  116201. if (options.useDirectMapping === undefined) {
  116202. _this._useDirectMapping = true;
  116203. }
  116204. else {
  116205. _this._useDirectMapping = options.useDirectMapping;
  116206. }
  116207. _this._setReady(false);
  116208. // create
  116209. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  116210. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  116211. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  116212. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  116213. texture.onLoadObservable.addOnce(function () {
  116214. _this._setReady(true);
  116215. });
  116216. // configure material
  116217. material.useEquirectangularFOV = true;
  116218. material.fovMultiplier = 1.0;
  116219. material.opacityFresnel = false;
  116220. if (_this._useDirectMapping) {
  116221. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116222. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116223. material.diffuseTexture = texture;
  116224. }
  116225. else {
  116226. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  116227. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116228. material.reflectionTexture = texture;
  116229. }
  116230. // configure mesh
  116231. _this._mesh.material = material;
  116232. _this._mesh.parent = _this;
  116233. // optional configuration
  116234. if (options.clickToPlay) {
  116235. scene.onPointerUp = function () {
  116236. _this._videoTexture.video.play();
  116237. };
  116238. }
  116239. return _this;
  116240. }
  116241. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  116242. /**
  116243. * Gets the video texture being displayed on the sphere
  116244. */
  116245. get: function () {
  116246. return this._videoTexture;
  116247. },
  116248. enumerable: true,
  116249. configurable: true
  116250. });
  116251. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  116252. /**
  116253. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  116254. * Also see the options.resolution property.
  116255. */
  116256. get: function () {
  116257. return this._material.fovMultiplier;
  116258. },
  116259. set: function (value) {
  116260. this._material.fovMultiplier = value;
  116261. },
  116262. enumerable: true,
  116263. configurable: true
  116264. });
  116265. /**
  116266. * Releases resources associated with this node.
  116267. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  116268. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  116269. */
  116270. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  116271. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  116272. this._videoTexture.dispose();
  116273. this._mesh.dispose();
  116274. this._material.dispose();
  116275. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  116276. };
  116277. return VideoDome;
  116278. }(BABYLON.TransformNode));
  116279. BABYLON.VideoDome = VideoDome;
  116280. })(BABYLON || (BABYLON = {}));
  116281. //# sourceMappingURL=babylon.videoDome.js.map
  116282. var BABYLON;
  116283. (function (BABYLON) {
  116284. /**
  116285. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  116286. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  116287. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  116288. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  116289. */
  116290. var PhotoDome = /** @class */ (function (_super) {
  116291. __extends(PhotoDome, _super);
  116292. /**
  116293. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  116294. * @param name Element's name, child elements will append suffixes for their own names.
  116295. * @param urlsOfPhoto defines the url of the photo to display
  116296. * @param options defines an object containing optional or exposed sub element properties
  116297. * @param onError defines a callback called when an error occured while loading the texture
  116298. */
  116299. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  116300. if (onError === void 0) { onError = null; }
  116301. var _this = _super.call(this, name, scene) || this;
  116302. _this._useDirectMapping = false;
  116303. /**
  116304. * Observable raised when an error occured while loading the 360 image
  116305. */
  116306. _this.onLoadErrorObservable = new BABYLON.Observable();
  116307. // set defaults and manage values
  116308. name = name || "photoDome";
  116309. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  116310. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  116311. if (options.useDirectMapping === undefined) {
  116312. _this._useDirectMapping = true;
  116313. }
  116314. else {
  116315. _this._useDirectMapping = options.useDirectMapping;
  116316. }
  116317. _this._setReady(false);
  116318. // create
  116319. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  116320. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  116321. // configure material
  116322. material.opacityFresnel = false;
  116323. material.useEquirectangularFOV = true;
  116324. material.fovMultiplier = 1.0;
  116325. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  116326. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  116327. if (onError) {
  116328. onError(message, exception);
  116329. }
  116330. });
  116331. _this.photoTexture.onLoadObservable.addOnce(function () {
  116332. _this._setReady(true);
  116333. });
  116334. // configure mesh
  116335. _this._mesh.material = material;
  116336. _this._mesh.parent = _this;
  116337. return _this;
  116338. }
  116339. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  116340. /**
  116341. * Gets or sets the texture being displayed on the sphere
  116342. */
  116343. get: function () {
  116344. return this._photoTexture;
  116345. },
  116346. set: function (value) {
  116347. if (this._photoTexture === value) {
  116348. return;
  116349. }
  116350. this._photoTexture = value;
  116351. if (this._useDirectMapping) {
  116352. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116353. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116354. this._material.diffuseTexture = this._photoTexture;
  116355. }
  116356. else {
  116357. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  116358. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116359. this._material.reflectionTexture = this._photoTexture;
  116360. }
  116361. },
  116362. enumerable: true,
  116363. configurable: true
  116364. });
  116365. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  116366. /**
  116367. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  116368. * Also see the options.resolution property.
  116369. */
  116370. get: function () {
  116371. return this._material.fovMultiplier;
  116372. },
  116373. set: function (value) {
  116374. this._material.fovMultiplier = value;
  116375. },
  116376. enumerable: true,
  116377. configurable: true
  116378. });
  116379. /**
  116380. * Releases resources associated with this node.
  116381. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  116382. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  116383. */
  116384. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  116385. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  116386. this._photoTexture.dispose();
  116387. this._mesh.dispose();
  116388. this._material.dispose();
  116389. this.onLoadErrorObservable.clear();
  116390. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  116391. };
  116392. return PhotoDome;
  116393. }(BABYLON.TransformNode));
  116394. BABYLON.PhotoDome = PhotoDome;
  116395. })(BABYLON || (BABYLON = {}));
  116396. //# sourceMappingURL=babylon.photoDome.js.map
  116397. var BABYLON;
  116398. (function (BABYLON) {
  116399. /** @hidden */
  116400. var _OcclusionDataStorage = /** @class */ (function () {
  116401. function _OcclusionDataStorage() {
  116402. /** @hidden */
  116403. this.occlusionInternalRetryCounter = 0;
  116404. /** @hidden */
  116405. this.isOcclusionQueryInProgress = false;
  116406. /** @hidden */
  116407. this.isOccluded = false;
  116408. /** @hidden */
  116409. this.occlusionRetryCount = -1;
  116410. /** @hidden */
  116411. this.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE;
  116412. /** @hidden */
  116413. this.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  116414. }
  116415. return _OcclusionDataStorage;
  116416. }());
  116417. BABYLON.Engine.prototype.createQuery = function () {
  116418. return this._gl.createQuery();
  116419. };
  116420. BABYLON.Engine.prototype.deleteQuery = function (query) {
  116421. this._gl.deleteQuery(query);
  116422. return this;
  116423. };
  116424. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  116425. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  116426. };
  116427. BABYLON.Engine.prototype.getQueryResult = function (query) {
  116428. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  116429. };
  116430. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  116431. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  116432. this._gl.beginQuery(glAlgorithm, query);
  116433. return this;
  116434. };
  116435. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  116436. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  116437. this._gl.endQuery(glAlgorithm);
  116438. return this;
  116439. };
  116440. BABYLON.Engine.prototype._createTimeQuery = function () {
  116441. var timerQuery = this.getCaps().timerQuery;
  116442. if (timerQuery.createQueryEXT) {
  116443. return timerQuery.createQueryEXT();
  116444. }
  116445. return this.createQuery();
  116446. };
  116447. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  116448. var timerQuery = this.getCaps().timerQuery;
  116449. if (timerQuery.deleteQueryEXT) {
  116450. timerQuery.deleteQueryEXT(query);
  116451. return;
  116452. }
  116453. this.deleteQuery(query);
  116454. };
  116455. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  116456. var timerQuery = this.getCaps().timerQuery;
  116457. if (timerQuery.getQueryObjectEXT) {
  116458. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  116459. }
  116460. return this.getQueryResult(query);
  116461. };
  116462. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  116463. var timerQuery = this.getCaps().timerQuery;
  116464. if (timerQuery.getQueryObjectEXT) {
  116465. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  116466. }
  116467. return this.isQueryResultAvailable(query);
  116468. };
  116469. BABYLON.Engine.prototype.startTimeQuery = function () {
  116470. var caps = this.getCaps();
  116471. var timerQuery = caps.timerQuery;
  116472. if (!timerQuery) {
  116473. return null;
  116474. }
  116475. var token = new BABYLON._TimeToken();
  116476. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  116477. if (caps.canUseTimestampForTimerQuery) {
  116478. token._startTimeQuery = this._createTimeQuery();
  116479. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  116480. }
  116481. else {
  116482. if (this._currentNonTimestampToken) {
  116483. return this._currentNonTimestampToken;
  116484. }
  116485. token._timeElapsedQuery = this._createTimeQuery();
  116486. if (timerQuery.beginQueryEXT) {
  116487. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  116488. }
  116489. else {
  116490. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  116491. }
  116492. this._currentNonTimestampToken = token;
  116493. }
  116494. return token;
  116495. };
  116496. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  116497. var caps = this.getCaps();
  116498. var timerQuery = caps.timerQuery;
  116499. if (!timerQuery || !token) {
  116500. return -1;
  116501. }
  116502. if (caps.canUseTimestampForTimerQuery) {
  116503. if (!token._startTimeQuery) {
  116504. return -1;
  116505. }
  116506. if (!token._endTimeQuery) {
  116507. token._endTimeQuery = this._createTimeQuery();
  116508. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  116509. }
  116510. }
  116511. else if (!token._timeElapsedQueryEnded) {
  116512. if (!token._timeElapsedQuery) {
  116513. return -1;
  116514. }
  116515. if (timerQuery.endQueryEXT) {
  116516. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  116517. }
  116518. else {
  116519. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  116520. }
  116521. token._timeElapsedQueryEnded = true;
  116522. }
  116523. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  116524. var available = false;
  116525. if (token._endTimeQuery) {
  116526. available = this._getTimeQueryAvailability(token._endTimeQuery);
  116527. }
  116528. else if (token._timeElapsedQuery) {
  116529. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  116530. }
  116531. if (available && !disjoint) {
  116532. var result = 0;
  116533. if (caps.canUseTimestampForTimerQuery) {
  116534. if (!token._startTimeQuery || !token._endTimeQuery) {
  116535. return -1;
  116536. }
  116537. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  116538. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  116539. result = timeEnd - timeStart;
  116540. this._deleteTimeQuery(token._startTimeQuery);
  116541. this._deleteTimeQuery(token._endTimeQuery);
  116542. token._startTimeQuery = null;
  116543. token._endTimeQuery = null;
  116544. }
  116545. else {
  116546. if (!token._timeElapsedQuery) {
  116547. return -1;
  116548. }
  116549. result = this._getTimeQueryResult(token._timeElapsedQuery);
  116550. this._deleteTimeQuery(token._timeElapsedQuery);
  116551. token._timeElapsedQuery = null;
  116552. token._timeElapsedQueryEnded = false;
  116553. this._currentNonTimestampToken = null;
  116554. }
  116555. return result;
  116556. }
  116557. return -1;
  116558. };
  116559. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  116560. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  116561. };
  116562. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  116563. get: function () {
  116564. return this._occlusionDataStorage.isOcclusionQueryInProgress;
  116565. },
  116566. enumerable: false,
  116567. configurable: true
  116568. });
  116569. Object.defineProperty(BABYLON.AbstractMesh.prototype, "_occlusionDataStorage", {
  116570. get: function () {
  116571. if (!this.__occlusionDataStorage) {
  116572. this.__occlusionDataStorage = new _OcclusionDataStorage();
  116573. }
  116574. return this.__occlusionDataStorage;
  116575. },
  116576. enumerable: false,
  116577. configurable: true
  116578. });
  116579. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOccluded", {
  116580. get: function () {
  116581. return this._occlusionDataStorage.isOccluded;
  116582. },
  116583. set: function (value) {
  116584. this._occlusionDataStorage.isOccluded = value;
  116585. },
  116586. enumerable: true,
  116587. configurable: true
  116588. });
  116589. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
  116590. get: function () {
  116591. return this._occlusionDataStorage.occlusionQueryAlgorithmType;
  116592. },
  116593. set: function (value) {
  116594. this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
  116595. },
  116596. enumerable: true,
  116597. configurable: true
  116598. });
  116599. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionType", {
  116600. get: function () {
  116601. return this._occlusionDataStorage.occlusionType;
  116602. },
  116603. set: function (value) {
  116604. this._occlusionDataStorage.occlusionType = value;
  116605. },
  116606. enumerable: true,
  116607. configurable: true
  116608. });
  116609. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionRetryCount", {
  116610. get: function () {
  116611. return this._occlusionDataStorage.occlusionRetryCount;
  116612. },
  116613. set: function (value) {
  116614. this._occlusionDataStorage.occlusionRetryCount = value;
  116615. },
  116616. enumerable: true,
  116617. configurable: true
  116618. });
  116619. // We also need to update AbstractMesh as there is a portion of the code there
  116620. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  116621. var dataStorage = this._occlusionDataStorage;
  116622. if (dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  116623. dataStorage.isOccluded = false;
  116624. return false;
  116625. }
  116626. var engine = this.getEngine();
  116627. if (engine.webGLVersion < 2) {
  116628. dataStorage.isOccluded = false;
  116629. return false;
  116630. }
  116631. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  116632. dataStorage.isOccluded = false;
  116633. return false;
  116634. }
  116635. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  116636. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  116637. if (isOcclusionQueryAvailable) {
  116638. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  116639. dataStorage.isOcclusionQueryInProgress = false;
  116640. dataStorage.occlusionInternalRetryCounter = 0;
  116641. dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true;
  116642. }
  116643. else {
  116644. dataStorage.occlusionInternalRetryCounter++;
  116645. if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
  116646. dataStorage.isOcclusionQueryInProgress = false;
  116647. dataStorage.occlusionInternalRetryCounter = 0;
  116648. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  116649. // if strict continue the last state of the object.
  116650. dataStorage.isOccluded = dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
  116651. }
  116652. else {
  116653. return false;
  116654. }
  116655. }
  116656. }
  116657. var scene = this.getScene();
  116658. if (scene.getBoundingBoxRenderer) {
  116659. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  116660. if (!this._occlusionQuery) {
  116661. this._occlusionQuery = engine.createQuery();
  116662. }
  116663. engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery);
  116664. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  116665. engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
  116666. this._occlusionDataStorage.isOcclusionQueryInProgress = true;
  116667. }
  116668. return dataStorage.isOccluded;
  116669. };
  116670. })(BABYLON || (BABYLON = {}));
  116671. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  116672. var BABYLON;
  116673. (function (BABYLON) {
  116674. /**
  116675. * Class used to generate noise procedural textures
  116676. */
  116677. var NoiseProceduralTexture = /** @class */ (function (_super) {
  116678. __extends(NoiseProceduralTexture, _super);
  116679. /**
  116680. * Creates a new NoiseProceduralTexture
  116681. * @param name defines the name fo the texture
  116682. * @param size defines the size of the texture (default is 256)
  116683. * @param scene defines the hosting scene
  116684. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  116685. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  116686. */
  116687. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  116688. if (size === void 0) { size = 256; }
  116689. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  116690. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  116691. _this._time = 0;
  116692. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  116693. _this.brightness = 0.2;
  116694. /** Defines the number of octaves to process */
  116695. _this.octaves = 3;
  116696. /** Defines the level of persistence (0.8 by default) */
  116697. _this.persistence = 0.8;
  116698. /** Gets or sets animation speed factor (default is 1) */
  116699. _this.animationSpeedFactor = 1;
  116700. _this._updateShaderUniforms();
  116701. return _this;
  116702. }
  116703. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  116704. var scene = this.getScene();
  116705. if (!scene) {
  116706. return;
  116707. }
  116708. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  116709. this.setFloat("brightness", this.brightness);
  116710. this.setFloat("persistence", this.persistence);
  116711. this.setFloat("timeScale", this._time);
  116712. };
  116713. NoiseProceduralTexture.prototype._getDefines = function () {
  116714. return "#define OCTAVES " + (this.octaves | 0);
  116715. };
  116716. /** Generate the current state of the procedural texture */
  116717. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  116718. this._updateShaderUniforms();
  116719. _super.prototype.render.call(this, useCameraPostProcess);
  116720. };
  116721. /**
  116722. * Serializes this noise procedural texture
  116723. * @returns a serialized noise procedural texture object
  116724. */
  116725. NoiseProceduralTexture.prototype.serialize = function () {
  116726. var serializationObject = {};
  116727. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  116728. serializationObject.brightness = this.brightness;
  116729. serializationObject.octaves = this.octaves;
  116730. serializationObject.persistence = this.persistence;
  116731. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  116732. serializationObject.size = this.getSize().width;
  116733. serializationObject.generateMipMaps = this._generateMipMaps;
  116734. return serializationObject;
  116735. };
  116736. /**
  116737. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  116738. * @param parsedTexture defines parsed texture data
  116739. * @param scene defines the current scene
  116740. * @param rootUrl defines the root URL containing noise procedural texture information
  116741. * @returns a parsed NoiseProceduralTexture
  116742. */
  116743. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  116744. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  116745. texture.brightness = parsedTexture.brightness;
  116746. texture.octaves = parsedTexture.octaves;
  116747. texture.persistence = parsedTexture.persistence;
  116748. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  116749. return texture;
  116750. };
  116751. return NoiseProceduralTexture;
  116752. }(BABYLON.ProceduralTexture));
  116753. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  116754. })(BABYLON || (BABYLON = {}));
  116755. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  116756. var __assign = (this && this.__assign) || function () {
  116757. __assign = Object.assign || function(t) {
  116758. for (var s, i = 1, n = arguments.length; i < n; i++) {
  116759. s = arguments[i];
  116760. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  116761. t[p] = s[p];
  116762. }
  116763. return t;
  116764. };
  116765. return __assign.apply(this, arguments);
  116766. };
  116767. var BABYLON;
  116768. (function (BABYLON) {
  116769. /**
  116770. * This can helps recording videos from BabylonJS.
  116771. * This is based on the available WebRTC functionalities of the browser.
  116772. *
  116773. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  116774. */
  116775. var VideoRecorder = /** @class */ (function () {
  116776. /**
  116777. * Create a new VideoCapture object which can help converting what you see in Babylon to
  116778. * a video file.
  116779. * @param engine Defines the BabylonJS Engine you wish to record
  116780. * @param options Defines options that can be used to customized the capture
  116781. */
  116782. function VideoRecorder(engine, options) {
  116783. if (options === void 0) { options = null; }
  116784. if (!VideoRecorder.IsSupported(engine)) {
  116785. throw "Your browser does not support recording so far.";
  116786. }
  116787. var canvas = engine.getRenderingCanvas();
  116788. if (!canvas) {
  116789. throw "The babylon engine must have a canvas to be recorded";
  116790. }
  116791. this._canvas = canvas;
  116792. this._canvas.isRecording = false;
  116793. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  116794. var stream = this._canvas.captureStream(this._options.fps);
  116795. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  116796. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  116797. this._mediaRecorder.onerror = this._handleError.bind(this);
  116798. this._mediaRecorder.onstop = this._handleStop.bind(this);
  116799. }
  116800. /**
  116801. * Returns wehther or not the VideoRecorder is available in your browser.
  116802. * @param engine Defines the Babylon Engine to check the support for
  116803. * @returns true if supported otherwise false
  116804. */
  116805. VideoRecorder.IsSupported = function (engine) {
  116806. var canvas = engine.getRenderingCanvas();
  116807. return (!!canvas && typeof canvas.captureStream === "function");
  116808. };
  116809. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  116810. /**
  116811. * True wether a recording is already in progress.
  116812. */
  116813. get: function () {
  116814. return !!this._canvas && this._canvas.isRecording;
  116815. },
  116816. enumerable: true,
  116817. configurable: true
  116818. });
  116819. /**
  116820. * Stops the current recording before the default capture timeout passed in the startRecording
  116821. * functions.
  116822. */
  116823. VideoRecorder.prototype.stopRecording = function () {
  116824. if (!this._canvas || !this._mediaRecorder) {
  116825. return;
  116826. }
  116827. if (!this.isRecording) {
  116828. return;
  116829. }
  116830. this._canvas.isRecording = false;
  116831. this._mediaRecorder.stop();
  116832. };
  116833. /**
  116834. * Starts recording the canvas for a max duration specified in parameters.
  116835. * @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.
  116836. * @param maxDuration Defines the maximum recording time in seconds.
  116837. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  116838. * @return a promise callback at the end of the recording with the video data in Blob.
  116839. */
  116840. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  116841. var _this = this;
  116842. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  116843. if (maxDuration === void 0) { maxDuration = 7; }
  116844. if (!this._canvas || !this._mediaRecorder) {
  116845. throw "Recorder has already been disposed";
  116846. }
  116847. if (this.isRecording) {
  116848. throw "Recording already in progress";
  116849. }
  116850. if (maxDuration > 0) {
  116851. setTimeout(function () {
  116852. _this.stopRecording();
  116853. }, maxDuration * 1000);
  116854. }
  116855. this._fileName = fileName;
  116856. this._recordedChunks = [];
  116857. this._resolve = null;
  116858. this._reject = null;
  116859. this._canvas.isRecording = true;
  116860. this._mediaRecorder.start(this._options.recordChunckSize);
  116861. return new Promise(function (resolve, reject) {
  116862. _this._resolve = resolve;
  116863. _this._reject = reject;
  116864. });
  116865. };
  116866. /**
  116867. * Releases internal resources used during the recording.
  116868. */
  116869. VideoRecorder.prototype.dispose = function () {
  116870. this._canvas = null;
  116871. this._mediaRecorder = null;
  116872. this._recordedChunks = [];
  116873. this._fileName = null;
  116874. this._resolve = null;
  116875. this._reject = null;
  116876. };
  116877. VideoRecorder.prototype._handleDataAvailable = function (event) {
  116878. if (event.data.size > 0) {
  116879. this._recordedChunks.push(event.data);
  116880. }
  116881. };
  116882. VideoRecorder.prototype._handleError = function (event) {
  116883. this.stopRecording();
  116884. if (this._reject) {
  116885. this._reject(event.error);
  116886. }
  116887. else {
  116888. throw new event.error();
  116889. }
  116890. };
  116891. VideoRecorder.prototype._handleStop = function () {
  116892. this.stopRecording();
  116893. var superBuffer = new Blob(this._recordedChunks);
  116894. if (this._resolve) {
  116895. this._resolve(superBuffer);
  116896. }
  116897. window.URL.createObjectURL(superBuffer);
  116898. if (this._fileName) {
  116899. BABYLON.Tools.Download(superBuffer, this._fileName);
  116900. }
  116901. };
  116902. VideoRecorder._defaultOptions = {
  116903. mimeType: "video/webm",
  116904. fps: 25,
  116905. recordChunckSize: 3000
  116906. };
  116907. return VideoRecorder;
  116908. }());
  116909. BABYLON.VideoRecorder = VideoRecorder;
  116910. })(BABYLON || (BABYLON = {}));
  116911. //# sourceMappingURL=babylon.videoRecorder.js.map
  116912. var BABYLON;
  116913. (function (BABYLON) {
  116914. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  116915. if (replace === void 0) { replace = false; }
  116916. // Dispose existing light in replace mode.
  116917. if (replace) {
  116918. if (this.lights) {
  116919. for (var i = 0; i < this.lights.length; i++) {
  116920. this.lights[i].dispose();
  116921. }
  116922. }
  116923. }
  116924. // Light
  116925. if (this.lights.length === 0) {
  116926. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  116927. }
  116928. };
  116929. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  116930. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  116931. if (replace === void 0) { replace = false; }
  116932. if (attachCameraControls === void 0) { attachCameraControls = false; }
  116933. // Dispose existing camera in replace mode.
  116934. if (replace) {
  116935. if (this.activeCamera) {
  116936. this.activeCamera.dispose();
  116937. this.activeCamera = null;
  116938. }
  116939. }
  116940. // Camera
  116941. if (!this.activeCamera) {
  116942. var worldExtends = this.getWorldExtends();
  116943. var worldSize = worldExtends.max.subtract(worldExtends.min);
  116944. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  116945. var camera;
  116946. var radius = worldSize.length() * 1.5;
  116947. // empty scene scenario!
  116948. if (!isFinite(radius)) {
  116949. radius = 1;
  116950. worldCenter.copyFromFloats(0, 0, 0);
  116951. }
  116952. if (createArcRotateCamera) {
  116953. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  116954. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  116955. arcRotateCamera.wheelPrecision = 100 / radius;
  116956. camera = arcRotateCamera;
  116957. }
  116958. else {
  116959. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  116960. freeCamera.setTarget(worldCenter);
  116961. camera = freeCamera;
  116962. }
  116963. camera.minZ = radius * 0.01;
  116964. camera.maxZ = radius * 1000;
  116965. camera.speed = radius * 0.2;
  116966. this.activeCamera = camera;
  116967. var canvas = this.getEngine().getRenderingCanvas();
  116968. if (attachCameraControls && canvas) {
  116969. camera.attachControl(canvas);
  116970. }
  116971. }
  116972. };
  116973. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  116974. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  116975. if (replace === void 0) { replace = false; }
  116976. if (attachCameraControls === void 0) { attachCameraControls = false; }
  116977. this.createDefaultLight(replace);
  116978. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  116979. };
  116980. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  116981. if (pbr === void 0) { pbr = false; }
  116982. if (scale === void 0) { scale = 1000; }
  116983. if (blur === void 0) { blur = 0; }
  116984. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  116985. if (!environmentTexture) {
  116986. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  116987. return null;
  116988. }
  116989. if (setGlobalEnvTexture) {
  116990. if (environmentTexture) {
  116991. this.environmentTexture = environmentTexture;
  116992. }
  116993. }
  116994. // Skybox
  116995. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  116996. if (pbr) {
  116997. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  116998. hdrSkyboxMaterial.backFaceCulling = false;
  116999. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  117000. if (hdrSkyboxMaterial.reflectionTexture) {
  117001. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  117002. }
  117003. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  117004. hdrSkyboxMaterial.disableLighting = true;
  117005. hdrSkyboxMaterial.twoSidedLighting = true;
  117006. hdrSkybox.infiniteDistance = true;
  117007. hdrSkybox.material = hdrSkyboxMaterial;
  117008. }
  117009. else {
  117010. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  117011. skyboxMaterial.backFaceCulling = false;
  117012. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  117013. if (skyboxMaterial.reflectionTexture) {
  117014. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  117015. }
  117016. skyboxMaterial.disableLighting = true;
  117017. hdrSkybox.infiniteDistance = true;
  117018. hdrSkybox.material = skyboxMaterial;
  117019. }
  117020. return hdrSkybox;
  117021. };
  117022. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  117023. if (BABYLON.EnvironmentHelper) {
  117024. return new BABYLON.EnvironmentHelper(options, this);
  117025. }
  117026. return null;
  117027. };
  117028. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  117029. if (webVROptions === void 0) { webVROptions = {}; }
  117030. return new BABYLON.VRExperienceHelper(this, webVROptions);
  117031. };
  117032. })(BABYLON || (BABYLON = {}));
  117033. //# sourceMappingURL=babylon.sceneHelpers.js.map
  117034. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction; \n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\n\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nin vec3 direction;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \nvec4 textureColor=texture(textureSampler,vUV);\noutFragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\noutFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); \n#endif \n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\nin vec3 noiseCoordinates2;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\nout vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nfloat newAge=age+timeDelta; \n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(direction,0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#endif \nfloat ratio=clamp(mod(offsetAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n","noisePixelShader":"\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  117035. 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};"};